<?php
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/src/auth.php';
require_login();

if (session_status() === PHP_SESSION_NONE) session_start();
set_time_limit(0);

function esc($v){ return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }
function json_err($msg){ header('Content-Type: application/json; charset=utf-8'); echo json_encode(['ok'=>0,'msg'=>$msg]); exit; }

 $lang = $_GET['lang'] ?? ($_SESSION['lang'] ?? 'en');
if (isset($_GET['lang'])) { $_SESSION['lang'] = $_GET['lang'] === 'ar' ? 'ar' : 'en'; $lang = $_SESSION['lang']; }
 $is_ar = $lang === 'ar';

function session_save_parsed(array $rows){ $_SESSION['purchase_parsed_all'] = $rows; }
function session_load_parsed(){ return $_SESSION['purchase_parsed_all'] ?? null; }
function session_clear_parsed(){ unset($_SESSION['purchase_parsed_all'], $_SESSION['purchase_zero_choice']); }

 $has_suppliers = false;
try { $res = $pdo->query("SHOW TABLES LIKE 'suppliers'")->fetchColumn(); if ($res) $has_suppliers = true; } catch (Exception $e){}
if ($has_suppliers) $suppliers = $pdo->query("SELECT id, name, COALESCE(balance,0) AS balance FROM suppliers ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);
else $suppliers = $pdo->query("SELECT id, name, COALESCE(balance,0) AS balance FROM customers ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);

 $cols = $pdo->query("SHOW COLUMNS FROM products")->fetchAll(PDO::FETCH_COLUMN);
 $nameField = in_array('name_en', $cols) ? 'name_en' : (in_array('name_ar',$cols) ? 'name_ar' : 'name');

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_zero_choice'])) {
    header('Content-Type: application/json; charset=utf-8');
    $choice = $_POST['choice'] ?? 'include';
    $all = session_load_parsed();
    if ($all === null) json_err($is_ar ? 'لا توجد بيانات مؤقتة.' : 'No parsed data');
    if ($choice === 'ignore') {
        $filtered = array_values(array_filter($all, function($r){ return floatval($r['qty']) > 0; }));
        session_save_parsed($filtered);
        $_SESSION['purchase_zero_choice'] = 'ignore';
        echo json_encode(['ok'=>1,'msg'=>'zeros removed','total'=>count($filtered)]);
        exit;
    } else {
        $_SESSION['purchase_zero_choice'] = 'include';
        echo json_encode(['ok'=>1,'msg'=>'zeros kept','total'=>count($all)]);
        exit;
    }
}

if (isset($_GET['load_chunk']) && isset($_SESSION['purchase_parsed_all'])) {
    header('Content-Type: application/json; charset=utf-8');
    $start = max(0, intval($_GET['start'] ?? 0));
    $chunk = max(1, intval($_GET['chunk'] ?? 200));
    $all = session_load_parsed();
    $slice = array_slice($all, $start, $chunk);
    echo json_encode(['ok'=>1,'start'=>$start,'chunk'=>count($slice),'rows'=>$slice,'total'=>count($all)]);
    exit;
}

if (isset($_GET['download_template']) && $_GET['download_template']=='1') {
    $filename = 'purchase_template_' . date('Ymd') . '.xlsx';
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment; filename="'.$filename.'"');
    $zip = new ZipArchive();
    $tmp = tempnam(sys_get_temp_dir(), 'xlsx');
    $zip->open($tmp, ZipArchive::OVERWRITE);
    $zip->addFromString('[Content_Types].xml','<?xml version="1.0" encoding="UTF-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/><Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/></Types>');
    $zip->addFromString('_rels/.rels','<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>');
    $zip->addFromString('xl/_rels/workbook.xml.rels','<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>');
    $zip->addFromString('xl/workbook.xml','<?xml version="1.0" encoding="UTF-8"?><workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Purchase Template" sheetId="1" r:id="rId1"/></sheets></workbook>');
    $zip->addFromString('xl/styles.xml','<?xml version="1.0" encoding="UTF-8"?><styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><fonts count="1"><font><name val="Calibri"/><sz val="11"/></font></fonts><fills count="1"><fill><patternFill patternType="none"/></fill></fills><borders count="1"><border/></borders><cellXfs count="1"><xf fontId="0" fillId="0" borderId="0"/></cellXfs></styleSheet>');
    $sheet = '<?xml version="1.0" encoding="UTF-8"?><worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData><row r="1"><c r="A1" t="inlineStr"><is><t>Product Name</t></is></c><c r="B1" t="inlineStr"><is><t>SKU</t></is></c><c r="C1" t="inlineStr"><is><t>Qty</t></is></c><c r="D1" t="inlineStr"><is><t>Cost</t></is></c><c r="E1" t="inlineStr"><is><t>Sale Price</t></is></c></row></sheetData></worksheet>';
    $zip->addFromString('xl/worksheets/sheet1.xml', $sheet);
    $zip->close();
    readfile($tmp); unlink($tmp); exit;
}

if (isset($_GET['clear_parsed']) && $_GET['clear_parsed']=='1') { session_clear_parsed(); header('Location: purchase_invoice.php'); exit; }

 $errors = []; $success = false; $saved_purchase_id = null;
 $parsed_items = []; $parsed_count = 0; $zero_count = 0; $invoice_total = 0.0;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload_excel'])) {
    session_clear_parsed();
    if (empty($_FILES['csv_file']) || $_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
        $errors[] = $is_ar ? 'يرجى اختيار ملف صالح للرفع.' : 'Please select a valid file to upload.';
    } else {
        $tmp = $_FILES['csv_file']['tmp_name'];
        $ext = strtolower(pathinfo($_FILES['csv_file']['name'], PATHINFO_EXTENSION));
        $all_rows = [];
        if ($ext === 'xlsx') {
            $zip = new ZipArchive;
            if ($zip->open($tmp) === true) {
                $shared = [];
                if (($idx = $zip->locateName('xl/sharedStrings.xml')) !== false) {
                    $xml = simplexml_load_string($zip->getFromIndex($idx));
                    foreach ($xml->si as $si) {
                        if (isset($si->t)) $shared[] = (string)$si->t;
                        else { $txt=''; if($si->r) foreach ($si->r as $r) $txt .= (string)$r->t; $shared[] = $txt; }
                    }
                }
                if (($idx = $zip->locateName('xl/worksheets/sheet1.xml')) !== false) {
                    $xml = simplexml_load_string($zip->getFromIndex($idx));
                    foreach ($xml->sheetData->row as $row) {
                        $r = [];
                        foreach ($row->c as $c) {
                            $cellRef = (string)$c['r']; preg_match('/^([A-Z]+)[0-9]+$/', $cellRef, $m);
                            $col = $m[1] ?? null; $val = '';
                            if (isset($c['t']) && (string)$c['t'] === 's') { $v = (string)$c->v; $val = $shared[intval($v)] ?? $v; }
                            elseif (isset($c['t']) && (string)$c['t'] === 'inlineStr') { $val = (string)$c->is->t; }
                            else { $val = (string)$c->v; }
                            if ($col !== null) $r[$col] = $val;
                        }
                        $all_rows[] = [$r['A'] ?? '', $r['B'] ?? '', $r['C'] ?? '', $r['D'] ?? '', $r['E'] ?? ''];
                    }
                }
                $zip->close();
            }
            if (!empty($all_rows)) {
                $header = array_map('strtolower', array_map('trim', $all_rows[0]));
                $parsed_list = [];
                foreach (array_slice($all_rows,1) as $r) {
                    $parsed_list[] = ['name'=>trim($r[0]),'sku'=>trim($r[1]),'qty'=>floatval($r[2]),'cost'=>floatval($r[3]),'sale_price'=>floatval($r[4])];
                }
                session_save_parsed($parsed_list);
            }
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && (isset($_POST['confirm_save']) || isset($_POST['save_direct']))) {
    $supplier_id = !empty($_POST['supplier_id']) ? intval($_POST['supplier_id']) : null;
    $datetime = !empty($_POST['datetime']) ? $_POST['datetime'] : date('Y-m-d H:i:s');
    $paid_now = isset($_POST['paid_now']) ? floatval($_POST['paid_now']) : 0.0;
    $note = trim($_POST['note'] ?? '');
    
    $items_to_save = [];
    if (isset($_POST['use_manual']) && $_POST['use_manual']=='1') {
        $pn = $_POST['pname'] ?? []; $sk = $_POST['sku'] ?? []; $qt = $_POST['qty'] ?? []; $co = $_POST['cost'] ?? []; $sa = $_POST['sale_price'] ?? [];
        for ($i=0;$i<count($pn);$i++){
            if(trim($pn[$i])==='' && floatval($qt[$i]??0)==0) continue;
            $items_to_save[] = ['name'=>trim($pn[$i]),'sku'=>trim($sk[$i]),'qty'=>floatval($qt[$i]),'cost'=>floatval($co[$i]),'sale_price'=>floatval($sa[$i])];
        }
    } else {
        $items_to_save = session_load_parsed() ?: [];
    }

    if (count($items_to_save) > 0) {
        try {
            $pdo->beginTransaction();
            $total = 0.0;
            foreach ($items_to_save as $it) $total += round(floatval($it['qty']) * floatval($it['cost']), 2);
            
            $ins = $pdo->prepare("INSERT INTO purchases (supplier_id, total, paid, note, created_at) VALUES (?, ?, ?, ?, ?)");
            $ins->execute([$supplier_id, $total, $paid_now, $note, $datetime]);
            $purchase_id = $pdo->lastInsertId();

            foreach ($items_to_save as $it) {
                $pdo->prepare("INSERT INTO products (sku, {$nameField}, cost, price, stock, created_at) VALUES (?, ?, ?, ?, ?, NOW())")
                    ->execute([$it['sku'], $it['name'], $it['cost'], $it['sale_price'], 0]);
                $pid = $pdo->lastInsertId();
                $pdo->prepare("INSERT INTO purchase_items (purchase_id, product_id, qty, cost, subtotal) VALUES (?, ?, ?, ?, ?)")
                    ->execute([$purchase_id, $pid, $it['qty'], $it['cost'], round($it['qty']*$it['cost'], 2)]);
                $pdo->prepare("UPDATE products SET stock = stock + ?, cost = ?, price = ? WHERE id = ?")
                    ->execute([$it['qty'], $it['cost'], $it['sale_price'], $pid]);
            }

            // ← التعديل: أضفنا category = 'purchase'
            if ($paid_now > 0) {
                $pdo->prepare("INSERT INTO cash_transactions (`type`, amount, description, category, created_at) VALUES ('out', ?, ?, ?, ?)")
                    ->execute([$paid_now, "Purchase #$purchase_id", 'purchase', $datetime]);
            }
            if ($supplier_id) {
                $balance_diff = round($total - $paid_now, 2);
                $table = $has_suppliers ? 'suppliers' : 'customers';
                $pdo->prepare("UPDATE $table SET balance = balance + ? WHERE id = ?")->execute([$balance_diff, $supplier_id]);
            }

            $pdo->commit(); $success = true; $saved_purchase_id = $purchase_id; session_clear_parsed();
        } catch (Exception $e) { if($pdo->inTransaction()) $pdo->rollBack(); $errors[] = $e->getMessage(); }
    }
}

if (!empty($_SESSION['purchase_parsed_all'])) {
    $all = $_SESSION['purchase_parsed_all']; $parsed_count = count($all);
    foreach ($all as $r) {
        if(floatval($r['qty']) <= 0) $zero_count++;
        else $invoice_total += round(floatval($r['qty']) * floatval($r['cost']), 2);
    }
    $parsed_items = array_slice($all, 0, 100);
}
?>
<!doctype html>
<html lang="<?= $is_ar ? 'ar' : 'en' ?>" dir="<?= $is_ar ? 'rtl' : 'ltr' ?>">
<head>
    <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
    <title><?= $is_ar ? 'فاتورة مشتريات | Top Tools' : 'Purchase Invoice | Top Tools' ?></title>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&family=Plus+Jakarta+Sans:wght@400;600;700&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <style>
        :root {
            --primary: #2563eb;
            --primary-hover: #1d4ed8;
            --bg-body: #f8fafc;
            --card-shadow: 0 10px 40px -10px rgba(0, 0, 0, 0.05);
            --border: #e2e8f0;
        }

        body {
            font-family: <?= $is_ar ? "'Cairo', sans-serif" : "'Plus Jakarta Sans', sans-serif" ?>;
            background-color: var(--bg-body);
            color: #1e293b;
            padding-bottom: 50px;
        }

        .bg-pattern {
            position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: -1;
            background-image: radial-gradient(#cbd5e1 1px, transparent 1px);
            background-size: 30px 30px; opacity: 0.2;
        }

        .container { max-width: 1300px; padding: 30px; }

        .glass-card {
            background: #ffffff; border-radius: 24px; border: 1px solid var(--border);
            box-shadow: var(--card-shadow); padding: 30px; margin-bottom: 25px;
        }

        .page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 40px; }
        
        .summary-badge {
            background: #fff; border: 1px solid var(--border); border-radius: 16px;
            padding: 15px 25px; display: flex; flex-direction: column; text-align: center;
            min-width: 140px;
        }
        .summary-label { font-size: 0.75rem; color: #64748b; text-transform: uppercase; font-weight: 700; }
        .summary-val { font-size: 1.25rem; font-weight: 800; color: var(--primary); }

        .form-label { font-size: 0.85rem; font-weight: 600; color: #475569; margin-bottom: 8px; }
        .form-control-pro { border-radius: 12px; padding: 12px; border: 1.5px solid var(--border); transition: 0.2s; }
        .form-control-pro:focus { border-color: var(--primary); box-shadow: 0 0 0 4px rgba(37, 99, 235, 0.1); }

        .upload-section {
            background: #fdfdfd; border: 2px dashed var(--border); border-radius: 20px;
            padding: 30px; text-align: center; margin-bottom: 30px; transition: 0.3s;
        }
        .upload-section:hover { border-color: var(--primary); background: #f8faff; }

        .table-container { border-radius: 16px; border: 1px solid var(--border); overflow: hidden; max-height: 600px; overflow-y: auto; }
        .table thead th { background: #f8fafc; color: #64748b; font-size: 0.75rem; text-transform: uppercase; padding: 15px; border: 0; }
        .table td { vertical-align: middle; border-bottom: 1px solid #f1f5f9; padding: 8px 15px; }

        .btn-pro { border-radius: 12px; padding: 12px 24px; font-weight: 700; transition: 0.3s; }
        .btn-primary-pro { background: var(--primary); color: white; border: none; }
        .btn-primary-pro:hover { background: var(--primary-hover); transform: translateY(-2px); box-shadow: 0 10px 20px rgba(37, 99, 235, 0.2); }
    </style>
</head>
<body>

    <div class="bg-pattern"></div>

    <div class="container">
        <div class="page-header">
            <div>
                <h1 class="fw-bold fs-3 m-0"><?= $is_ar ? 'استيراد فاتورة شراء' : 'Import Purchase Invoice' ?></h1>
                <p class="text-muted small m-0"><?= $is_ar ? 'قم برفع ملف Excel أو إدخال الأصناف يدوياً' : 'Upload Excel or manual entry' ?></p>
            </div>
            <div class="d-flex gap-2">
                <a href="purchase_view.php" class="btn btn-light rounded-pill px-4 fw-bold shadow-sm">📋 <?= $is_ar ? 'سجل الفواتير' : 'Invoices Log' ?></a>
                <a href="index.php" class="btn btn-light rounded-pill px-4 fw-bold shadow-sm">🏠</a>
                <a href="?lang=<?= $is_ar ? 'en' : 'ar' ?>" class="btn btn-light rounded-pill px-4 fw-bold shadow-sm"><?= $is_ar ? 'EN' : 'عربي' ?></a>
            </div>
        </div>

        <?php if ($success): ?>
            <div class="alert alert-success border-0 shadow-sm rounded-4 mb-4 d-flex align-items-center justify-content-between p-3">
                <span>✅ <?= $is_ar ? 'تم حفظ فاتورة المشتريات وتحديث المخزون بنجاح.' : 'Purchase saved and stock updated.' ?></span>
                <a href="purchase_view_invoice.php?id=<?= $saved_purchase_id ?>" class="btn btn-primary btn-sm px-4 rounded-pill">عرض / طباعة</a>
            </div>
        <?php endif; ?>

        <?php if (!empty($errors)): ?>
            <div class="alert alert-danger border-0 shadow-sm rounded-4 mb-4"><?php foreach($errors as $e) echo "• ".esc($e)."<br>"; ?></div>
        <?php endif; ?>

        <form method="post" enctype="multipart/form-data" id="mainForm">
            <input type="hidden" name="use_manual" id="use_manual" value="0">

            <div class="glass-card">
                <div class="row g-4 align-items-center mb-4">
                    <div class="col-md-3">
                        <label class="form-label"><?= $is_ar ? 'المورد / الحساب' : 'Supplier / Account' ?></label>
                        <select name="supplier_id" class="form-select form-control-pro">
                            <option value=""><?= $is_ar ? 'نقدي (بدون حساب)' : 'Cash (No Account)' ?></option>
                            <?php foreach($suppliers as $s): ?>
                                <option value="<?= $s['id'] ?>"><?= esc($s['name']) ?> (<?= number_format($s['balance'],2) ?>)</option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label"><?= $is_ar ? 'التاريخ' : 'Date' ?></label>
                        <input type="datetime-local" name="datetime" class="form-control form-control-pro" value="<?= date('Y-m-d\TH:i') ?>">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label"><?= $is_ar ? 'المدفوع نقداً' : 'Paid Cash' ?></label>
                        <input type="number" step="0.01" name="paid_now" class="form-control form-control-pro" value="0">
                    </div>
                    <div class="col-md-4 d-flex justify-content-end gap-3">
                        <div class="summary-badge">
                            <span class="summary-label"><?= $is_ar ? 'إجمالي الفاتورة' : 'Invoice Total' ?></span>
                            <span class="summary-val" id="invoiceTotal"><?= number_format($invoice_total,2) ?></span>
                        </div>
                        <?php if($parsed_count > 0): ?>
                        <div class="summary-badge border-primary">
                            <span class="summary-label"><?= $is_ar ? 'عدد الأصناف' : 'Total Items' ?></span>
                            <span class="summary-val"><?= $parsed_count ?></span>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="upload-section">
                    <div class="mb-3">
                        <svg width="40" height="40" class="text-primary mb-3" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v8"></path></svg>
                        <h6 class="fw-bold"><?= $is_ar ? 'ارفع ملف المنتجات (Excel/CSV)' : 'Upload Products File (Excel/CSV)' ?></h6>
                        <p class="text-muted small"><?= $is_ar ? 'يجب أن يحتوي الملف على أعمدة: Name, SKU, Qty, Cost, Sale Price' : 'Header columns: Name, SKU, Qty, Cost, Sale Price' ?></p>
                    </div>
                    <div class="d-inline-flex gap-2">
                        <input type="file" name="csv_file" class="form-control" style="max-width: 300px;">
                        <button type="submit" name="upload_excel" class="btn btn-primary px-4 rounded-3 fw-bold"><?= $is_ar ? 'بدء الاستيراد' : 'Start Import' ?></button>
                        <a href="?download_template=1" class="btn btn-outline-secondary px-4 rounded-3 fw-bold"><?= $is_ar ? 'تحميل النموذج' : 'Template' ?></a>
                        <?php if($parsed_count > 0): ?>
                            <a href="?clear_parsed=1" class="btn btn-outline-danger px-3 rounded-3">✕</a>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h6 class="fw-bold m-0"><?= $is_ar ? 'قائمة المنتجات (مراجعة)' : 'Product List (Review)' ?></h6>
                    <button type="button" class="btn btn-light btn-sm fw-bold border" onclick="addRow()">+ أضف صنف يدوي</button>
                </div>

                <div class="table-container">
                    <table class="table" id="itemsTable">
                        <thead>
                            <tr>
                                <th><?= $is_ar ? 'المنتج' : 'Product' ?></th>
                                <th>SKU</th>
                                <th style="width: 100px;">Qty</th>
                                <th style="width: 120px;">Cost</th>
                                <th style="width: 120px;">Sale</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(!empty($parsed_items)): foreach($parsed_items as $p): ?>
                            <tr>
                                <td><input name="pname[]" class="form-control form-control-sm manual-input" value="<?= esc($p['name']) ?>"></td>
                                <td><input name="sku[]" class="form-control form-control-sm manual-input" value="<?= esc($p['sku']) ?>"></td>
                                <td><input name="qty[]" type="number" step="0.01" class="form-control form-control-sm manual-input qty-trigger" value="<?= $p['qty'] ?>"></td>
                                <td><input name="cost[]" type="number" step="0.01" class="form-control form-control-sm manual-input cost-trigger" value="<?= $p['cost'] ?>"></td>
                                <td><input name="sale_price[]" type="number" step="0.01" class="form-control form-control-sm manual-input" value="<?= $p['sale_price'] ?>"></td>
                                <td><button type="button" class="btn btn-link text-danger p-0" onclick="this.closest('tr').remove()">✕</button></td>
                            </tr>
                            <?php endforeach; else: ?>
                            <tr id="emptyRow">
                                <td colspan="6" class="text-center py-4 text-muted small"><?= $is_ar ? 'لا توجد بيانات مستوردة، ابدأ بالرفع أو الإضافة اليدوية' : 'No data. Start by uploading or adding manually.' ?></td>
                            </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <div class="mt-4 row g-3 align-items-center">
                    <div class="col-md-8">
                        <input type="text" name="note" class="form-control form-control-pro" placeholder="<?= $is_ar ? 'أضف ملاحظة للفاتورة...' : 'Add a note...' ?>">
                    </div>
                    <div class="col-md-4">
                        <?php if($parsed_count > 0): ?>
                            <button type="submit" name="confirm_save" class="btn-pro btn-primary-pro w-100">
                                <?= $is_ar ? 'تأكيد وحفظ الفاتورة' : 'Confirm & Save Purchase' ?>
                            </button>
                        <?php else: ?>
                            <button type="submit" name="save_direct" class="btn-pro btn-primary-pro w-100">
                                <?= $is_ar ? 'حفظ الفاتورة مباشرة' : 'Save Invoice Directly' ?>
                            </button>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </form>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        const isAr = <?= $is_ar ? 'true' : 'false' ?>;
        
        function recalcTotal() {
            let total = 0;
            document.querySelectorAll('#itemsTable tbody tr').forEach(tr => {
                const qty = parseFloat(tr.querySelector('input[name="qty[]"]')?.value || 0);
                const cost = parseFloat(tr.querySelector('input[name="cost[]"]')?.value || 0);
                total += Math.round(qty * cost * 100) / 100;
            });
            document.getElementById('invoiceTotal').textContent = total.toLocaleString(undefined, {minimumFractionDigits: 2});
        }

        function addRow() {
            const empty = document.getElementById('emptyRow');
            if(empty) empty.remove();
            const tbody = document.querySelector('#itemsTable tbody');
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td><input name="pname[]" class="form-control form-control-sm manual-input" required></td>
                <td><input name="sku[]" class="form-control form-control-sm manual-input"></td>
                <td><input name="qty[]" type="number" step="0.01" class="form-control form-control-sm manual-input qty-trigger" value="1"></td>
                <td><input name="cost[]" type="number" step="0.01" class="form-control form-control-sm manual-input cost-trigger" value="0"></td>
                <td><input name="sale_price[]" type="number" step="0.01" class="form-control form-control-sm manual-input" value="0"></td>
                <td><button type="button" class="btn btn-link text-danger p-0" onclick="this.closest('tr').remove(); recalcTotal();">✕</button></td>
            `;
            tbody.appendChild(tr);
            document.getElementById('use_manual').value = '1';
            recalcTotal();
        }

        document.getElementById('itemsTable').addEventListener('input', (e) => {
            if(e.target.classList.contains('manual-input')) {
                document.getElementById('use_manual').value = '1';
                if(e.target.classList.contains('qty-trigger') || e.target.classList.contains('cost-trigger')) recalcTotal();
            }
        });

        <?php if ($parsed_count > 0 && $zero_count > 0 && empty($_SESSION['purchase_zero_choice'])): ?>
        window.onload = () => {
            Swal.fire({
                title: isAr ? 'تنبيه: صفوف بكمية صفر' : 'Attention: Zero-Qty Rows',
                text: isAr ? 'يحتوي الملف على عناصر بكمية صفر. هل تريد استيرادها أم تجاهلها؟' : 'Rows with 0 qty found. Include or Ignore?',
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: isAr ? 'استيراد الكل' : 'Include All',
                cancelButtonText: isAr ? 'تجاهل الصفر' : 'Ignore Zeros',
                allowOutsideClick: false
            }).then(async (res) => {
                const choice = res.isConfirmed ? 'include' : 'ignore';
                const fd = new FormData();
                fd.append('ajax_zero_choice', '1');
                fd.append('choice', choice);
                const r = await fetch(location.pathname, { method:'POST', body: fd });
                const j = await r.json();
                if(j.ok) location.reload();
            });
        };
        <?php endif; ?>
    </script>
</body>
</html>