<?php
require_once __DIR__ . '/app/core.php';
app_send_security_headers();
app_send_no_cache_headers();
app_session_start();

$route = $_GET['p'] ?? 'invoice';
$config = app_config();
$lang = app_lang();
$dir = app_dir();
[$licensed, $licenseMessage] = license_status();
$flash = null; $errors = []; $generatedKey = null; $lastFiles = null; $csrPreview = null;
$allCustomers = customers_all();
$phase2Readiness = phase2_readiness($config);
$brandDisplayName = trim((string)($config['company']['brand_name'] ?? '')) ?: trim((string)($config['company']['name'] ?? '')) ?: APP_NAME;
$logoDataUri = image_data_uri(app_logo_path($config));
$phase2SubmissionLabel = phase2_submission_label($config);
$runtimeDiagnostics = runtime_diagnostics($config);

function tp(string $key): string {
    static $map = [
        'app_subtitle' => ['واجهة إصدار الفواتير','Invoice issuing panel'],
        'invoice' => ['إصدار فاتورة','Issue invoice'],
        'dashboard' => ['لوحة التحكم','Dashboard'],
        'customers' => ['العملاء','Customers'],
        'settings' => ['الإعدادات','Settings'],
        'phase2' => ['Phase 2','Phase 2'],
        'archive' => ['الأرشيف','Archive'],
        'activation' => ['تفعيل النظام','Activation'],
        'company_settings' => ['إعدادات الشركة','Company settings'],
        'company_name' => ['اسم الشركة','Company name'],
        'company_vat' => ['رقم VAT','VAT number'],
        'company_cr' => ['السجل التجاري','Commercial registration'],
        'currency' => ['العملة','Currency'],
        'address_optional' => ['العنوان (اختياري)','Address (optional)'],
        'vat_rate' => ['نسبة الضريبة','VAT rate'],
        'save_settings' => ['حفظ الإعدادات','Save settings'],
        'save_customer' => ['حفظ العميل','Save customer'],
        'add_edit_customer' => ['إضافة / تعديل عميل','Add / edit customer'],
        'saved_customers' => ['العملاء المحفوظون','Saved customers'],
        'customer_name' => ['اسم العميل','Customer name'],
        'customer_address' => ['العنوان','Address'],
        'new_invoice' => ['فاتورة جديدة','New invoice'],
        'invoice_no' => ['رقم الفاتورة','Invoice number'],
        'issue_date' => ['تاريخ الإصدار','Issue date'],
        'pick_customer' => ['اختر عميل محفوظ','Choose saved customer'],
        'quick_select' => ['-- اختيار سريع --','-- Quick select --'],
        'buyer_name' => ['اسم العميل','Buyer name'],
        'buyer_vat' => ['رقم VAT للعميل','Buyer VAT number'],
        'invoice_type' => ['نوع الفاتورة','Invoice type'],
        'print_language' => ['لغة الطباعة','Print language'],
        'buyer_address' => ['عنوان العميل','Buyer address'],
        'items' => ['بنود الفاتورة','Invoice items'],
        'description' => ['الوصف','Description'],
        'qty' => ['الكمية','Qty'],
        'unit_price' => ['سعر الوحدة','Unit price'],
        'delete' => ['حذف','Delete'],
        'add_item' => ['إضافة بند','Add item'],
        'generate_invoice' => ['إنشاء الفاتورة','Create invoice'],
        'company_optional_hint' => ['هذه الواجهة مخصصة للمستخدم بعد التفعيل. النظام جاهز هيكليًا لـ Phase 2 الحقيقي، ويمكنك تشغيله الآن على وضع QR المرحلة الأولى ثم تفعيل التوقيع وبيانات ZATCA لاحقًا من صفحة Phase 2.','This panel is for the activated user. The system is structurally ready for real Phase 2, and you can use it now with Phase 1 QR then enable signing and ZATCA credentials later from the Phase 2 page.'],
        'lang_switch' => ['اللغة','Language'],
        'status_on' => ['مفعل','Activated'],
        'status_off' => ['غير مفعل','Not activated'],
        'valid_until' => ['التفعيل ساري حتى','Active until'],
        'english' => ['English','English'],
        'arabic' => ['العربية','Arabic'],
        'tax_invoice_standard' => ['قياسية','Standard'],
        'tax_invoice_simplified' => ['مبسطة','Simplified'],
        'auto' => ['تلقائي','Auto'],
        'arabic_print' => ['العربية','Arabic'],
        'english_print' => ['English','English'],
        'bilingual_print' => ['عربي + English','Arabic + English'],
        'wa_support' => ['دعم واتساب','WhatsApp Support'],
        'invoice_live_summary' => ['ملخص مباشر','Live summary'],
        'subtotal' => ['الإجمالي قبل الضريبة','Subtotal'],
        'vat_total' => ['الضريبة','VAT'],
        'grand_total' => ['الإجمالي النهائي','Grand total'],
        'quick_actions' => ['إجراءات سريعة','Quick actions'],
        'go_settings' => ['إعدادات الشركة','Company settings'],
        'go_customers' => ['العملاء','Customers'],
        'go_archive' => ['الأرشيف','Archive'],
    ];
    global $lang;
    $pair = $map[$key] ?? [$key, $key];
    return $lang === 'en' ? $pair[1] : $pair[0];
}


function page_title(string $route): string {
    $map = [
        'dashboard' => tp('dashboard'),
        'settings' => tp('company_settings'),
        'customers' => tp('customers'),
        'phase2' => 'Phase 2',
        'activation' => tp('activation'),
        'archive' => tp('archive'),
        'invoice' => tp('new_invoice'),
    ];
    return $map[$route] ?? 'BK Invoice';
}

function page_hint(string $route): string {
    $map = [
        'dashboard' => app_lang()==='en' ? 'Quick summary of invoices, taxes, and Phase 2 readiness.' : 'نظرة سريعة على الفواتير والضرائب وجاهزية Phase 2.',
        'settings' => app_lang()==='en' ? 'Update company details once and use them across all invoices.' : 'حدّث بيانات الشركة مرة واحدة لتستخدم في جميع الفواتير.',
        'customers' => app_lang()==='en' ? 'Save customer data once and select it instantly during invoice creation.' : 'احفظ بيانات العملاء مرة واحدة واخترها مباشرة عند إنشاء الفاتورة.',
        'phase2' => app_lang()==='en' ? 'Prepare B2B clearance credentials step by step, then activate ZATCA integration.' : 'جهّز ربط الشركات B2B مع الزكاة خطوة بخطوة، ثم فعّل التكامل.',
        'activation' => app_lang()==='en' ? 'This page is only for entering the activation key for the user panel.' : 'هذه الصفحة مخصصة فقط لإدخال مفتاح التفعيل الخاص بلوحة المستخدم.',
        'archive' => app_lang()==='en' ? 'Review generated invoices and access printing, XML, and submission actions.' : 'راجع الفواتير المنشأة وافتح الطباعة وملفات XML وإجراءات الإرسال.',
        'invoice' => app_lang()==='en' ? 'Create invoices quickly with a cleaner flow and fewer steps.' : 'أنشئ الفواتير بسرعة وبخطوات أقل داخل واجهة أوضح.',
    ];
    return $map[$route] ?? '';
}

$allowedRoutes = ['dashboard','customers','settings','activation','phase2','archive','invoice','file','qr'];
if (!in_array($route, $allowedRoutes, true)) {
    $route = 'invoice';
}
if ($route === 'file') {
    if (!$licensed) {
        http_response_code(403);
        header('Content-Type: text/plain; charset=utf-8');
        echo 'Activation required';
        exit;
    }
    serve_archive_file((string)($_GET['id'] ?? ''), (string)($_GET['type'] ?? 'html'));
}
if ($route === 'qr') {
    if (!$licensed) {
        http_response_code(403);
        header('Content-Type: text/plain; charset=utf-8');
        echo 'Activation required';
        exit;
    }
    serve_qr_image((string)($_GET['payload'] ?? ''));
}

$actionsAllowedWithoutLicense = ['activate'];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string)($_POST['action'] ?? '');

    if (!csrf_validate($_POST['csrf_token'] ?? null)) {
        $errors[] = 'انتهت جلسة الحماية أو الطلب غير صالح. حدّث الصفحة وحاول مرة أخرى.';
        if (!$licensed) $route = 'activation';
    } elseif (!$licensed && !in_array($action, $actionsAllowedWithoutLicense, true)) {
        $errors[] = 'لا يمكن تنفيذ أي عملية قبل تفعيل اللوحة.';
        $route = 'activation';
    } else {
        switch ($action) {
            case 'save_settings':
                $config['company']['name'] = trim((string)($_POST['company_name'] ?? ''));
                $config['company']['vat'] = normalize_vat((string)($_POST['company_vat'] ?? ''));
                $config['company']['address'] = trim((string)($_POST['company_address'] ?? ''));
                $config['company']['commercial_registration'] = trim((string)($_POST['company_cr'] ?? ''));
                $config['company']['brand_name'] = trim((string)($_POST['brand_name'] ?? ''));
                $config['company']['phone'] = trim((string)($_POST['company_phone'] ?? ''));
                $config['company']['logo_path'] = trim((string)($_POST['logo_path'] ?? ''));
                $config['defaults']['currency'] = trim((string)($_POST['currency'] ?? 'SAR')) ?: 'SAR';
                $config['defaults']['vat_rate'] = max(0, (float)($_POST['vat_rate'] ?? 0.15));
                save_config($config);
                $config = app_config();
                $flash = 'تم حفظ إعدادات الشركة.';
                $route = 'settings';
                break;

            case 'save_customer':
                $customer = [
                    'name' => trim((string)($_POST['name'] ?? '')),
                    'vat' => normalize_vat((string)($_POST['vat'] ?? '')),
                    'address' => trim((string)($_POST['address'] ?? '')),
                    'commercial_registration' => '',
                ];
                if ($customer['name'] === '') $errors[] = 'اسم العميل مطلوب.';
                if ($customer['vat'] !== '' && strlen($customer['vat']) !== 15) $errors[] = 'رقم VAT للعميل يجب أن يكون 15 رقمًا أو يترك فارغًا.';
                if (!$errors) {
                    $all = customers_all();
                    $updated = false;
                    foreach ($all as &$row) {
                        if (($row['vat'] ?? '') !== '' && ($row['vat'] ?? '') === $customer['vat']) { $row = $customer; $updated = true; break; }
                    }
                    if (!$updated) $all[] = $customer;
                    customers_save($all);
                    $flash = 'تم حفظ العميل.';
                }
                $route = 'customers';
                break;

            case 'activate':
                [$ok, $msg] = try_activate((string)($_POST['request_code'] ?? ''), (string)($_POST['activation_key'] ?? ''));
                if ($ok) {
                    $flash = $msg;
                    $config = app_config();
                    [$licensed, $licenseMessage] = license_status();
                } else {
                    $errors[] = $msg;
                }
                $route = 'activation';
                break;

            case 'save_phase2_settings':
                $requestEnable = !empty($_POST['phase2_enabled']);
                $config['phase2']['enabled'] = false;
                $config['phase2']['environment'] = in_array(($_POST['environment'] ?? 'Sandbox'), ['Sandbox','Production'], true) ? $_POST['environment'] : 'Sandbox';
                $config['phase2']['device_id'] = trim((string)($_POST['device_id'] ?? ''));
                $config['phase2']['otp'] = trim((string)($_POST['otp'] ?? ''));
                $config['phase2']['b2b_mode'] = true;
                $config['phase2']['qr_mode'] = in_array(($_POST['qr_mode'] ?? 'auto'), ['phase1','auto','phase2'], true) ? $_POST['qr_mode'] : 'auto';
                $config['phase2']['compliance_request_id'] = trim((string)($_POST['compliance_request_id'] ?? ($config['phase2']['compliance_request_id'] ?? '')));
                $productionTokenInput = trim((string)($_POST['production_binary_security_token'] ?? ''));
                $productionSecretInput = trim((string)($_POST['production_secret'] ?? ''));
                if ($productionTokenInput !== '') {
                    $config['phase2']['production_binary_security_token'] = $productionTokenInput;
                    $config['phase2']['binary_security_token'] = $productionTokenInput;
                }
                if ($productionSecretInput !== '') {
                    $config['phase2']['production_secret'] = $productionSecretInput;
                    $config['phase2']['secret'] = $productionSecretInput;
                }
                if (trim((string)($_POST['private_key_pem'] ?? '')) !== '') {
                    $config['phase2']['private_key_path'] = save_pem_text('phase2/private_key.pem', (string)$_POST['private_key_pem']);
                }
                if (trim((string)($_POST['production_certificate_pem'] ?? '')) !== '') {
                    $config['phase2']['production_csid_path'] = save_pem_text('phase2/production-csid.pem', (string)$_POST['production_certificate_pem']);
                    $config['phase2']['csid_path'] = $config['phase2']['production_csid_path'];
                }
                if (trim((string)($_POST['compliance_certificate_pem'] ?? '')) !== '') {
                    $config['phase2']['compliance_csid_path'] = save_pem_text('phase2/compliance-csid.pem', (string)$_POST['compliance_certificate_pem']);
                }
                $draftReadiness = phase2_readiness($config);
                if ($requestEnable && !$draftReadiness['ready']) {
                    $failedLabels = [];
                    foreach ($draftReadiness['checks'] as $check) {
                        if (empty($check['ok'])) $failedLabels[] = $check['label'];
                    }
                    $errors[] = 'تم حفظ البيانات، لكن لم يتم تفعيل Phase 2 لأن الجاهزية غير مكتملة: ' . implode('، ', $failedLabels) . '.';
                    $flash = 'أكمل عناصر الجاهزية ثم فعّل Phase 2 مرة أخرى.';
                } else {
                    $config['phase2']['enabled'] = $requestEnable;
                    $flash = $requestEnable ? 'تم حفظ الإعدادات وتفعيل Phase 2.' : 'تم حفظ إعدادات Phase 2.';
                }
                save_config($config);
                $config = app_config();
                $phase2Readiness = phase2_readiness($config);
                $brandDisplayName = trim((string)($config['company']['brand_name'] ?? '')) ?: trim((string)($config['company']['name'] ?? '')) ?: APP_NAME;
                $logoDataUri = image_data_uri(app_logo_path($config));
                $phase2SubmissionLabel = phase2_submission_label($config);
                $route = 'phase2';
                break;

            case 'generate_csr':
                [$ok, $msg, $payload] = array_pad(generate_csr_package($config), 3, null);
                if ($ok) { $flash = $msg; $csrPreview = $payload; $config = app_config(); $brandDisplayName = trim((string)($config['company']['brand_name'] ?? '')) ?: trim((string)($config['company']['name'] ?? '')) ?: APP_NAME; $logoDataUri = image_data_uri(app_logo_path($config)); $phase2SubmissionLabel = phase2_submission_label($config); }
                else $errors[] = $msg;
                $route = 'phase2';
                break;

            case 'request_compliance':
                $otp = trim((string)($_POST['otp'] ?? $config['phase2']['otp'] ?? ''));
                if ($otp === '') $errors[] = 'OTP مطلوب لطلب compliance CSID.';
                else {
                    [$ok, $msg] = request_compliance_csid($config, $otp);
                    if ($ok) { $config = app_config(); $phase2Readiness = phase2_readiness($config); $brandDisplayName = trim((string)($config['company']['brand_name'] ?? '')) ?: trim((string)($config['company']['name'] ?? '')) ?: APP_NAME; $logoDataUri = image_data_uri(app_logo_path($config)); $phase2SubmissionLabel = phase2_submission_label($config); $flash = $msg . ($phase2Readiness['ready'] ? ' ويمكن الآن تفعيل Phase 2.' : ' راجع قائمة الجاهزية ثم أكمل خطوة ' . $phase2SubmissionLabel . '.'); } else $errors[] = $msg;
                }
                $route = 'phase2';
                break;

            case 'generate_invoice':
                $items = [];
                foreach (($_POST['item_description'] ?? []) as $i => $desc) {
                    $description = trim((string)$desc);
                    $qty = (float)($_POST['item_qty'][$i] ?? 0);
                    $price = (float)($_POST['item_price'][$i] ?? 0);
                    $vatRate = (float)($_POST['item_vat'][$i] ?? ($config['defaults']['vat_rate'] ?? 0.15));
                    if ($description === '' && $qty <= 0 && $price <= 0) continue;
                    $items[] = ['description'=>$description, 'qty'=>$qty, 'unit_price'=>$price, 'vat_rate'=>$vatRate];
                }

                $buyerVat = normalize_vat((string)($_POST['buyer_vat'] ?? ''));
                $invoiceKind = (($_POST['invoice_kind'] ?? '') === 'Simplified') ? 'Simplified' : (((($_POST['invoice_kind'] ?? '') === 'Standard') || strlen($buyerVat) === 15) ? 'Standard' : 'Simplified');
                $request = [
                    'invoice_id' => trim((string)($_POST['invoice_id'] ?? '')),
                    'uuid' => make_uuid(),
                    'issue_utc' => gmdate('c', strtotime((string)($_POST['issue_date'] ?? 'now')) ?: time()),
                    'currency' => trim((string)($_POST['currency'] ?? ($config['defaults']['currency'] ?? 'SAR'))) ?: 'SAR',
                    'invoice_kind' => $invoiceKind,
                    'seller' => [
                        'name' => trim((string)($config['company']['name'] ?? '')),
                        'vat' => (string)($config['company']['vat'] ?? ''),
                        'address' => trim((string)($config['company']['address'] ?? '')),
                        'commercial_registration' => trim((string)($config['company']['commercial_registration'] ?? '')),
                    ],
                    'buyer' => [
                        'name' => trim((string)($_POST['buyer_name'] ?? '')),
                        'vat' => $buyerVat,
                        'address' => trim((string)($_POST['buyer_address'] ?? '')),
                    ],
                    'items' => $items,
                ];
                $errors = validate_invoice($request);
                if (!$errors) {
                    $state = phase2_state();
                    $pkg = create_signed_invoice_package($request, $config, $state, (string)($_POST['print_language'] ?? 'ar'));
                    $lastFiles = $pkg['files'];
                    $flash = 'تم إنشاء الفاتورة وحفظ XML / HTML / metadata داخل التخزين الآمن.';
                }
                $route = 'invoice';
                break;

            case 'submit_invoice':
                $metaPath = (string)($_POST['metadata_path'] ?? '');
                if ($metaPath === '' || !is_safe_storage_path($metaPath, 'archive') || !file_exists($metaPath)) {
                    $errors[] = 'ملف metadata غير موجود أو غير مسموح.';
                } else {
                    $meta = read_json_file($metaPath, []);
                    if (!$meta) {
                        $errors[] = 'تعذر قراءة metadata.';
                    } else {
                        [$ok, $msg] = array_pad(submit_invoice_to_zatca($config, $meta), 2, null);
                        if ($ok) $flash = $msg; else $errors[] = $msg;
                    }
                }
                $route = 'archive';
                break;

            case 'repair_invoice_html':
                $metaPath = (string)($_POST['metadata_path'] ?? '');
                [$ok, $msg] = array_pad(repair_invoice_html_from_metadata_path($metaPath, $config), 2, null);
                if ($ok) $flash = $msg; else $errors[] = $msg;
                $route = 'archive';
                break;

            case 'repair_all_archive_html':
                [$ok, $msg] = array_pad(repair_all_archived_invoice_html($config), 2, null);
                if ($ok) $flash = $msg; else $errors[] = $msg;
                $route = 'archive';
                break;
        }
    }
}
$phase2Readiness = phase2_readiness($config);
if ($csrPreview === null && !empty($config['phase2']['csr_path']) && file_exists((string)$config['phase2']['csr_path'])) {
    $csrPreview = ['csr_pem' => (string)file_get_contents((string)$config['phase2']['csr_path'])];
}
$brandDisplayName = trim((string)($config['company']['brand_name'] ?? '')) ?: trim((string)($config['company']['name'] ?? '')) ?: APP_NAME;
$logoDataUri = image_data_uri(app_logo_path($config));
$phase2SubmissionLabel = phase2_submission_label($config);
$runtimeDiagnostics = runtime_diagnostics($config);

if (!$licensed && $route !== 'activation') {
    $route = 'activation';
}

function nav_link(string $page, string $label, string $route): string {
    $active = $page === $route ? 'active' : '';
    return '<a class="nav-link ' . $active . '" href="?p=' . h($page) . '">' . h($label) . '</a>';
}
$archive = invoice_metadata_all();
$summary = [
    'count' => count($archive),
    'gross' => array_sum(array_map(fn($r)=>(float)($r['totals']['payable_amount'] ?? 0), $archive)),
    'vat' => array_sum(array_map(fn($r)=>(float)($r['totals']['vat_amount'] ?? 0), $archive)),
    'draft' => count(array_filter($archive, fn($r)=>(($r['status'] ?? 'Draft') === 'Draft'))),
    'sent' => count(array_filter($archive, fn($r)=>in_array(($r['status'] ?? ''), ['Cleared','Reported'], true))),
];
?><!doctype html>
<html lang="<?= h($lang) ?>" dir="<?= h($dir) ?>">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= h(APP_NAME) ?></title>
<style>
:root{--bg:#0c0907;--bg-2:#17110c;--panel:#18110b;--panel-soft:#21170f;--panel-elev:#2a1d12;--text:#f6efe3;--muted:#ccb894;--line:rgba(197,161,106,.16);--line-strong:rgba(197,161,106,.28);--primary:#c5a16a;--primary-2:#a87d47;--success:#1f9d72;--warn:#d97706;--danger:#dc2626;--radius:20px;--radius-sm:14px;--shadow:0 20px 48px rgba(5,4,3,.42);--sidebar-w:282px}
*{box-sizing:border-box}html{-webkit-text-size-adjust:100%;scroll-behavior:smooth}body{margin:0;background:radial-gradient(circle at top left,rgba(197,161,106,.15),transparent 26%),radial-gradient(circle at top right,rgba(214,195,156,.08),transparent 24%),linear-gradient(180deg,#0b0907 0%,#110d09 100%);color:var(--text);font:500 15px/1.7 Inter,Tahoma,Arial,sans-serif}
a{text-decoration:none;color:inherit}h1,h2,h3{margin:0 0 12px;line-height:1.25}h1{font-size:1.22rem;font-weight:800}h2{font-size:1.05rem;font-weight:800}h3{font-size:.98rem;font-weight:800}label{display:block;font-size:.9rem;color:#ead8b6;margin:0 0 8px;font-weight:700}small,.small{font-size:.82rem;color:var(--muted)}.muted{color:var(--muted)}
.layout{min-height:100vh;display:grid;grid-template-columns:var(--sidebar-w) 1fr}.sidebar{background:linear-gradient(180deg,rgba(18,13,9,.97),rgba(12,9,7,.98));border-inline-end:1px solid var(--line);padding:24px 18px 18px;position:sticky;top:0;height:100vh;backdrop-filter:blur(10px)}.brand-lockup{display:grid;gap:12px;padding:14px;border-radius:20px;background:linear-gradient(180deg,rgba(197,161,106,.12),rgba(24,17,11,.35));border:1px solid rgba(197,161,106,.18)}.brand-top{display:flex;align-items:center;gap:12px}.brand-logo{width:52px;height:52px;border-radius:16px;object-fit:cover;background:#fff;padding:4px;box-shadow:0 10px 24px rgba(0,0,0,.18)}.brand-meta{min-width:0}.brand-kicker{font-size:.72rem;letter-spacing:.16em;text-transform:uppercase;color:#e4d0aa;font-weight:900}.brand{font-size:1.24rem;font-weight:900;letter-spacing:.2px}.nav{display:grid;gap:8px;margin-top:20px}.nav-link{display:flex;align-items:center;gap:10px;padding:12px 14px;border-radius:14px;color:#f4ead8;border:1px solid transparent;transition:.18s ease}.nav-link:hover{background:rgba(255,255,255,.03);border-color:var(--line);transform:translateY(-1px)}.nav-link.active{background:linear-gradient(180deg,rgba(197,161,106,.22),rgba(168,125,71,.14));border-color:rgba(197,161,106,.34);box-shadow:inset 0 1px 0 rgba(255,255,255,.06)}
.content{padding:24px 24px 30px;min-width:0}.topbar{display:flex;justify-content:space-between;align-items:flex-start;gap:16px;margin-bottom:18px;padding:0 0 10px;position:sticky;top:0;z-index:15;background:linear-gradient(180deg,#0b0907 78%,rgba(11,9,7,0))}.page-head{display:flex;align-items:flex-start;gap:12px;min-width:0}.eyebrow{font-size:.76rem;font-weight:800;letter-spacing:.12em;text-transform:uppercase;color:#e8c98d;margin-bottom:5px}.page-title{margin:0;font-size:1.7rem;letter-spacing:-.02em}.page-subtitle{color:var(--muted);max-width:760px;font-size:.94rem}.top-actions{display:flex;align-items:center;gap:10px;flex-wrap:wrap;justify-content:flex-end}.status-chip{display:inline-flex;align-items:center;gap:8px;padding:10px 12px;border-radius:999px;border:1px solid var(--line-strong);background:rgba(24,17,11,.88);font-size:.84rem;font-weight:800}.status-chip .dot{width:9px;height:9px;border-radius:50%;background:#c9b28f;box-shadow:0 0 0 4px rgba(201,178,143,.12)}.status-chip.ok .dot{background:#22c55e;box-shadow:0 0 0 4px rgba(34,197,94,.12)}.status-chip.off .dot{background:#f59e0b;box-shadow:0 0 0 4px rgba(245,158,11,.12)}
.lang-switch{display:flex;align-items:center;gap:8px;flex-wrap:wrap;padding:6px;border-radius:999px;background:rgba(24,17,11,.78);border:1px solid var(--line)}.lang-group{display:flex;gap:8px;flex-wrap:wrap}.lang-btn,.menu-btn{display:inline-flex;align-items:center;justify-content:center;padding:10px 14px;border-radius:999px;border:1px solid var(--line-strong);background:#17110c;color:var(--text);font-weight:700;min-height:42px;transition:.18s ease}.lang-btn:hover,.menu-btn:hover{transform:translateY(-1px);border-color:#c5a16a}.lang-btn.active{background:linear-gradient(180deg,var(--primary),var(--primary-2));border-color:transparent;box-shadow:0 12px 24px rgba(168,125,71,.28)}.menu-btn{display:none}
.card,.stat{background:linear-gradient(180deg,rgba(24,17,11,.96),rgba(16,12,9,.97));border:1px solid var(--line);border-radius:var(--radius);padding:20px;box-shadow:var(--shadow)}.card{position:relative;overflow:hidden}.card::before{content:"";position:absolute;inset:0 0 auto 0;height:1px;background:linear-gradient(90deg,transparent,rgba(229,201,141,.48),transparent)}.stat{padding:22px;transition:.18s ease}.stat:hover,.card:hover{transform:translateY(-2px);border-color:rgba(229,201,141,.24)}.stat h2{margin:8px 0 0;font-size:1.55rem}.pill{display:inline-flex;align-items:center;gap:8px;padding:8px 11px;border-radius:999px;background:rgba(197,161,106,.12);border:1px solid rgba(197,161,106,.24);font-size:.8rem;font-weight:800}.progress{height:11px;border-radius:999px;background:rgba(197,161,106,.12);overflow:hidden;border:1px solid rgba(197,161,106,.18);margin:12px 0 10px}.progress>span{display:block;height:100%;border-radius:999px;background:linear-gradient(90deg,#d6c39c,#c5a16a)}.checklist{list-style:none;padding:0;margin:14px 0 0;display:grid;gap:10px}.check-item{display:flex;justify-content:space-between;gap:14px;padding:12px 14px;border-radius:14px;background:rgba(12,9,7,.46);border:1px solid rgba(197,161,106,.12)}.check-meta{display:grid;gap:4px}.check-meta strong{font-size:.94rem}.check-meta span{font-size:.82rem;color:var(--muted)}.mini-stat-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px}.mini-stat{padding:14px;border-radius:16px;background:rgba(12,9,7,.46);border:1px solid rgba(197,161,106,.12)}.mini-stat .label{display:block;font-size:.8rem;color:var(--muted);margin-bottom:6px}.mini-stat strong{font-size:1rem}.callout{padding:14px 16px;border-radius:16px;border:1px solid var(--line-strong);background:rgba(12,9,7,.46);margin:0 0 14px}.callout.warn{border-color:rgba(245,158,11,.3);background:rgba(217,119,6,.11)}.callout.success{border-color:rgba(34,197,94,.3);background:rgba(22,163,74,.11)}.field-hint{margin-top:8px;font-size:.8rem;color:var(--muted)}.step-grid{display:grid;gap:12px}.step-card{padding:14px;border-radius:16px;background:rgba(12,9,7,.5);border:1px solid rgba(197,161,106,.14)}.step-card strong{display:block;margin-bottom:6px}.soft-list{margin:0;padding-inline-start:18px;color:var(--muted)}.soft-list li+li{margin-top:6px}.helper-grid{display:grid;gap:14px}.subsection-title{margin:6px 0 10px;font-size:.92rem;color:#eed7af;font-weight:800}
.grid{display:grid;gap:18px}.grid-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-4{grid-template-columns:repeat(4,minmax(0,1fr))}.form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}.full{grid-column:1/-1}.stack-end{display:flex;align-items:end}.toolbar,.actions{display:flex;gap:10px;flex-wrap:wrap}.toolbar{align-items:center}
input,select,textarea,button,.btn{font:inherit}input,select,textarea{width:100%;padding:12px 14px;min-height:46px;border-radius:14px;border:1px solid var(--line-strong);background:#0f0b08;color:var(--text);outline:none;transition:.18s ease;box-shadow:inset 0 1px 0 rgba(255,255,255,.03)}textarea{min-height:110px;resize:vertical}input:focus,select:focus,textarea:focus{border-color:rgba(197,161,106,.72);box-shadow:0 0 0 4px rgba(197,161,106,.12)}input::placeholder,textarea::placeholder{color:#9f8f70}
button,.btn{display:inline-flex;align-items:center;justify-content:center;padding:11px 16px;min-height:46px;border:none;border-radius:14px;background:linear-gradient(180deg,var(--primary),var(--primary-2));color:#1b120b;font-weight:900;cursor:pointer;transition:.18s ease;box-shadow:0 10px 24px rgba(168,125,71,.24)}button:hover,.btn:hover{transform:translateY(-1px);filter:brightness(1.03)}.btn.secondary{background:#2c2014;color:#f5ead7;box-shadow:none}.btn.warn{background:linear-gradient(180deg,#f59e0b,#d97706);color:#fff;box-shadow:0 10px 24px rgba(217,119,6,.22)}.btn.success{background:linear-gradient(180deg,#22c55e,#16a34a);color:#fff;box-shadow:0 10px 24px rgba(34,197,94,.22)}
.wa-support{position:fixed;left:20px;bottom:74px;display:inline-flex;align-items:center;gap:10px;padding:12px 18px;border-radius:999px;background:linear-gradient(135deg,#25D366,#1ebe5d);color:#fff;font-weight:800;font-size:14px;letter-spacing:.01em;box-shadow:0 16px 35px rgba(10,20,35,.32),0 0 0 1px rgba(255,255,255,.08) inset;z-index:55;transition:transform .18s ease,box-shadow .18s ease;direction:ltr}.wa-support:hover{transform:translateY(-2px);box-shadow:0 18px 40px rgba(10,20,35,.38),0 0 0 1px rgba(255,255,255,.12) inset}.wa-icon{display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;border-radius:50%;background:rgba(255,255,255,.18);font-size:14px;line-height:1}.wa-support span:last-child{white-space:nowrap}
.flash,.error{padding:14px 16px;border-radius:16px;margin-bottom:14px;border:1px solid}.flash{background:rgba(22,163,74,.14);border-color:rgba(22,163,74,.35);color:#dcfce7}.error{background:rgba(220,38,38,.12);border-color:rgba(220,38,38,.28);color:#fee2e2}.badge-ok,.badge-warn,.badge-bad{display:inline-flex;align-items:center;padding:4px 10px;border-radius:999px;font-size:.8rem;font-weight:800}.badge-ok{background:rgba(22,163,74,.15);border:1px solid rgba(22,163,74,.35)}.badge-warn{background:rgba(217,119,6,.15);border:1px solid rgba(217,119,6,.35)}.badge-bad{background:rgba(220,38,38,.15);border:1px solid rgba(220,38,38,.35)}
.table-wrap,.items-table{overflow:auto;-webkit-overflow-scrolling:touch;border:1px solid var(--line);border-radius:16px;background:rgba(12,9,7,.42)}table{width:100%;border-collapse:collapse}th,td{padding:12px 14px;border-bottom:1px solid rgba(197,161,106,.08);text-align:start;vertical-align:top}thead th{position:sticky;top:0;background:#1d140d;z-index:1;font-size:.85rem;color:#f0dfbf}tbody tr:nth-child(even){background:rgba(255,255,255,.012)}tbody tr:hover{background:rgba(197,161,106,.04)}.items-table{display:block}.items-table input{min-width:110px}.mono{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;direction:ltr;text-align:left;word-break:break-all;font-size:.85rem}.codebox{background:#0f0b08;border:1px dashed rgba(197,161,106,.36);border-radius:14px;padding:12px;max-height:220px;overflow:auto;white-space:pre-wrap}
@media (min-width:1441px){.content{padding-inline:34px}.grid-4{grid-template-columns:repeat(4,minmax(0,1fr))}}
@media (min-width:981px) and (max-width:1280px){:root{--sidebar-w:248px}.grid-4{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-3{grid-template-columns:repeat(2,minmax(0,1fr))}.page-title{font-size:1.45rem}}
@media (min-width:981px){.sidebar-backdrop{display:none}.menu-btn{display:none}}
@media (max-width:980px){.layout{grid-template-columns:1fr}.quick-actions{grid-template-columns:repeat(2,minmax(0,1fr))}.live-summary-grid{grid-template-columns:1fr}.sidebar{position:fixed;inset:0 auto 0 0;width:min(84vw,320px);height:100vh;transform:translateX(-100%);transition:transform .22s ease;z-index:40;box-shadow:18px 0 40px rgba(0,0,0,.28)}.layout.menu-open .sidebar{transform:translateX(0)}.sidebar-backdrop{position:fixed;inset:0;background:rgba(2,6,23,.62);opacity:0;pointer-events:none;transition:opacity .25s ease;z-index:30}.layout.menu-open .sidebar-backdrop{opacity:1;pointer-events:auto}.content{padding:18px 14px 24px;width:100%}.menu-btn{display:inline-flex}.grid-4{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-3,.grid-2,.mini-stat-grid{grid-template-columns:repeat(2,minmax(0,1fr))}.form-grid{grid-template-columns:1fr 1fr}.topbar{padding-top:0}.stack-end{display:block}}
@media (max-width:768px){body{font-size:14px}.quick-actions{grid-template-columns:1fr}.wa-support{left:14px;right:14px;justify-content:center;bottom:14px}.sticky-actions{bottom:10px}.card,.stat{padding:16px;border-radius:16px}.topbar,.top-actions,.page-head{flex-direction:column;align-items:stretch}.page-title{font-size:1.35rem}.lang-switch,.lang-group,.status-chip{width:100%}.lang-group{display:grid;grid-template-columns:repeat(2,minmax(0,1fr))}.lang-btn,.menu-btn,.toolbar .btn,.actions .btn,.btn,button{width:100%}.grid-2,.grid-3,.grid-4,.form-grid,.mini-stat-grid{grid-template-columns:1fr}.items-table td,.items-table th{padding:8px}.table-wrap{border-radius:14px}table{min-width:620px}}
@media (max-width:480px){.content{padding:14px 10px 20px}.card,.stat{padding:14px;border-radius:14px}.topbar{gap:10px}.page-subtitle{font-size:.88rem}input,select,textarea,button,.btn{min-height:44px;padding:10px 12px}table{min-width:560px}th,td{font-size:.82rem;padding:10px 8px}}
</style>
</head>
<body>
<div class="layout" id="appLayout"><div class="sidebar-backdrop" onclick="toggleMenu(false)"></div>
<aside class="sidebar">
  <div class="brand-lockup">
    <div class="brand-top">
      <?php if ($logoDataUri !== ''): ?>
        <img class="brand-logo" src="<?= h($logoDataUri) ?>" alt="<?= h($brandDisplayName) ?>">
      <?php endif; ?>
      <div class="brand-meta">
        <div class="brand-kicker">B2B Invoicing</div>
        <div class="brand"><?= h($brandDisplayName) ?></div>
      </div>
    </div>
    <div class="small"><?= h(tp('app_subtitle')) ?></div>
  </div>
  <div style="margin-top:18px" class="pill"><?= $licensed ? h(tp('status_on')) : h(tp('status_off')) ?></div>
  <div class="small" style="margin-top:10px"><?= h($licenseMessage) ?></div>
  <nav class="nav">
    <?= nav_link('invoice',tp('invoice'),$route) ?>
    <?= nav_link('dashboard',tp('dashboard'),$route) ?>
    <?= nav_link('customers',tp('customers'),$route) ?>
    <?= nav_link('settings',tp('settings'),$route) ?>
    <?= nav_link('phase2',tp('phase2'),$route) ?>
    <?= nav_link('archive',tp('archive'),$route) ?>
    <?php if (!$licensed): ?>
      <?= nav_link('activation',tp('activation'),$route) ?>
    <?php endif; ?>
  </nav>

</aside>
<main class="content">
  <div class="topbar">
    <div class="page-head">
      <button type="button" class="menu-btn" onclick="toggleMenu()">☰ <?= $lang === 'en' ? 'Menu' : 'القائمة' ?></button>
      <div>
        <div class="eyebrow"><?= h($brandDisplayName) ?></div>
        <h1 class="page-title"><?= h(page_title($route)) ?></h1>
        <div class="page-subtitle"><?= h(page_hint($route)) ?></div>
      </div>
    </div>
    <div class="top-actions">
      <div class="status-chip <?= $licensed ? 'ok' : 'off' ?>">
        <span class="dot"></span>
        <span><?= $licensed ? h(tp('status_on')) : h(tp('status_off')) ?></span>
      </div>
      <div class="status-chip <?= $phase2Readiness['ready'] ? 'ok' : 'off' ?>">
        <span class="dot"></span>
        <span>Phase 2 <?= (int)$phase2Readiness['completed'] ?>/<?= (int)$phase2Readiness['total'] ?></span>
      </div>
      <div class="lang-switch">
        <span class="small"><?= h(tp('lang_switch')) ?>:</span>
        <div class="lang-group">
          <a class="lang-btn <?= $lang === 'ar' ? 'active' : '' ?>" href="?p=<?= h($route) ?>&lang=ar"><?= h(tp('arabic')) ?></a>
          <a class="lang-btn <?= $lang === 'en' ? 'active' : '' ?>" href="?p=<?= h($route) ?>&lang=en"><?= h(tp('english')) ?></a>
        </div>
      </div>
    </div>
  </div>
  <?php if ($flash): ?><div class="flash"><?= h($flash) ?></div><?php endif; ?>
  <?php foreach ($errors as $err): ?><div class="error"><?= h($err) ?></div><?php endforeach; ?>

  <?php if ($route === 'dashboard'): ?>
    <div class="grid grid-4">
      <div class="stat"><div class="muted">عدد الفواتير</div><h2><?= (int)$summary['count'] ?></h2></div>
      <div class="stat"><div class="muted">إجمالي الضريبة</div><h2><?= number_format((float)$summary['vat'],2) ?></h2></div>
      <div class="stat"><div class="muted">إجمالي المبيعات</div><h2><?= number_format((float)$summary['gross'],2) ?></h2></div>
      <div class="stat"><div class="muted">جاهزية Phase 2</div><h2><?= (int)$phase2Readiness['percent'] ?>%</h2></div>
    </div>
    <div class="grid grid-2" style="margin-top:18px">
      <div class="card">
        <div class="toolbar" style="justify-content:space-between;align-items:flex-start">
          <div>
            <h1>جاهزية Phase 2</h1>
            <div class="muted">لن يتم تفعيل المرحلة الثانية إلا بعد اكتمال كل العناصر الأساسية.</div>
          </div>
          <span class="pill"><?= (int)$phase2Readiness['completed'] ?>/<?= (int)$phase2Readiness['total'] ?></span>
        </div>
        <div class="progress"><span style="width:<?= (int)$phase2Readiness['percent'] ?>%"></span></div>
        <div class="callout <?= $phase2Readiness['ready'] ? 'success' : 'warn' ?>"><?= $phase2Readiness['ready'] ? 'Phase 2 جاهزة الآن للتفعيل من صفحة Phase 2.' : h($phase2Readiness['next_step']) ?></div>
        <ul class="checklist">
          <?php foreach ($phase2Readiness['checks'] as $check): ?>
            <li class="check-item">
              <div class="check-meta">
                <strong><?= h($check['label']) ?></strong>
                <span><?= h($check['hint']) ?></span>
              </div>
              <span class="<?= !empty($check['ok']) ? 'badge-ok' : 'badge-warn' ?>"><?= !empty($check['ok']) ? 'جاهز' : 'ناقص' ?></span>
            </li>
          <?php endforeach; ?>
        </ul>
      </div>
      <div class="card">
        <h1>إجراءات سريعة</h1>
        <div class="actions">
          <a class="btn" href="?p=invoice">إنشاء فاتورة</a>
          <a class="btn secondary" href="?p=settings">إعدادات الشركة</a>
          <a class="btn secondary" href="?p=phase2">Phase 2</a>
          <a class="btn secondary" href="?p=archive">الأرشيف</a>
        </div>
        <div class="mini-stat-grid" style="margin-top:16px">
          <div class="mini-stat"><span class="label">Environment</span><strong><?= h($config['phase2']['environment'] ?? 'Sandbox') ?></strong></div>
          <div class="mini-stat"><span class="label">QR Mode</span><strong><?= h($config['phase2']['qr_mode'] ?? 'auto') ?></strong></div>
          <div class="mini-stat"><span class="label">Key Algorithm</span><strong><?= h((string)($config['phase2']['key_algorithm'] ?? '')) ?: 'غير محدد' ?></strong></div>
        </div>
        <div class="callout" style="margin-top:16px">
          <strong>تشخيص سريع للبيئة</strong>
          <div class="small" style="margin-top:6px">تم تعديل المشروع بحيث يظهر QR على الاستضافات المشتركة عبر نفس الدومين، مع Proxy و Cache داخليين عند الحاجة.</div>
          <ul class="checklist" style="margin-top:12px">
            <?php foreach ($runtimeDiagnostics['checks'] as $diag): ?>
              <li class="check-item">
                <div class="check-meta"><strong><?= h($diag['label']) ?></strong><span class="mono"><?= h($diag['hint']) ?></span></div>
                <span class="<?= !empty($diag['ok']) ? 'badge-ok' : 'badge-warn' ?>"><?= !empty($diag['ok']) ? 'OK' : 'Check' ?></span>
              </li>
            <?php endforeach; ?>
          </ul>
        </div>
        <h3 style="margin-top:18px">آخر الفواتير</h3>
        <div class="table-wrap"><table><thead><tr><th>الرقم</th><th>النوع</th><th>الحالة</th><th>الإجمالي</th></tr></thead><tbody>
          <?php foreach (array_slice($archive,0,8) as $row): ?><tr><td><?= h($row['invoice_id'] ?? '') ?></td><td><?= h($row['invoice_kind'] ?? '') ?></td><td><?= h($row['status'] ?? 'Draft') ?></td><td><?= number_format((float)($row['totals']['payable_amount'] ?? 0),2) ?></td></tr><?php endforeach; ?>
        </tbody></table></div>
      </div>
    </div>

  <?php elseif ($route === 'settings'): ?>
    <div class="card"><h1><?= h(tp('company_settings')) ?></h1>
      <div class="callout warn">لجعل Phase 2 جاهزة للتفعيل، أكمل اسم الشركة ورقم VAT والعنوان هنا أولًا ثم ارجع إلى صفحة Phase 2.</div>
      <form method="post" class="form-grid">
        <?= csrf_input() ?>
        <input type="hidden" name="action" value="save_settings">
        <div><label><?= h(tp('company_name')) ?></label><input name="company_name" value="<?= h($config['company']['name'] ?? '') ?>"></div>
        <div><label><?= h(tp('company_vat')) ?></label><input name="company_vat" value="<?= h($config['company']['vat'] ?? '') ?>"></div>
        <div><label><?= h(tp('company_cr')) ?></label><input name="company_cr" value="<?= h($config['company']['commercial_registration'] ?? '') ?>"></div>
        <div><label><?= h(tp('currency')) ?></label><select name="currency"><?php foreach (['SAR','USD','EUR'] as $cur): ?><option value="<?= $cur ?>" <?= (($config['defaults']['currency'] ?? 'SAR') === $cur) ? 'selected' : '' ?>><?= $cur ?></option><?php endforeach; ?></select></div>
        <div><label>الاسم التجاري (اختياري)</label><input name="brand_name" value="<?= h($config['company']['brand_name'] ?? '') ?>"></div>
        <div><label>الهاتف (اختياري)</label><input name="company_phone" value="<?= h($config['company']['phone'] ?? '') ?>"></div>
        <div class="full"><label><?= h(tp('address_optional')) ?></label><textarea name="company_address"><?= h($config['company']['address'] ?? '') ?></textarea><div class="field-hint">حتى لو كان اختياريًا للطباعة، وجود العنوان مهم لرفع جاهزية Phase 2.</div></div>
        <div class="full"><label>مسار الشعار (اختياري)</label><input class="mono" name="logo_path" value="<?= h($config['company']['logo_path'] ?? '') ?>" placeholder="مثال: ../bk-invoice-data/branding/company-logo.png"></div>
        <div><label><?= h(tp('vat_rate')) ?></label><input name="vat_rate" type="number" step="0.01" value="<?= h((string)($config['defaults']['vat_rate'] ?? 0.15)) ?>"></div>
        <div class="full muted">يُفضّل حفظ الشعار داخل مجلد البيانات الآمن خارج الويب ثم وضع مساره هنا.</div>
        <div class="stack-end"><button type="submit"><?= h(tp('save_settings')) ?></button></div>
      </form>
    </div>

  <?php elseif ($route === 'customers'): $customers = customers_all(); ?>
    <div class="grid grid-2">
      <div class="card"><h1><?= h(tp('add_edit_customer')) ?></h1>
        <form method="post" class="form-grid">
          <?= csrf_input() ?>
          <input type="hidden" name="action" value="save_customer">
          <div class="full"><label><?= h(tp('customer_name')) ?></label><input name="name"></div>
          <div><label><?= h(tp('company_vat')) ?></label><input name="vat"></div>
          <div class="full"><label><?= h(tp('customer_address')) ?></label><textarea name="address"></textarea></div>
          <div><button type="submit"><?= h(tp('save_customer')) ?></button></div>
        </form>
      </div>
      <div class="card"><h1><?= h(tp('saved_customers')) ?></h1>
        <div class="table-wrap"><table><thead><tr><th>الاسم</th><th>VAT</th><th>العنوان</th></tr></thead><tbody><?php foreach ($customers as $c): ?><tr><td><?= h($c['name'] ?? '') ?></td><td class="mono"><?= h($c['vat'] ?? '') ?></td><td><?= h($c['address'] ?? '') ?></td></tr><?php endforeach; ?></tbody></table></div>
      </div>
    </div>

  <?php elseif ($route === 'phase2'): ?>
    <div class="grid grid-2">
      <div class="card">
        <div class="toolbar" style="justify-content:space-between;align-items:flex-start">
          <div>
            <h1>جاهزية الربط B2B مع الزكاة</h1>
            <div class="muted">بما إنك هتطلع فواتير من شركة إلى شركة، فالمسار الأساسي هنا هو <strong>Standard / B2B</strong> ثم <strong>Clearance</strong> بعد اكتمال التهيئة.</div>
          </div>
          <span class="pill"><?= (int)$phase2Readiness['completed'] ?>/<?= (int)$phase2Readiness['total'] ?></span>
        </div>
        <div class="progress"><span style="width:<?= (int)$phase2Readiness['percent'] ?>%"></span></div>
        <div class="callout <?= $phase2Readiness['ready'] ? 'success' : 'warn' ?>"><?= $phase2Readiness['ready'] ? 'الواجهة جاهزة للحفظ والتفعيل. فعّل الخيار بالأسفل واستخدم Clearance للفواتير القياسية.' : h($phase2Readiness['next_step']) ?></div>
        <ul class="checklist">
          <?php foreach ($phase2Readiness['checks'] as $check): ?>
            <li class="check-item">
              <div class="check-meta">
                <strong><?= h($check['label']) ?></strong>
                <span><?= h($check['hint']) ?></span>
              </div>
              <span class="<?= !empty($check['ok']) ? 'badge-ok' : 'badge-warn' ?>"><?= !empty($check['ok']) ? 'جاهز' : 'ناقص' ?></span>
            </li>
          <?php endforeach; ?>
        </ul>
      </div>
      <div class="card helper-grid">
        <div>
          <h1>المطلوب منك من موقع الزكاة</h1>
          <div class="muted">البرنامج جهزته بحيث يفصل بين <strong>Compliance</strong> و <strong><?= h($phase2SubmissionLabel) ?></strong>؛ أنت فقط هتجيب الأكواد من البوابة أو الـSandbox وتحطها هنا.</div>
        </div>
        <div class="step-grid">
          <div class="step-card">
            <strong>1) OTP من Fatoora Portal</strong>
            من البوابة: افتح onboarding للجهاز أو الـsolution unit وولّد OTP، ثم استخدمه خلال مدته في خطوة طلب Compliance CSID.
          </div>
          <div class="step-card">
            <strong>2) Compliance CSID</strong>
            بعد توليد CSR من هنا، اطلب Compliance CSID عبر OTP. النظام سيحفظ لك شهادة الـCompliance وطلب الـCompliance Request ID.
          </div>
          <div class="step-card">
            <strong>3) <?= h($phase2SubmissionLabel) ?></strong>
            بعد نجاح فحص الـCompliance، هتحتاج التوكن + الـSecret + الشهادة الخاصة بخطوة الإرسال الفعلي. الصقهم في النموذج بالأسفل.
          </div>
          <div class="step-card">
            <strong>4) تشغيل B2B / Clearance</strong>
            بمجرد اكتمال الجاهزية وتفعيل Phase 2، الفواتير القياسية هتظهر لك في الأرشيف بزر Clearance لأن ده مسار شركة إلى شركة.
          </div>
        </div>
        <div class="mini-stat-grid">
          <div class="mini-stat"><span class="label">Environment</span><strong><?= h($config['phase2']['environment'] ?? 'Sandbox') ?></strong></div>
          <div class="mini-stat"><span class="label">Activation</span><strong><?= !empty($config['phase2']['enabled']) ? 'Enabled' : 'Disabled' ?></strong></div>
          <div class="mini-stat"><span class="label">QR Mode</span><strong><?= h($config['phase2']['qr_mode'] ?? 'auto') ?></strong></div>
          <div class="mini-stat"><span class="label">CSR</span><strong><?= !empty($config['phase2']['csr_path']) && file_exists((string)$config['phase2']['csr_path']) ? 'Ready' : 'Missing' ?></strong></div>
          <div class="mini-stat"><span class="label">Compliance</span><strong><?= phase2_compliance_request_id($config) !== '' ? 'Tracked' : 'Missing' ?></strong></div>
          <div class="mini-stat"><span class="label"><?= h($phase2SubmissionLabel) ?></span><strong><?= phase2_submission_credentials_ready($config) ? 'Ready' : 'Missing' ?></strong></div>
        </div>
        <div class="table-wrap"><table>
          <tr><th>CSR Path</th><td class="mono"><?= h(storage_relative_path((string)($config['phase2']['csr_path'] ?? ''))) ?></td></tr>
          <tr><th>Private Key Path</th><td class="mono"><?= h(storage_relative_path((string)($config['phase2']['private_key_path'] ?? ''))) ?></td></tr>
          <tr><th>Compliance Cert Path</th><td class="mono"><?= h(storage_relative_path(phase2_compliance_cert_path($config))) ?></td></tr>
          <tr><th><?= h($phase2SubmissionLabel) ?> Cert Path</th><td class="mono"><?= h(storage_relative_path(phase2_submission_certificate_path($config))) ?></td></tr>
          <tr><th>Last API Response</th><td class="mono"><?= h(storage_relative_path((string)($config['phase2']['production_last_api_response_path'] ?? ($config['phase2']['last_api_response_path'] ?? '')))) ?></td></tr>
        </table></div>
      </div>
    </div>

    <div class="card" style="margin-top:18px">
      <div class="toolbar" style="justify-content:space-between;align-items:flex-start">
        <div>
          <h1>تشخيص الاستضافة وQR</h1>
          <div class="muted">لو واجهت مشكلة في ظهور QR أو حفظ الأرشيف، راجع المؤشرات دي أولًا.</div>
        </div>
        <span class="pill"><?= (int)$runtimeDiagnostics['completed'] ?>/<?= (int)$runtimeDiagnostics['total'] ?></span>
      </div>
      <div class="progress"><span style="width:<?= (int)$runtimeDiagnostics['percent'] ?>%"></span></div>
      <ul class="checklist">
        <?php foreach ($runtimeDiagnostics['checks'] as $diag): ?>
          <li class="check-item">
            <div class="check-meta"><strong><?= h($diag['label']) ?></strong><span class="mono"><?= h($diag['hint']) ?></span></div>
            <span class="<?= !empty($diag['ok']) ? 'badge-ok' : 'badge-warn' ?>"><?= !empty($diag['ok']) ? 'جاهز' : 'راجع' ?></span>
          </li>
        <?php endforeach; ?>
      </ul>
    </div>

    <div class="grid grid-2" style="margin-top:18px">
      <div class="card">
        <h1>إعدادات التفعيل</h1>
        <div class="callout <?= $phase2Readiness['ready'] ? 'success' : 'warn' ?>"><?= $phase2Readiness['ready'] ? 'كل عناصر الجاهزية مكتملة. تقدر الآن تحفظ وتفعّل Phase 2.' : 'احفظ البيانات الآن براحتك. التفعيل نفسه لن يثبت إلا بعد اكتمال العناصر المطلوبة.' ?></div>
        <form method="post" class="form-grid">
          <?= csrf_input() ?>
          <input type="hidden" name="action" value="save_phase2_settings">
          <div>
            <label>Environment</label>
            <select name="environment">
              <option value="Sandbox" <?= (($config['phase2']['environment'] ?? '')==='Sandbox')?'selected':'' ?>>Sandbox</option>
              <option value="Production" <?= (($config['phase2']['environment'] ?? '')==='Production')?'selected':'' ?>>Production</option>
            </select>
            <div class="field-hint">ابدأ بـ Sandbox للتجربة، وبعدها انقل نفس المسار إلى Production ببياناته الحقيقية.</div>
          </div>
          <div>
            <label>Device UUID / ID</label>
            <input name="device_id" value="<?= h($config['phase2']['device_id'] ?? '') ?>">
            <div class="field-hint">مهم لربط نفس الجهاز أو الـEGS unit داخل البوابة وداخل الـCSR.</div>
          </div>
          <div>
            <label>OTP</label>
            <input name="otp" value="<?= h($config['phase2']['otp'] ?? '') ?>">
            <div class="field-hint">انسخه من البوابة ثم استخدمه في زر Request Compliance CSID.</div>
          </div>
          <div>
            <label>QR Mode</label>
            <select name="qr_mode">
              <option value="auto" <?= (($config['phase2']['qr_mode'] ?? 'auto')==='auto')?'selected':'' ?>>Auto</option>
              <option value="phase2" <?= (($config['phase2']['qr_mode'] ?? '')==='phase2')?'selected':'' ?>>Phase 2 Always</option>
              <option value="phase1" <?= (($config['phase2']['qr_mode'] ?? '')==='phase1')?'selected':'' ?>>Phase 1 Only</option>
            </select>
            <div class="field-hint">للاستخدام اليومي خليها Auto، وسيستخدم Phase 2 تلقائيًا لما تبقى الشهادة جاهزة.</div>
          </div>

          <div class="full"><label><input type="checkbox" name="phase2_enabled" value="1" <?= !empty($config['phase2']['enabled']) ? 'checked' : '' ?>> تفعيل Phase 2 الآن (مع منع التفعيل لو أي خطوة ناقصة)</label></div>

          <div class="full subsection-title">الحالة الحالية</div>
          <div><label>Compliance Request ID الحالي</label><input class="mono" value="<?= h(phase2_compliance_request_id($config) ?: 'غير محفوظ') ?>" readonly></div>
          <div><label><?= h($phase2SubmissionLabel) ?> الحالي</label><input class="mono" value="<?= phase2_submission_credentials_ready($config) ? 'محفوظ وجاهز للإرسال' : 'غير محفوظ' ?>" readonly></div>
          <div><label>Compliance Token الحالي</label><input class="mono" value="<?= h(mask_secret(phase2_compliance_token($config), 6) ?: 'غير محفوظ') ?>" readonly></div>
          <div><label>Compliance Secret الحالي</label><input class="mono" value="<?= h(mask_secret(phase2_compliance_secret($config), 4) ?: 'غير محفوظ') ?>" readonly></div>
          <div><label><?= h($phase2SubmissionLabel) ?> Token الحالي</label><input class="mono" value="<?= h(mask_secret(phase2_production_token($config), 6) ?: 'غير محفوظ') ?>" readonly></div>
          <div><label><?= h($phase2SubmissionLabel) ?> Secret الحالي</label><input class="mono" value="<?= h(mask_secret(phase2_production_secret($config), 4) ?: 'غير محفوظ') ?>" readonly></div>
          <div><label>Private Key الحالي</label><input class="mono" value="<?= (!empty($config['phase2']['private_key_path']) && file_exists((string)$config['phase2']['private_key_path'])) ? 'محفوظ داخل التخزين الآمن' : 'غير موجود' ?>" readonly></div>
          <div><label>Compliance Certificate</label><input class="mono" value="<?= (phase2_compliance_cert_path($config) !== '' && file_exists(phase2_compliance_cert_path($config))) ? 'محفوظ داخل التخزين الآمن' : 'غير موجود' ?>" readonly></div>
          <div><label><?= h($phase2SubmissionLabel) ?> Certificate</label><input class="mono" value="<?= (phase2_submission_certificate_path($config) !== '' && file_exists(phase2_submission_certificate_path($config))) ? 'محفوظ داخل التخزين الآمن' : 'غير موجود' ?>" readonly></div>
          <div><label>Key Algorithm</label><input class="mono" value="<?= h((string)($config['phase2']['key_algorithm'] ?? '')) ?: 'Unknown' ?>" readonly></div>

          <div class="full subsection-title">مدخلات التفعيل أو الاستبدال عند الحاجة</div>
          <div class="full"><label>Compliance Request ID</label><input class="mono" name="compliance_request_id" value="<?= h(phase2_compliance_request_id($config)) ?>" placeholder="ألصقه هنا لو طلع لك من الـAPI أو من الـSandbox"></div>
          <div class="full"><label><?= h($phase2SubmissionLabel) ?> Binary Security Token</label><textarea class="mono" name="production_binary_security_token" placeholder="اتركه فارغًا لو مش هتبدل القيمة الحالية"></textarea></div>
          <div class="full"><label><?= h($phase2SubmissionLabel) ?> Secret</label><input class="mono" type="password" name="production_secret" autocomplete="new-password" placeholder="اتركه فارغًا لو مش هتبدل القيمة الحالية"></div>
          <div class="full"><label>Private Key PEM</label><textarea class="mono" name="private_key_pem" placeholder="اختياري للصق المفتاح الخاص لو نقلته من بيئة أخرى"></textarea></div>
          <div class="full"><label>Compliance Certificate PEM</label><textarea class="mono" name="compliance_certificate_pem" placeholder="اختياري: الصق شهادة الـCompliance لو محتاج تحفظها يدويًا"></textarea></div>
          <div class="full"><label><?= h($phase2SubmissionLabel) ?> Certificate PEM</label><textarea class="mono" name="production_certificate_pem" placeholder="الصق شهادة الإرسال الفعلية هنا عندما تحصل عليها"></textarea></div>
          <div class="full muted">الأسرار والمفاتيح لا تُعرض هنا نصًا. أنت فقط تشوف حالة الحفظ وتستبدل القيم عند الحاجة.</div>
          <div><button type="submit">حفظ إعدادات Phase 2</button></div>
        </form>
      </div>

      <div class="card helper-grid">
        <div>
          <h1>أدوات الجاهزية</h1>
          <div class="muted">رتبت لك الخطوات بحيث ما تحتاجش تلف بين الشاشة والوثائق. اعملهم بالترتيب ده.</div>
        </div>

        <div class="step-grid">
          <div class="step-card">
            <strong>أ) Generate CSR + Key</strong>
            شغّل الزر مرة واحدة لكل جهاز أو بيئة. لو بيئة الخادم تدعم EC، النظام يفضّل ECDSA P-256 تلقائيًا.
            <div class="toolbar" style="margin-top:12px">
              <form method="post"><?= csrf_input() ?><input type="hidden" name="action" value="generate_csr"><button class="btn secondary">Generate CSR + Key</button></form>
            </div>
          </div>
          <div class="step-card">
            <strong>ب) Request Compliance CSID</strong>
            بعد ما تحط OTP فوق، اطلب الـCompliance مباشرة من هنا. هيتم حفظ الشهادة والـtoken والـsecret داخل مجلد البيانات الآمن.
            <form method="post" class="form-grid" style="margin-top:12px">
              <?= csrf_input() ?>
              <input type="hidden" name="action" value="request_compliance">
              <div class="full"><label>OTP المستخدم في الطلب</label><input name="otp" value="<?= h($config['phase2']['otp'] ?? '') ?>"></div>
              <div><button class="btn warn">Request Compliance CSID</button></div>
            </form>
          </div>
        </div>

        <?php if ($csrPreview): ?>
          <div>
            <div class="subsection-title">CSR Preview</div>
            <div class="codebox mono"><?= h($csrPreview['csr_pem'] ?? '') ?></div>
          </div>
        <?php endif; ?>

        <div class="callout">
          <strong>المسار العملي المختصر:</strong>
          <ol class="soft-list">
            <li>أكمل بيانات الشركة والعنوان من صفحة الإعدادات.</li>
            <li>ولّد CSR والمفتاح.</li>
            <li>هات OTP واطلب Compliance CSID.</li>
            <li>نفّذ فحص الـCompliance في بوابة الزكاة أو الـSandbox.</li>
            <li>هات <?= h($phase2SubmissionLabel) ?> والصقه هنا.</li>
            <li>فعّل Phase 2 وابدأ Clearance للفواتير القياسية B2B.</li>
          </ol>
        </div>
      </div>
    </div>

  <?php elseif ($route === 'activation'): ?>
    <div class="grid grid-2">
      <div class="card"><h1>تفعيل لوحة المستخدم</h1><p class="muted">المستخدم لا يستطيع دخول بقية الصفحات إلا بعد إدخال كود التفعيل الصحيح.</p>
        <form method="post" class="form-grid">
          <?= csrf_input() ?>
          <input type="hidden" name="action" value="activate">
          <div class="full"><label>كود الطلب</label><input class="mono" name="request_code" value="<?= h(build_request_code()) ?>" readonly></div>
          <div class="full"><label>مفتاح التفعيل</label><input class="mono" name="activation_key" placeholder="ACT-YYYYMMDD-XXXXXXXXXXXX-XXXXXXXXXXXXXXXX"></div>
          <div><button type="submit">تفعيل اللوحة</button></div>
        </form>
      </div>
      <div class="card"><h1>تعليمات سريعة</h1>
        <ol style="margin:0;padding-right:18px;line-height:2">
          <li>انسخ كود الطلب الظاهر هنا.</li>
          <li>ولّد مفتاح التفعيل وحدد تاريخ الانتهاء.</li>
          <li>أرسل المفتاح للمستخدم ليتم فتح اللوحة بالكامل.</li>
          <li>بعد التفعيل تُفتح بقية الصفحات تلقائيًا.</li>
        </ol>
        <div class="small" style="margin-top:18px">بعد التفعيل ستظهر للمستخدم: لوحة التحكم، الإعدادات، العملاء، Phase 2، الأرشيف، وإصدار الفواتير.</div>
      </div>
    </div>

  <?php elseif ($route === 'invoice'): ?>
    <?php $invoiceCustomers = customers_all(); ?>
    <div class="card"><h1><?= h(tp('new_invoice')) ?></h1>
      <p class="muted"><?= h(tp('company_optional_hint')) ?></p>
      <p class="muted">سيتم حفظ ملفات الأرشيف داخل التخزين الآمن، وفتحها عبر روابط داخلية محمية بدل المسارات المباشرة.</p>
      <div class="callout <?= !empty($config['phase2']['enabled']) ? 'success' : 'warn' ?>"><?= !empty($config['phase2']['enabled']) ? 'Phase 2 مفعلة حاليًا، وسيتم استخدام الإعدادات حسب وضع QR المختار.' : 'Phase 2 غير مفعلة حاليًا. يمكنك الاستمرار بإصدار الفواتير ورفع الجاهزية من صفحة Phase 2.' ?></div>
      <div class="callout">هذه الشاشة مضبوطة الآن على استخدام <strong>الفاتورة القياسية Standard</strong> بشكل افتراضي، لأنك تعمل شركة إلى شركة. أدخل اسم العميل ورقم VAT الخاص به، وسيظهر في الأرشيف زر <strong>Clearance</strong> بدل Reporting.</div>
      <div class="callout success">عرض QR الآن يمر بنفس الدومين أولًا، أو يندمج داخل الفاتورة مباشرة إذا تم تحميله بنجاح وقت الإنشاء. ده يقلل مشاكل الاستضافة المشتركة وCSP.</div>
      <div class="mini-stat-grid" style="margin:0 0 16px">
        <div class="mini-stat"><span class="label">Next Invoice</span><strong><?= h(next_invoice_id_preview()) ?></strong></div>
        <div class="mini-stat"><span class="label">Submission</span><strong><?= !empty($config['phase2']['enabled']) ? h($phase2SubmissionLabel) : 'Draft / Phase 1' ?></strong></div>
        <div class="mini-stat"><span class="label">Archive</span><strong>Secure</strong></div>
      </div>
      <form method="post">
        <?= csrf_input() ?>
        <input type="hidden" name="action" value="generate_invoice">
        <div class="form-grid">
          <div><label><?= h(tp('invoice_no')) ?></label><input name="invoice_id" value="<?= h(next_invoice_id_preview()) ?>"></div>
          <div><label><?= h(tp('issue_date')) ?></label><input type="datetime-local" name="issue_date" value="<?= h(date('Y-m-d\TH:i')) ?>"></div>
          <div><label><?= h(tp('pick_customer')) ?></label><select id="customer_picker"><option value=""><?= h(tp('quick_select')) ?></option><?php foreach ($invoiceCustomers as $idx => $customer): ?><option value="<?= $idx ?>" data-name="<?= h($customer['name'] ?? '') ?>" data-vat="<?= h($customer['vat'] ?? '') ?>" data-address="<?= h($customer['address'] ?? '') ?>"><?= h($customer['name'] ?? '') ?><?= !empty($customer['vat']) ? ' - ' . h($customer['vat']) : '' ?></option><?php endforeach; ?></select></div>
          <div><label><?= h(tp('buyer_name')) ?></label><input id="buyer_name" name="buyer_name"></div>
          <div><label><?= h(tp('buyer_vat')) ?></label><input id="buyer_vat" name="buyer_vat" placeholder="15 رقم للفاتورة القياسية"></div>
          <div><label><?= h(tp('invoice_type')) ?></label><select name="invoice_kind"><option value="Standard" selected><?= h(tp('tax_invoice_standard')) ?></option><option value="Auto"><?= h(tp('auto')) ?></option><option value="Simplified"><?= h(tp('tax_invoice_simplified')) ?></option></select><div class="field-hint">الافتراضي هنا Standard لأن استخدامك الأساسي B2B.</div></div>
          <div><label><?= h(tp('currency')) ?></label><select name="currency"><?php foreach (['SAR','USD','EUR'] as $cur): ?><option value="<?= $cur ?>" <?= (($config['defaults']['currency'] ?? 'SAR') === $cur) ? 'selected' : '' ?>><?= $cur ?></option><?php endforeach; ?></select></div>
          <div><label><?= h(tp('print_language')) ?></label><select name="print_language"><option value="ar" <?= $lang === 'ar' ? 'selected' : '' ?>><?= h(tp('arabic_print')) ?></option><option value="en" <?= $lang === 'en' ? 'selected' : '' ?>><?= h(tp('english_print')) ?></option><option value="bi"><?= h(tp('bilingual_print')) ?></option></select></div>
          <div class="full"><label><?= h(tp('buyer_address')) ?></label><textarea id="buyer_address" name="buyer_address"></textarea></div>
        </div>
        <h2 style="margin-top:24px"><?= h(tp('items')) ?></h2>
        <table class="items-table" id="items-table"><thead><tr><th><?= h(tp('description')) ?></th><th><?= h(tp('qty')) ?></th><th><?= h(tp('unit_price')) ?></th><th>VAT Rate</th><th></th></tr></thead><tbody><tr><td><input name="item_description[]"></td><td><input name="item_qty[]" type="number" step="0.01" value="1"></td><td><input name="item_price[]" type="number" step="0.01" value="0"></td><td><input name="item_vat[]" type="number" step="0.01" value="<?= h((string)($config['defaults']['vat_rate'] ?? 0.15)) ?>"></td><td><button type="button" class="btn secondary" onclick="this.closest('tr').remove()"><?= h(tp('delete')) ?></button></td></tr></tbody></table>
        <div class="toolbar sticky-actions" style="margin-top:12px"><button type="button" class="btn secondary" onclick="addRow()"><?= h(tp('add_item')) ?></button><button type="submit" class="btn success"><?= h(tp('generate_invoice')) ?></button></div>
        <div class="live-summary" id="liveSummary">
          <div class="live-summary-title"><?= h(tp('invoice_live_summary')) ?></div>
          <div class="live-summary-grid">
            <div><span><?= h(tp('subtotal')) ?></span><strong id="sumSubtotal">0.00</strong></div>
            <div><span><?= h(tp('vat_total')) ?></span><strong id="sumVat">0.00</strong></div>
            <div><span><?= h(tp('grand_total')) ?></span><strong id="sumTotal">0.00</strong></div>
          </div>
        </div>
      </form>
      <?php if (!empty($lastFiles)): $mp = read_json_file($lastFiles['metadata'], []); ?>
      <div class="card" style="margin-top:18px;background:linear-gradient(180deg,rgba(24,17,11,.98),rgba(16,12,9,.98))">
        <h3>آخر فاتورة تم إنشاؤها</h3>
        <div class="actions">
          <a class="btn" href="<?= h(archive_file_url($lastFiles['metadata'], 'html')) ?>" target="_blank">فتح نسخة الطباعة</a>
          <a class="btn secondary" href="<?= h(archive_file_url($lastFiles['metadata'], 'xml')) ?>" target="_blank">فتح XML</a>
        </div>
        <div class="table-wrap"><table style="margin-top:14px"><tr><th>Hash</th><td class="mono"><?= h($mp['invoice_hash_base64'] ?? '') ?></td></tr><tr><th>QR TLV Base64</th><td class="mono"><?= h($mp['effective_qr_base64'] ?? '') ?></td></tr><tr><th>Recommended Submission</th><td><?= h($mp['recommended_submission'] ?? '') ?></td></tr></table></div>
      </div>
      <?php endif; ?>
    </div>

  <?php elseif ($route === 'archive'): ?>
    <div class="card"><h1>أرشيف الفواتير</h1>
      <div class="callout">لو عندك فواتير قديمة كان QR فيها لا يظهر، استخدم زر <strong>إعادة بناء HTML</strong> للفواتير القديمة بعد هذا التحديث.</div>
      <div class="actions" style="margin-bottom:14px">
        <form method="post" style="display:inline"><?= csrf_input() ?><input type="hidden" name="action" value="repair_all_archive_html"><button class="btn secondary">إعادة بناء كل HTML</button></form>
      </div>
      <div class="table-wrap"><table><thead><tr><th>الرقم</th><th>التاريخ</th><th>النوع</th><th>الحالة</th><th>الإجمالي</th><th>إجراءات</th></tr></thead><tbody>
      <?php foreach ($archive as $row): ?>
        <tr>
          <td><?= h($row['invoice_id'] ?? '') ?></td>
          <td><?= h($row['issue_utc'] ?? '') ?></td>
          <td><?= h($row['invoice_kind'] ?? '') ?></td>
          <td><?= h($row['status'] ?? 'Draft') ?></td>
          <td><?= number_format((float)($row['totals']['payable_amount'] ?? 0),2) ?> <?= h($row['currency'] ?? '') ?></td>
          <td><div class="actions">
            <?php if (!empty($row['files']['html'])): ?><a class="btn secondary" target="_blank" href="<?= h(archive_file_url($row['_path'], 'html')) ?>">HTML</a><?php endif; ?>
            <?php if (!empty($row['files']['xml'])): ?><a class="btn secondary" target="_blank" href="<?= h(archive_file_url($row['_path'], 'xml')) ?>">XML</a><?php endif; ?>
            <form method="post" style="display:inline"><?= csrf_input() ?><input type="hidden" name="action" value="repair_invoice_html"><input type="hidden" name="metadata_path" value="<?= h($row['_path']) ?>"><button class="btn secondary">إصلاح HTML</button></form>
            <form method="post" style="display:inline"><?= csrf_input() ?><input type="hidden" name="action" value="submit_invoice"><input type="hidden" name="metadata_path" value="<?= h($row['_path']) ?>"><button class="btn <?= (($row['invoice_kind'] ?? '') === 'Standard') ? 'warn' : 'success' ?>"><?= (($row['invoice_kind'] ?? '') === 'Standard') ? 'Clearance' : 'Reporting' ?></button></form>
          </div></td>
        </tr>
      <?php endforeach; ?>
      </tbody></table></div>
    </div>
  <?php endif; ?>
</main></div>
<script>
function addRow(){const tbody=document.querySelector('#items-table tbody');const tr=document.createElement('tr');tr.innerHTML='<td><input name="item_description[]"></td><td><input name="item_qty[]" type="number" step="0.01" value="1"></td><td><input name="item_price[]" type="number" step="0.01" value="0"></td><td><input name="item_vat[]" type="number" step="0.01" value="<?= h((string)($config['defaults']['vat_rate'] ?? 0.15)) ?>"></td><td><button type="button" class="btn secondary" onclick="this.closest(\'tr\').remove()"><?= h(tp('delete')) ?></button></td>';tbody.appendChild(tr);}
const picker=document.getElementById('customer_picker');
if(picker){picker.addEventListener('change',function(){const opt=this.options[this.selectedIndex];document.getElementById('buyer_name').value=opt?.dataset?.name||'';document.getElementById('buyer_vat').value=opt?.dataset?.vat||'';document.getElementById('buyer_address').value=opt?.dataset?.address||'';});}
function toggleMenu(force){const el=document.getElementById("appLayout");const open=typeof force==="boolean"?force:!el.classList.contains("menu-open");el.classList.toggle("menu-open",open);}document.querySelectorAll(".nav-link").forEach(a=>a.addEventListener("click",()=>toggleMenu(false)));window.addEventListener("resize",()=>{if(window.innerWidth>980){toggleMenu(false);}});
function updateLiveSummary(){const rows=[...document.querySelectorAll('#items-table tbody tr')];if(!rows.length)return;let subtotal=0,vat=0;rows.forEach(row=>{const qty=parseFloat(row.querySelector('input[name="item_qty[]"]')?.value||0)||0;const price=parseFloat(row.querySelector('input[name="item_price[]"]')?.value||0)||0;const rate=parseFloat(row.querySelector('input[name="item_vat[]"]')?.value||0)||0;const line=qty*price;subtotal+=line;vat+=line*rate;});const total=subtotal+vat;const fmt=n=>n.toLocaleString(undefined,{minimumFractionDigits:2,maximumFractionDigits:2});const a=document.getElementById('sumSubtotal');const b=document.getElementById('sumVat');const c=document.getElementById('sumTotal');if(a)a.textContent=fmt(subtotal);if(b)b.textContent=fmt(vat);if(c)c.textContent=fmt(total);}
document.addEventListener('input',e=>{if(e.target.closest('#items-table')) updateLiveSummary();});updateLiveSummary();
</script>
<?php if ($route !== 'activation'): ?>
<a href="https://wa.me/966596246462?text=Hello%20I%20need%20support%20for%20BK%20Invoice" target="_blank" class="wa-support" aria-label="<?= h(tp('wa_support')) ?>"><span class="wa-icon">💬</span><span><?= h(tp('wa_support')) ?></span></a>
<?php endif; ?>
</body></html>
