<?php
/**
 * Demo کامل ۷ نوع خدمت — از ثبت ویجت تا dispatch ارشد، SRD، فاکتور
 * http://localhost/acc-engine/run-service-seven-types.php
 *
 * C:\xampp\php\php.exe C:\xampp\htdocs\acc-engine\run-service-seven-types.php
 */
declare(strict_types=1);

define( 'ACC_BASE_PATH', __DIR__ );
define( 'ACC_PATH', __DIR__ . '/' );
define( 'ABSPATH', __DIR__ . '/' );
define( 'ACC_URL', '/acc-engine/' );

require_once __DIR__ . '/standalone/bootstrap.php';
require_once ACC_PATH . 'includes/helpers/svc-teams.php';
require_once ACC_PATH . 'includes/controllers/SR_Controller.php';
require_once ACC_PATH . 'includes/helpers/service-report-render.php';

/** @var wpdb $wpdb */
global $wpdb;

const DEMO_PASS = 'Demo@2026';

function seven_req( string $method, array $json = [], array $url = [] ): WP_REST_Request {
    $req = new WP_REST_Request( $method );
    $req->set_json_params( $json );
    $req->set_url_params( $url );
    return $req;
}

function seven_data( WP_REST_Response $res ): array {
    $d = $res->get_data();
    return is_array( $d ) ? $d : [ 'raw' => $d ];
}

function seven_act_as( int $uid ): void {
    global $wpdb;
    $row = $wpdb->get_row( $wpdb->prepare(
        "SELECT ID, user_login, display_name FROM {$wpdb->users} WHERE ID = %d", $uid
    ), ARRAY_A );
    $GLOBALS['acc_current_user'] = [
        'id'           => $uid,
        'username'     => $row['user_login'] ?? ( 'user_' . $uid ),
        'display_name' => $row['display_name'] ?? '',
        'roles'        => [ 'authenticated' ],
        'permissions'  => [ '*' ],
    ];
    $GLOBALS['acc_jwt_user_id'] = $uid;
}

function seven_reset(): void {
    $GLOBALS['acc_current_user'] = null;
    unset( $GLOBALS['acc_jwt_user_id'] );
}

function seven_ensure_user( string $login, string $display, string $email, string $role ): int {
    global $wpdb;
    $id = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT ID FROM {$wpdb->users} WHERE user_login = %s AND ID > 0", $login
    ) );
    if ( ! $id ) {
        $new_id = (int) $wpdb->get_var( "SELECT COALESCE( MAX( ID ), 0 ) + 1 FROM {$wpdb->users}" );
        $wpdb->insert( $wpdb->users, [
            'ID'              => $new_id,
            'user_login'      => $login,
            'user_pass'       => password_hash( DEMO_PASS, PASSWORD_BCRYPT ),
            'user_nicename'   => $login,
            'user_email'      => $email,
            'user_registered' => current_time( 'mysql' ),
            'display_name'    => $display,
        ] );
        $id = $new_id;
    }
    $role_id = (int) $wpdb->get_var( $wpdb->prepare(
        "SELECT id FROM {$wpdb->prefix}acl_roles WHERE slug = %s", $role
    ) );
    if ( $role_id && ! $wpdb->get_var( $wpdb->prepare(
        "SELECT id FROM {$wpdb->prefix}acl_user_roles WHERE user_id=%d AND role_id=%d AND scope_type='global'",
        $id, $role_id
    ) ) ) {
        $wpdb->insert( "{$wpdb->prefix}acl_user_roles", [
            'user_id' => $id, 'role_id' => $role_id, 'scope_type' => 'global', 'scope_id' => null,
        ] );
    }
    return $id;
}

function seven_srd_payload( string $service_type, array $customer, string $complaint, array $lines ): array {
    $svc_total = array_sum( array_column( $lines['service_lines'] ?? [], 'total' ) );
    $part_total = array_sum( array_column( $lines['part_lines'] ?? [], 'total' ) );
    $mat_total = array_sum( array_column( $lines['material_lines'] ?? [], 'total' ) );
    $extra_total = array_sum( array_column( $lines['extra_costs'] ?? [], 'amount' ) );
    $subtotal = $svc_total + $part_total + $mat_total + $extra_total;
    $discount = $lines['discount'] ?? 0;
    $tax = (int) round( ( $subtotal - $discount ) * 0.09 );
    $total = $subtotal - $discount + $tax;
    $paid = $lines['paid'] ?? 0;
    return array_merge( [
        'service_type'       => $service_type,
        'customer_name'      => $customer['name'],
        'company'            => $customer['company'],
        'phone'              => $customer['phone'],
        'email'              => $customer['email'],
        'address'            => $customer['address'],
        'site_label'         => $customer['site'],
        'complaint_text'     => $complaint,
        'diagnosis_result'   => $lines['diagnosis'] ?? 'بررسی و اقدام انجام شد.',
        'service_lines'      => $lines['service_lines'] ?? [],
        'part_lines'         => $lines['part_lines'] ?? [],
        'material_lines'     => $lines['material_lines'] ?? [],
        'extra_costs'        => $lines['extra_costs'] ?? [],
        'recommendations'    => $lines['recommendations'] ?? [ 'سرویس دوره‌ای پیشنهاد می‌شود.' ],
        'pm_offer'           => $lines['pm_offer'] ?? [ 'plan' => 'quarterly', 'selected' => false ],
        'subtotal_services'  => $svc_total,
        'subtotal_parts'     => $part_total,
        'subtotal_materials' => $mat_total,
        'subtotal_extra'     => $extra_total,
        'discount'           => $discount,
        'tax'                => $tax,
        'total'              => $total,
        'paid'               => $paid,
        'balance'            => max( 0, $total - $paid ),
        'tech_signature'     => 'رضا موسوی',
        'customer_signature' => 'امضای مشتری',
        'report_date'        => current_time( 'Y-m-d' ),
        'warehouse_id'       => 0,
    ], $lines['extra_fields'] ?? [] );
}

function seven_run_case(
    string $type,
    string $title,
    array $visitor_payload,
    array $srd_lines,
    int $senior_id,
    int $tech_id,
    ?callable $after_finalize = null
): array {
    global $wpdb;
    $steps = [];
    $scheduled = date( 'Y-m-d H:i:s', strtotime( '+1 day 10:00' ) );

    // ۱. ثبت درخواست
    seven_reset();
    $create = seven_data( SR_Controller::visitor_create_request( seven_req( 'POST', $visitor_payload ) ) );
    if ( empty( $create['success'] ) ) {
        throw new RuntimeException( $create['message'] ?? 'ثبت درخواست ناموفق' );
    }
    $d = $create['data'];
    $request_id = (int) $d['id'];
    $steps[] = [ 'step' => 'ثبت درخواست', 'tracking_code' => $d['tracking_code'] ];

    // ۲. Dispatch ارشد
    seven_act_as( $senior_id );
    seven_data( SR_Controller::assign_request( seven_req( 'POST', [
        'technician_id'  => $tech_id,
        'status'         => 'assigned',
        'scheduled_at'   => $scheduled,
        'dispatch_notes' => "دمو ۷نوع — {$title} — اولویت عادی",
    ], [ 'id' => $request_id ] ) ) );
    $steps[] = [ 'step' => 'Dispatch ارشد', 'technician_id' => $tech_id ];

    // ۳. شروع کار
    seven_act_as( $tech_id );
    seven_data( SR_Controller::update_request( seven_req( 'PUT', [ 'status' => 'in_progress' ], [ 'id' => $request_id ] ) ) );
    $steps[] = [ 'step' => 'شروع کار میدانی' ];

    // ۴. SRD
    $create_rpt = seven_data( SR_Controller::create_report( seven_req( 'POST', [ 'request_id' => $request_id ] ) ) );
    if ( empty( $create_rpt['success'] ) ) {
        throw new RuntimeException( 'ایجاد SRD ناموفق' );
    }
    $report_id = (int) $create_rpt['data']['id'];
    $payload = seven_srd_payload( $type, [
        'name'    => $visitor_payload['name'],
        'company' => $visitor_payload['company'] ?? '',
        'phone'   => $visitor_payload['phone'],
        'email'   => $visitor_payload['email'] ?? '',
        'address' => $visitor_payload['address'] ?? '',
        'site'    => $visitor_payload['site_label'],
    ], $visitor_payload['complaint_text'] ?? '', $srd_lines );

    seven_data( SR_Controller::save_report( seven_req( 'PUT', $payload, [ 'id' => $report_id ] ) ) );
    $fin = seven_data( SR_Controller::finalize_report( seven_req( 'POST', $payload, [ 'id' => $report_id ] ) ) );
    if ( empty( $fin['success'] ) ) {
        throw new RuntimeException( $fin['message'] ?? 'Finalize ناموفق' );
    }
    $rpt = $fin['data'] ?? [];
    $steps[] = [
        'step'       => 'صدور فاکتور / SRD نهایی',
        'report_no'  => $rpt['report_no'] ?? $create_rpt['data']['report_no'],
        'total'      => $rpt['total'] ?? $payload['total'],
        'balance'    => $rpt['balance'] ?? $payload['balance'],
        'public_url' => Service_Report_Render::public_url( $rpt['public_token'] ?? '' ),
    ];

    // ۵. بازبینی ارشد
    seven_act_as( $senior_id );
    seven_data( SR_Controller::senior_review_report( seven_req( 'POST', [
        'status' => 'approved',
        'note'   => "تأیید دمو — {$title}",
    ], [ 'id' => $report_id ] ) ) );
    $steps[] = [ 'step' => 'تأیید ارشد' ];

    if ( $after_finalize ) {
        $extra = $after_finalize( $request_id, $report_id, $d );
        if ( $extra ) {
            $steps[] = $extra;
        }
    }

    // ۶. پیگیری مشتری
    seven_reset();
    $track = seven_data( SR_Controller::visitor_track( seven_req( 'GET', [], [ 'code' => $d['tracking_code'] ] ) ) );
    $tl = $track['data']['timeline'] ?? [];

    seven_reset();
    return [
        'service_type'  => $type,
        'title'         => $title,
        'tracking_code' => $d['tracking_code'],
        'request_no'    => $d['request_no'] ?? '',
        'request_id'    => $request_id,
        'report_id'     => $report_id,
        'report_no'     => $rpt['report_no'] ?? '',
        'public_token'  => $rpt['public_token'] ?? '',
        'public_url'    => Service_Report_Render::public_url( $rpt['public_token'] ?? '' ),
        'total'         => $rpt['total'] ?? 0,
        'balance'       => $rpt['balance'] ?? 0,
        'timeline_count'=> count( $tl ),
        'timeline'      => $tl,
        'steps'         => $steps,
    ];
}

$base   = rtrim( ACC_URL, '/' );
$stamp  = date( 'Ymd_His' );
$log    = [];
$cases  = [];

$customer = [
    'name'    => 'آقای حسین کریمی',
    'company' => 'مجتمع غذایی سفره ایرانی',
    'phone'   => '09121234567',
    'email'   => 'demo-seven@safarhe.test',
    'address' => 'تهران، ولیعصر، پلاک ۱۲۴۵',
    'site'    => 'مجتمع سردخانه‌ای — آشپزخانه مرکزی',
];

$device_common = [
    'device_type'      => 'چیلر',
    'brand'            => 'Carrier',
    'model'            => '30RT',
    'serial_no'        => 'CR-7TYPES-' . substr( $stamp, -6 ),
    'capacity'         => '30 تن',
    'refrigerant'      => 'R404A',
    'install_location' => 'پشت‌بام — واحد ۲',
];

// کاربران
try {
    $senior_id = seven_ensure_user( 'svc_senior_demo', 'علی رضایی — ارشد', 'senior@test.local', 'service_senior' );
    $tech_id   = seven_ensure_user( 'svc_tech1_demo', 'رضا موسوی — میدانی', 'tech1@test.local', 'service_technician' );
    if ( Svc_Teams::table_exists() ) {
        Svc_Teams::add_team_member( $senior_id, $tech_id );
    }
} catch ( Throwable $e ) {
    $log[] = [ 'ok' => false, 'title' => 'کاربران', 'error' => $e->getMessage() ];
    goto render;
}

$session_base = 'seven_' . $stamp;

$definitions = [
    'phone_consult' => [
        'title' => 'مشاوره فنی',
        'visitor' => array_merge( $device_common, [
            'session_key' => $session_base . '_consult',
            'name' => $customer['name'], 'company' => $customer['company'],
            'phone' => $customer['phone'], 'email' => $customer['email'],
            'address' => $customer['address'], 'site_label' => $customer['site'],
            'service_type' => 'phone_consult',
            'complaint_text' => 'کمپرسور مدام قطع و وصل می‌شود. کد خطا E12 روی پنل.',
            'error_code' => 'E12', 'ambient_temp' => 32,
        ] ),
        'srd' => [
            'diagnosis' => 'مشاوره تلفنی: احتمال خرابی رله اورلود یا کمبود گاز.',
            'service_lines' => [ [ 'title' => 'مشاوره فنی تلفنی', 'qty' => 1, 'unit_price' => 850000, 'total' => 850000 ] ],
            'paid' => 850000, 'discount' => 0,
        ],
    ],
    'repair' => [
        'title' => 'تعمیر و سرویس',
        'visitor' => array_merge( $device_common, [
            'session_key' => $session_base . '_repair',
            'name' => $customer['name'], 'company' => $customer['company'],
            'phone' => $customer['phone'], 'email' => $customer['email'],
            'address' => $customer['address'], 'site_label' => $customer['site'],
            'service_type' => 'repair', 'priority' => 'urgent',
            'complaint_text' => 'کمپرسور هر ۲ ساعت خاموش می‌شود — اضطراری.',
        ] ),
        'srd' => [
            'diagnosis' => 'رله اورلود معیوب — تعویض انجام شد.',
            'service_lines' => [ [ 'title' => 'عیب‌یابی و تعمیر', 'qty' => 1, 'unit_price' => 3500000, 'total' => 3500000 ] ],
            'part_lines' => [ [ 'title' => 'رله اورلود', 'qty' => 1, 'unit_price' => 2800000, 'total' => 2800000 ] ],
            'paid' => 2000000, 'discount' => 300000,
        ],
    ],
    'pm' => [
        'title' => 'نگهداری PM',
        'visitor' => array_merge( $device_common, [
            'session_key' => $session_base . '_pm',
            'name' => $customer['name'], 'company' => $customer['company'],
            'phone' => $customer['phone'], 'email' => $customer['email'],
            'address' => $customer['address'], 'site_label' => $customer['site'],
            'service_type' => 'pm', 'pm_plan' => 'quarterly', 'operating_hours' => 12400,
            'complaint_text' => 'سرویس دوره‌ای سه‌ماهه چیلر.',
        ] ),
        'srd' => [
            'diagnosis' => 'PM انجام شد — فیلتر، روغن، بررسی فشار.',
            'service_lines' => [ [ 'title' => 'سرویس PM سه‌ماهه', 'qty' => 1, 'unit_price' => 4200000, 'total' => 4200000 ] ],
            'pm_offer' => [ 'plan' => 'quarterly', 'selected' => true ],
            'paid' => 0, 'discount' => 0,
        ],
    ],
    'parts_supply' => [
        'title' => 'تأمین قطعات',
        'visitor' => [
            'session_key' => $session_base . '_parts',
            'name' => $customer['name'], 'company' => $customer['company'],
            'phone' => $customer['phone'], 'email' => $customer['email'],
            'address' => $customer['address'], 'site_label' => $customer['site'],
            'service_type' => 'parts_supply',
            'device_type' => 'چیلر', 'brand' => 'Carrier', 'model' => '30RT',
            'part_number' => 'CAR-RLY-30RT-001', 'part_qty' => 2,
            'complaint_text' => 'نیاز به ۲ عدد رله اورلود اصلی.',
        ],
        'srd' => [
            'diagnosis' => 'قطعات تأمین و تحویل مشتری.',
            'service_lines' => [ [ 'title' => 'تأمین و ارسال قطعه', 'qty' => 1, 'unit_price' => 450000, 'total' => 450000 ] ],
            'part_lines' => [ [ 'title' => 'رله اورلود Carrier', 'qty' => 2, 'unit_price' => 2900000, 'total' => 5800000 ] ],
            'paid' => 3000000, 'discount' => 0,
        ],
        'after' => function ( int $req_id ) use ( $wpdb, $senior_id ) {
            $po = $wpdb->get_row( $wpdb->prepare(
                "SELECT id FROM {$wpdb->prefix}svc_parts_orders WHERE request_id=%d", $req_id
            ), ARRAY_A );
            if ( ! $po ) return null;
            seven_act_as( $senior_id );
            seven_data( SR_Controller::update_parts_order( seven_req( 'PUT', [
                'status' => 'quoted', 'quote_price' => 5800000, 'eta_days' => 3, 'notes' => 'موجود — ارسال ۳ روزه',
            ], [ 'id' => (int) $po['id'] ] ) ) );
            seven_data( SR_Controller::update_parts_order( seven_req( 'PUT', [
                'status' => 'delivered',
            ], [ 'id' => (int) $po['id'] ] ) ) );
            seven_reset();
            return [ 'step' => 'سفارش قطعه — استعلام و تحویل', 'parts_order_id' => (int) $po['id'] ];
        },
    ],
    'equipment_purchase' => [
        'title' => 'خرید تجهیزات',
        'visitor' => [
            'session_key' => $session_base . '_equip',
            'name' => $customer['name'], 'company' => $customer['company'],
            'phone' => $customer['phone'], 'email' => $customer['email'],
            'address' => $customer['address'], 'site_label' => $customer['site'],
            'service_type' => 'equipment_purchase',
            'project_city' => 'تهران', 'application' => 'سردخانه',
            'required_capacity' => '50 تن', 'budget_range' => '۸ تا ۱۲ میلیارد',
            'complaint_text' => 'نیاز به چیلر جدید برای توسعه سردخانه.',
        ],
        'srd' => [
            'diagnosis' => 'بازدید فنی و ارائه پیشنهاد تجهیز.',
            'service_lines' => [ [ 'title' => 'مشاوره و بازدید خرید تجهیز', 'qty' => 1, 'unit_price' => 5000000, 'total' => 5000000 ] ],
            'paid' => 0, 'discount' => 500000,
        ],
        'after' => function ( int $req_id ) use ( $wpdb, $senior_id ) {
            $eq = $wpdb->get_row( $wpdb->prepare(
                "SELECT id FROM {$wpdb->prefix}svc_equipment_inquiries WHERE request_id=%d", $req_id
            ), ARRAY_A );
            if ( ! $eq ) return null;
            seven_act_as( $senior_id );
            seven_data( SR_Controller::update_equipment_inquiry( seven_req( 'PUT', [
                'status' => 'quoted',
                'quote_options' => [
                    [ 'brand' => 'Carrier', 'model' => '30XA', 'capacity' => '50 تن', 'price' => 9800000000 ],
                    [ 'brand' => 'Trane', 'model' => 'RTAC', 'capacity' => '50 تن', 'price' => 10500000000 ],
                ],
            ], [ 'id' => (int) $eq['id'] ] ) ) );
            seven_reset();
            return [ 'step' => 'استعلام تجهیز — ۲ پیشنهاد قیمت', 'inquiry_id' => (int) $eq['id'] ];
        },
    ],
    'site_visit' => [
        'title' => 'بازدید کارشناس',
        'visitor' => array_merge( $device_common, [
            'session_key' => $session_base . '_visit',
            'name' => $customer['name'], 'company' => $customer['company'],
            'phone' => $customer['phone'], 'email' => $customer['email'],
            'address' => $customer['address'], 'site_label' => $customer['site'],
            'service_type' => 'site_visit',
            'complaint_text' => 'بازدید قبل از تعمیر اساسی — ارزیابی وضعیت چیلر.',
        ] ),
        'srd' => [
            'diagnosis' => 'بازدید انجام شد — نیاز به تعمیر رله و شارژ گاز.',
            'service_lines' => [ [ 'title' => 'بازدید کارشناس میدانی', 'qty' => 1, 'unit_price' => 1800000, 'total' => 1800000 ] ],
            'extra_costs' => [ [ 'title' => 'ایاب‌ذهاب', 'amount' => 350000 ] ],
            'paid' => 0, 'discount' => 0,
        ],
    ],
    'contract_support' => [
        'title' => 'پشتیبانی قراردادی',
        'visitor' => [
            'session_key' => $session_base . '_contract',
            'name' => $customer['name'], 'company' => $customer['company'],
            'phone' => $customer['phone'], 'email' => $customer['email'],
            'address' => $customer['address'], 'site_label' => $customer['site'],
            'service_type' => 'contract_support',
            'contract_no' => 'HVAC-1404-0088', 'company' => $customer['company'],
            'complaint_text' => 'درخواست سرویس اضطراری طبق قرارداد پشتیبانی سالانه.',
        ],
        'srd' => [
            'diagnosis' => 'اقدام طبق SLA قرارداد — تعویض سنسور دما.',
            'service_lines' => [ [ 'title' => 'سرویس قراردادی (SLA)', 'qty' => 1, 'unit_price' => 0, 'total' => 0 ] ],
            'part_lines' => [ [ 'title' => 'سنسور دما', 'qty' => 1, 'unit_price' => 1200000, 'total' => 1200000 ] ],
            'paid' => 1200000, 'discount' => 0,
        ],
    ],
];

foreach ( $definitions as $type => $def ) {
    try {
        $after = $def['after'] ?? null;
        $cases[] = seven_run_case(
            $type,
            $def['title'],
            $def['visitor'],
            $def['srd'],
            $senior_id,
            $tech_id,
            $after ? fn( $rid, $rpt, $d ) => $after( $rid ) : null
        );
        $log[] = [ 'ok' => true, 'title' => $def['title'], 'data' => end( $cases ) ];
    } catch ( Throwable $e ) {
        $log[] = [ 'ok' => false, 'title' => $def['title'], 'error' => $e->getMessage() ];
    }
}

$summary = [
    'customer_phone' => $customer['phone'],
    'customer_name'  => $customer['name'],
    'session_prefix' => $session_base,
    'cases_count'    => count( $cases ),
    'cases'          => array_map( fn( $c ) => [
        'type'          => $c['service_type'],
        'title'         => $c['title'],
        'tracking_code' => $c['tracking_code'],
        'report_no'     => $c['report_no'],
        'total'         => $c['total'],
        'balance'       => $c['balance'],
        'timeline_steps'=> $c['timeline_count'],
        'public_url'    => $c['public_url'],
    ], $cases ),
    'logins' => [
        'senior' => 'svc_senior_demo / ' . DEMO_PASS,
        'tech'   => 'svc_tech1_demo / ' . DEMO_PASS,
        'customer' => 'ویجت پیگیری با موبایل ' . $customer['phone'],
    ],
    'links' => [
        'portal'  => $base . '/service.php',
        'erp'     => $base . '/index.php#service',
        'docs'    => $base . '/docs/service/seven-types-result.json',
    ],
];

file_put_contents(
    __DIR__ . '/docs/service/seven-types-result.json',
    json_encode( [ 'summary' => $summary, 'cases' => $cases, 'log' => $log ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT )
);

render:
header( 'Content-Type: text/html; charset=utf-8' );
?>
<!DOCTYPE html>
<html dir="rtl" lang="fa">
<head>
    <meta charset="utf-8">
    <title>Demo ۷ نوع خدمت HVAC</title>
    <style>
        body { font-family: Tahoma, sans-serif; background: #f8fafc; padding: 24px; max-width: 1000px; margin: 0 auto; }
        h1 { color: #1e40af; }
        .card { background: #fff; border: 1px solid #e2e8f0; border-radius: 12px; padding: 16px; margin: 12px 0; }
        .ok { border-right: 4px solid #22c55e; }
        .err { border-right: 4px solid #ef4444; background: #fef2f2; }
        table { width: 100%; border-collapse: collapse; font-size: 13px; }
        td, th { border: 1px solid #e2e8f0; padding: 8px; text-align: right; }
        th { background: #eff6ff; }
        .badge { font-family: monospace; background: #1d4ed8; color: #fff; padding: 3px 10px; border-radius: 6px; font-weight: 700; }
        a { color: #1d4ed8; }
        pre { background: #f1f5f9; padding: 10px; overflow: auto; font-size: 11px; direction: ltr; text-align: left; }
    </style>
</head>
<body>
<h1>✅ Demo کامل ۷ نوع خدمت HVAC</h1>
<p>مشتری: <b><?= htmlspecialchars( $customer['name'] ?? '' ) ?></b> — <?= htmlspecialchars( $customer['phone'] ?? '' ) ?></p>

<div class="card ok">
    <h2>🔑 ورود تست</h2>
    <ul>
        <li>ارشد: <code>svc_senior_demo / <?= DEMO_PASS ?></code></li>
        <li>کارشناس: <code>svc_tech1_demo / <?= DEMO_PASS ?></code></li>
        <li>مشتری: ویجت → پیگیری (موبایل <?= htmlspecialchars( $customer['phone'] ?? '' ) ?>)</li>
        <li>پورتال: <a href="<?= htmlspecialchars( $base . '/service.php' ) ?>">service.php</a> → مشتری → پرونده من</li>
        <li>ERP: <a href="<?= htmlspecialchars( $base . '/index.php#service' ) ?>">خدمات میدانی</a> → درخواست‌ها → 👁 جزئیات</li>
    </ul>
</div>

<?php if ( ! empty( $cases ) ): ?>
<div class="card ok">
    <h2>📋 ۷ پرونده کامل</h2>
    <table>
        <tr><th>نوع</th><th>کد پیگیری</th><th>گزارش</th><th>فاکتور</th><th>مراحل timeline</th><th>لینک</th></tr>
        <?php foreach ( $cases as $c ): ?>
        <tr>
            <td><?= htmlspecialchars( $c['title'] ) ?></td>
            <td><span class="badge"><?= htmlspecialchars( $c['tracking_code'] ) ?></span></td>
            <td><code><?= htmlspecialchars( $c['report_no'] ) ?></code></td>
            <td><?= number_format( (float) $c['total'] ) ?> ت · مانده <?= number_format( (float) $c['balance'] ) ?></td>
            <td><?= (int) $c['timeline_count'] ?> مرحله</td>
            <td><a href="<?= htmlspecialchars( $c['public_url'] ) ?>" target="_blank">گزارش PDF</a></td>
        </tr>
        <?php endforeach; ?>
    </table>
</div>
<?php endif; ?>

<h2>جزئیات اجرا</h2>
<?php foreach ( $log as $s ): ?>
<div class="card <?= $s['ok'] ? 'ok' : 'err' ?>">
    <h3><?= $s['ok'] ? '✅' : '❌' ?> <?= htmlspecialchars( $s['title'] ) ?></h3>
    <?php if ( ! $s['ok'] ): ?>
        <p style="color:#991b1b;"><?= htmlspecialchars( $s['error'] ?? '' ) ?></p>
    <?php elseif ( ! empty( $s['data']['timeline'] ) ): ?>
        <ul style="font-size:12px;">
        <?php foreach ( $s['data']['timeline'] as $t ): ?>
            <li><?= htmlspecialchars( $t['label'] ?? '' ) ?> <small>(<?= htmlspecialchars( substr( $t['at'] ?? '', 0, 16 ) ) ?>)</small></li>
        <?php endforeach; ?>
        </ul>
    <?php else: ?>
        <pre><?= htmlspecialchars( json_encode( $s['data'] ?? [], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT ) ) ?></pre>
    <?php endif; ?>
</div>
<?php endforeach; ?>

<p style="font-size:11px;color:#94a3b8;">JSON: docs/service/seven-types-result.json</p>
</body>
</html>
