<?php
// sales_create.php
// Modern POS Design - Customer Requests Implemented
// Updates: Cost Column Added + Real-time Profit Calculation + Stock Warning

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

/* ====================================================================================
   BACKEND LOGIC
   ==================================================================================== */

/* AUTO ADD PRODUCT FROM products.php */
if (isset($_GET['add_product']) && intval($_GET['add_product']) > 0) {
    $pid = intval($_GET['add_product']);

    $stmt = $pdo->prepare("
        SELECT 
            id, 
            sku,
            COALESCE(NULLIF(name_en,''), name_ar, '') AS name,
            COALESCE(price,0) AS price,
            COALESCE(cost,0) AS cost,
            COALESCE(stock,0) AS stock
        FROM products 
        WHERE id = ? 
        LIMIT 1
    ");
    $stmt->execute([$pid]);
    $prod = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($prod) {
        $autoAddProduct = json_encode([
            'id'    => $prod['id'],
            'sku'   => $prod['sku'],
            'name'  => $prod['name'],
            'price' => floatval($prod['price']),
            'cost'  => floatval($prod['cost']),
            'stock' => floatval($prod['stock'])
        ]);
    }
}

function esc($v){ return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }
function json_out($arr){ header('Content-Type: application/json; charset=utf-8'); echo json_encode($arr, JSON_UNESCAPED_UNICODE); exit; }

$lang = $_GET['lang'] ?? 'en';
$is_ar = $lang === 'ar';
$is_admin = true; // Control who sees cost/profit

$action = $_GET['action'] ?? null;

/* ----------------- AJAX: search products ----------------- */
if ($action === 'search') {
    $q = trim($_GET['q'] ?? '');
    if ($q === '') json_out(['success'=>true,'results'=>[]]);
    try {
        $like = "%{$q}%";
        $sql = "SELECT id, sku,
                       COALESCE(NULLIF(name_en,''), name_ar, '') AS name,
                       COALESCE(price,0) AS price,
                       COALESCE(cost,0) AS cost,
                       COALESCE(stock,0) AS stock
                FROM products
                WHERE (name_en LIKE :q OR name_ar LIKE :q OR sku LIKE :q)
                  AND COALESCE(stock,0) > 0
                ORDER BY name ASC
                LIMIT 60";
        $stmt = $pdo->prepare($sql);
        $stmt->bindValue(':q', $like, PDO::PARAM_STR);
        $stmt->execute();
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        json_out(['success'=>true,'results'=>$rows]);
    } catch (Exception $e) {
        json_out(['success'=>false,'error'=>$e->getMessage()]);
    }
}

/* ------------- AJAX: search customers ------------- */
if ($action === 'search_customer') {
    $q = trim($_GET['q'] ?? '');
    if ($q === '') json_out(['success'=>true,'results'=>[]]);
    try {
        $like = "%{$q}%";
        $stmt = $pdo->prepare("SELECT id, name, phone FROM customers WHERE name LIKE :q OR phone LIKE :q ORDER BY name LIMIT 50");
        $stmt->execute([':q' => $like]);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        json_out(['success'=>true,'results'=>$rows]);
    } catch (Exception $e) {
        json_out(['success'=>false,'error'=>$e->getMessage()]);
    }
}

/* ------------- AJAX: add customer quick ------------- */
if ($action === 'add_customer') {
    $body = file_get_contents('php://input');
    $data = json_decode($body, true);
    $name = trim($data['name'] ?? '');
    $phone = trim($data['phone'] ?? '');
    if ($name === '') json_out(['success'=>false,'error'=>'missing_name']);
    try {
        $ins = $pdo->prepare("INSERT INTO customers (name, phone, balance, created_at) VALUES (?, ?, 0, ?)");
        $ins->execute([$name, $phone, date('Y-m-d H:i:s')]);
        $id = $pdo->lastInsertId();
        json_out(['success'=>true,'id'=>$id,'name'=>$name,'phone'=>$phone,'balance'=>0]);
    } catch (Exception $e) {
        json_out(['success'=>false,'error'=>$e->getMessage()]);
    }
}

/* ------------- AJAX: get customer balance ------------- */
if ($action === 'get_customer_balance') {
    $id = intval($_GET['id'] ?? 0);
    if (!$id) json_out(['success'=>false,'error'=>'missing_id']);
    try {
        $stmt = $pdo->prepare("SELECT COALESCE(balance,0) FROM customers WHERE id = ? LIMIT 1");
        $stmt->execute([$id]);
        $bal = floatval($stmt->fetchColumn() ?? 0);
        json_out(['success'=>true,'balance'=>$bal]);
    } catch (Exception $e) {
        json_out(['success'=>false,'error'=>$e->getMessage()]);
    }
}

/* ------------- AJAX: load sale (for editing) ------------- */
if ($action === 'load_sale') {
    $id = intval($_GET['id'] ?? 0);
    if (!$id) json_out(['success'=>false,'error'=>'missing_id']);
    try {
        $stmt = $pdo->prepare("SELECT s.*, c.name AS customer_name FROM sales s LEFT JOIN customers c ON s.customer_id = c.id WHERE s.id = ? LIMIT 1");
        $stmt->execute([$id]);
        $sale = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$sale) json_out(['success'=>false,'error'=>'sale_not_found']);
        // Fetch stock as well for the table
        $stmt2 = $pdo->prepare("SELECT si.*, p.sku, COALESCE(NULLIF(p.name_en,''), p.name_ar, '') AS name, COALESCE(p.cost,0) AS cost, COALESCE(p.stock,0) AS stock FROM sale_items si LEFT JOIN products p ON si.product_id = p.id WHERE si.sale_id = ?");
        $stmt2->execute([$id]);
        $items = $stmt2->fetchAll(PDO::FETCH_ASSOC);
        json_out(['success'=>true,'sale'=>$sale,'items'=>$items]);
    } catch (Exception $e) {
        json_out(['success'=>false,'error'=>$e->getMessage()]);
    }
}

/* ------------- AJAX: get adjacent sale id ------------- */
if ($action === 'get_adjacent_sale') {
    $sale_id = intval($_GET['sale_id'] ?? 0);
    $dir = $_GET['dir'] ?? 'prev';
    try {
        if ($dir === 'prev') {
            $st = $pdo->prepare("SELECT id FROM sales WHERE id < ? ORDER BY id DESC LIMIT 1");
            $st->execute([$sale_id]);
        } else {
            $st = $pdo->prepare("SELECT id FROM sales WHERE id > ? ORDER BY id ASC LIMIT 1");
            $st->execute([$sale_id]);
        }
        $adj = $st->fetchColumn();
        json_out(['success'=>true,'adjacent_id'=> $adj ? intval($adj) : null]);
    } catch (Exception $e) {
        json_out(['success'=>false,'error'=>$e->getMessage()]);
    }
}

/* ------------- AJAX: get latest sale id ------------- */
if ($action === 'get_latest_sale') {
    try {
        $st = $pdo->query("SELECT id FROM sales ORDER BY id DESC LIMIT 1");
        $id = $st->fetchColumn();
        json_out(['success'=>true, 'latest_id' => $id ? intval($id) : null]);
    } catch (Exception $e) {
        json_out(['success'=>false,'error'=>$e->getMessage()]);
    }
}

/* ------------- AJAX: save invoice ------------- */
if ($action === 'save') {
    $body = file_get_contents('php://input');
    $data = json_decode($body, true);
    if (!is_array($data)) json_out(['success'=>false,'error'=>'invalid_json']);

    $editing_sale_id = isset($data['sale_id']) && $data['sale_id'] ? intval($data['sale_id']) : null;
    $customer_id = isset($data['customer_id']) && $data['customer_id'] ? intval($data['customer_id']) : null;
    $datetime = $data['datetime'] ?? date('Y-m-d H:i:s');
    $paid_now = floatval($data['paid_now'] ?? 0);
    $tax_rate = floatval($data['tax_rate'] ?? 0);
    $note = trim($data['note'] ?? '');
    $items = $data['items'] ?? [];

    if (!is_array($items) || count($items) === 0) json_out(['success'=>false,'error'=>'no_items']);

    $subtotal = 0.0;
    $total_discount = 0.0;
    $profit = 0.0;
    $validated = [];

    try {
        $old_sale = null;
        $old_items = [];
        $old_delta = 0.0;
        $old_customer_id = null;
        if ($editing_sale_id) {
            $stm = $pdo->prepare("SELECT * FROM sales WHERE id = ? LIMIT 1");
            $stm->execute([$editing_sale_id]);
            $old_sale = $stm->fetch(PDO::FETCH_ASSOC);
            if (!$old_sale) json_out(['success'=>false,'error'=>'sale_not_found_for_edit']);
            $stm2 = $pdo->prepare("SELECT * FROM sale_items WHERE sale_id = ?");
            $stm2->execute([$editing_sale_id]);
            $old_items = $stm2->fetchAll(PDO::FETCH_ASSOC);
            $old_total = floatval($old_sale['total']);
            $old_paid = floatval($old_sale['paid']);
            $old_delta = round(max(0, $old_total - $old_paid), 2);
            $old_customer_id = intval($old_sale['customer_id']) ?: null;
        }

        foreach ($items as $it) {
            $pid = intval($it['product_id'] ?? 0);
            $qty = floatval($it['qty'] ?? 0);
            $unit_price = floatval($it['unit_price'] ?? 0);
            $discount = floatval($it['discount'] ?? 0);

            if ($pid <= 0 || $qty <= 0) continue;

            $ps = $pdo->prepare("SELECT id, COALESCE(price,0) AS db_price, COALESCE(cost,0) AS cost, COALESCE(stock,0) AS stock FROM products WHERE id = ? LIMIT 1");
            $ps->execute([$pid]);
            $prod = $ps->fetch(PDO::FETCH_ASSOC);
            if (!$prod) json_out(['success'=>false,'error'=>"product_not_found:{$pid}"]);

            $available_stock = floatval($prod['stock']);
            if ($editing_sale_id) {
                $old_qty_for_prod = 0;
                foreach ($old_items as $oi) {
                    if (intval($oi['product_id']) === $pid) { $old_qty_for_prod += floatval($oi['qty']); }
                }
                $available_stock += $old_qty_for_prod;
            }

            if ($qty > $available_stock) json_out(['success'=>false,'error'=>"insufficient_stock:{$pid}"]);

            $price = $unit_price > 0 ? $unit_price : floatval($prod['db_price']);
            $line_total = $price * $qty;
            $line_subtotal = max(0, $line_total - $discount);

            $subtotal += $line_subtotal;
            $total_discount += $discount;
            // Profit calculation: (Price - Cost) * Qty - Discount share
            $profit += (($price - floatval($prod['cost'])) * $qty) - $discount;

            $validated[] = [
                'product_id' => $pid,
                'qty' => $qty,
                'unit_price' => $price,
                'discount' => $discount,
                'subtotal' => $line_subtotal,
                'cost' => floatval($prod['cost'])
            ];
        }

        if (count($validated) === 0) json_out(['success'=>false,'error'=>'no_valid_items']);

        $tax_amount = round($subtotal * ($tax_rate/100), 2);
        $grand_total = round($subtotal + $tax_amount, 2);

        if ($paid_now < 0) $paid_now = 0;
        if ($paid_now > $grand_total) $paid_now = $grand_total;

        $forgiven = 0.0;
        if (!$customer_id) {
            if (floatval($paid_now) == 0.0) {
                $paid_now = $grand_total;
                $forgiven = 0.0;
            } else {
                $forgiven = round(max(0, $grand_total - $paid_now), 2);
                if ($forgiven > 0) {
                    $profit = round($profit - $forgiven, 2);
                    if ($profit < 0) $profit = 0;
                }
            }
            $payment_method = 'cash';
            $increase_due = 0.0;
        } else {
            $payment_method = ($paid_now >= $grand_total) ? 'cash' : 'debt';
            $increase_due = round(max(0, $grand_total - $paid_now), 2);
        }

        $pdo->beginTransaction();

        if ($editing_sale_id) {
            $old_invoice_no = $old_sale['invoice_no'];
            foreach ($old_items as $oi) {
                $u = $pdo->prepare("UPDATE products SET stock = stock + ? WHERE id = ?");
                $u->execute([ $oi['qty'], $oi['product_id'] ]);
            }
            $del = $pdo->prepare("DELETE FROM sale_items WHERE sale_id = ?");
            $del->execute([$editing_sale_id]);
            try {
                $delCash = $pdo->prepare("DELETE FROM cash_transactions WHERE sale_id = ?");
                $delCash->execute([$editing_sale_id]);
            } catch (Exception $e) { }
            $delCt = $pdo->prepare("DELETE FROM customer_transactions WHERE note LIKE ?");
            $delCt->execute(["%{$old_invoice_no}%"]);
            if ($old_customer_id) {
                $pdo->prepare("UPDATE customers SET balance = balance - ? WHERE id = ?")->execute([ $old_delta, $old_customer_id ]);
            }
        }

        if ($editing_sale_id) {
            $invoice_no = $old_sale['invoice_no'];
            $updSale = $pdo->prepare("UPDATE sales SET customer_id = ?, total = ?, paid = ?, payment_method = ?, profit = ?, created_at = ? WHERE id = ?");
            $updSale->execute([ $customer_id, $grand_total, $paid_now, $payment_method, $profit, $datetime, $editing_sale_id ]);
            $sale_id = $editing_sale_id;
        } else {
            $invoice_no = 'INV-' . date('YmdHis') . '-' . substr(bin2hex(random_bytes(3)),0,6);
            $insSale = $pdo->prepare("INSERT INTO sales (invoice_no, customer_id, total, paid, payment_method, profit, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $insSale->execute([$invoice_no, $customer_id, $grand_total, $paid_now, $payment_method, $profit, $datetime]);
            $sale_id = $pdo->lastInsertId();
        }

        $insItem = $pdo->prepare("INSERT INTO sale_items (sale_id, product_id, qty, unit_price, subtotal) VALUES (?, ?, ?, ?, ?)");
        $updStock = $pdo->prepare("UPDATE products SET stock = stock - ? WHERE id = ?");
        foreach ($validated as $v) {
            $insItem->execute([$sale_id, $v['product_id'], $v['qty'], $v['unit_price'], $v['subtotal']]);
            $updStock->execute([$v['qty'], $v['product_id']]);
        }

        if ($paid_now > 0) {
            $insCash = $pdo->prepare("INSERT INTO cash_transactions (`type`, amount, description, created_at, sale_id) VALUES (?, ?, ?, ?, ?)");
            $insCash->execute(['in', $paid_now, "Payment for $invoice_no", $datetime, $sale_id]);
        }

        if ($customer_id) {
            $stmt = $pdo->prepare("SELECT COALESCE(balance,0) FROM customers WHERE id = ? LIMIT 1");
            $stmt->execute([$customer_id]);
            $curbal = floatval($stmt->fetchColumn() ?? 0);
            $final_balance = round($curbal + ($grand_total - $paid_now), 2);

            if ($paid_now > 0) {
                $insCt = $pdo->prepare("INSERT INTO customer_transactions (customer_id, type, amount, balance_after, note, date) VALUES (?, ?, ?, ?, ?, ?)");
                $insCt->execute([$customer_id, 'payment', $paid_now, $final_balance, "Payment for $invoice_no", $datetime]);
            }
            if ($increase_due > 0) {
                $insCt2 = $pdo->prepare("INSERT INTO customer_transactions (customer_id, type, amount, balance_after, note, date) VALUES (?, ?, ?, ?, ?, ?)");
                $insCt2->execute([$customer_id, 'debt', $increase_due, $final_balance, "Invoice $invoice_no (due)", $datetime]);
            }
            $pdo->prepare("UPDATE customers SET balance = ? WHERE id = ?")->execute([$final_balance, $customer_id]);
        }

        $pdo->commit();
        json_out([
            'success'=>true,
            'sale_id'=>$sale_id,
            'invoice_no'=>$invoice_no,
            'grand_total'=>$grand_total,
            'paid_now'=>$paid_now,
            'due'=> round(max(0, $grand_total - $paid_now),2),
            'payment_method'=>$payment_method
        ]);

    } catch (Exception $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        json_out(['success'=>false,'error'=>$e->getMessage()]);
    }
}
?>
<!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 ? 'إنشاء فاتورة' : 'New Sale' ?></title>
    
    <!-- Fonts & Icons -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;500;600;700&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
    <!-- Bootstrap 5 -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">

    <style>
        :root {
            --primary-color: #4338ca; /* Indigo-700 */
            --primary-hover: #3730a3;
            --primary-light: #e0e7ff;
            --secondary-bg: #f8fafc; /* Slate-50 */
            --border-color: #e2e8f0;
            --text-dark: #1e293b;
            --text-muted: #64748b;
            --success-color: #10b981;
            --danger-color: #ef4444;
            --warning-color: #f59e0b;
            
            --shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.05);
            --shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
            --shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
            
            --font-family: <?= $is_ar ? "'Cairo', sans-serif" : "'Inter', sans-serif" ?>;
        }

        body {
            background-color: #f1f5f9;
            font-family: var(--font-family);
            color: var(--text-dark);
            height: 100vh;
            overflow: hidden; /* App-like structure */
        }

        /* --- Navbar --- */
        .pos-navbar {
            height: 60px;
            background: #ffffff;
            border-bottom: 1px solid var(--border-color);
            padding: 0 1.5rem;
            display: flex;
            align-items: center;
            justify-content: space-between;
            box-shadow: var(--shadow-sm);
            z-index: 50;
        }
        .brand-logo {
            font-size: 1.25rem;
            font-weight: 700;
            color: var(--primary-color);
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        .nav-btn {
            border: 1px solid var(--border-color);
            background: #fff;
            color: var(--text-dark);
            padding: 0.4rem 0.8rem;
            border-radius: 6px;
            font-size: 0.9rem;
            transition: all 0.2s;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }
        .nav-btn:hover {
            background: var(--secondary-bg);
            border-color: #cbd5e1;
            color: var(--primary-color);
        }

        /* --- Main Layout Grid --- */
        .pos-container {
            display: flex;
            height: calc(100vh - 60px);
            overflow: hidden;
        }

        /* --- Left Side: Products & Table --- */
        .main-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            padding: 1.5rem;
            overflow: hidden;
            gap: 1rem;
        }

        /* Search Area */
        .search-area {
            position: relative;
        }
        .search-input-group {
            position: relative;
            box-shadow: var(--shadow-md);
            border-radius: 10px;
        }
        .search-input {
            width: 100%;
            padding: 1rem 1.2rem;
            padding-inline-start: 3rem;
            border: 1px solid transparent;
            border-radius: 10px;
            font-size: 1.1rem;
            background: #fff;
            transition: all 0.2s;
        }
        .search-input:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px var(--primary-light);
        }
        .search-icon {
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            left: <?= $is_ar ? 'auto' : '1.2rem' ?>;
            right: <?= $is_ar ? '1.2rem' : 'auto' ?>;
            color: var(--text-muted);
            font-size: 1.2rem;
            pointer-events: none;
        }

        /* Suggestions Dropdown */
        .suggestions-dropdown {
            position: absolute;
            top: 100%;
            left: 0; right: 0;
            background: #fff;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            margin-top: 5px;
            max-height: 400px;
            overflow-y: auto;
            box-shadow: var(--shadow-lg);
            z-index: 100;
        }
        .suggestion-item {
            padding: 12px 16px;
            border-bottom: 1px solid var(--secondary-bg);
            cursor: pointer;
            transition: background 0.15s;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .suggestion-item:last-child { border-bottom: none; }
        .suggestion-item:hover { background-color: var(--primary-light); }
        .item-info h6 { margin: 0; font-weight: 600; color: var(--text-dark); }
        .item-meta { font-size: 0.85rem; color: var(--text-muted); display: flex; gap: 10px; margin-top: 2px; }
        .item-price { font-weight: 700; color: var(--primary-color); font-size: 1.1rem; }
        .badge-stock { background: #dcfce7; color: #166534; padding: 2px 6px; border-radius: 4px; font-size: 0.75rem; }
        .badge-stock.low { background: #fee2e2; color: #991b1b; }
        .cost-display { font-size: 0.8rem; color: #dc2626; margin-inline-start: 5px; opacity: 0.8; }

        /* Product Table */
        .table-container {
            background: #fff;
            border-radius: 12px;
            box-shadow: var(--shadow-sm);
            flex: 1;
            overflow: hidden;
            display: flex;
            flex-direction: column;
            border: 1px solid var(--border-color);
            position: relative;
        }
        .table-scroll {
            flex: 1;
            overflow-y: auto;
        }
        .custom-table {
            width: 100%;
            border-collapse: collapse;
        }
        .custom-table thead th {
            background: #f8fafc;
            padding: 14px 16px;
            font-size: 0.85rem;
            color: var(--text-muted);
            text-transform: uppercase;
            font-weight: 600;
            border-bottom: 1px solid var(--border-color);
            position: sticky;
            top: 0;
            z-index: 10;
            white-space: nowrap;
        }
        .custom-table tbody td {
            padding: 10px 12px;
            border-bottom: 1px solid var(--secondary-bg);
            vertical-align: middle;
        }
        .custom-table tbody tr:hover { background-color: #fafafa; }
        
        .qty-input, .price-input, .disc-input, .cost-input {
            width: 70px;
            padding: 6px;
            border: 1px solid #e2e8f0;
            border-radius: 6px;
            text-align: center;
            font-weight: 600;
            transition: all 0.2s;
        }
        .cost-input {
            background: #fdf2f2;
            color: #7f1d1d;
            border-color: #fecaca;
        }
        .qty-input:focus, .price-input:focus, .disc-input:focus {
            border-color: var(--primary-color);
            outline: none;
            background: #fff;
        }
        /* Stock Warning */
        .qty-input.stock-warning {
            background-color: #fee2e2;
            border-color: #ef4444;
            color: #b91c1c;
        }

        .row-total { font-weight: 700; color: var(--text-dark); }
        .btn-remove {
            background: #fee2e2;
            color: #ef4444;
            border: none;
            width: 32px;
            height: 32px;
            border-radius: 6px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.2s;
        }
        .btn-remove:hover { background: #ef4444; color: #fff; }

        /* Empty State */
        .empty-state {
            position: absolute;
            top: 50%; left: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
            color: var(--text-muted);
            opacity: 0.7;
        }
        .empty-state i { font-size: 3rem; margin-bottom: 1rem; color: #cbd5e1; }

        /* --- Right Side: Sidebar --- */
        .sidebar {
            width: 380px;
            background: #fff;
            border-inline-start: 1px solid var(--border-color);
            display: flex;
            flex-direction: column;
            z-index: 40;
            box-shadow: -4px 0 15px rgba(0,0,0,0.01);
            height: 100%; /* Important */
        }

        /* Sidebar Sections */
        .sidebar-header {
            padding: 1rem 1.5rem;
            border-bottom: 1px solid var(--border-color);
            background: #f8fafc;
            flex-shrink: 0; /* Prevent shrinking */
        }
        .customer-selector {
            position: relative;
            margin-bottom: 0.5rem;
        }
        .customer-input {
            width: 100%;
            padding: 10px 12px;
            padding-inline-start: 36px;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            font-size: 0.95rem;
        }
        .customer-icon {
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            left: <?= $is_ar ? 'auto' : '12px' ?>;
            right: <?= $is_ar ? '12px' : 'auto' ?>;
            color: var(--text-muted);
        }
        .balance-pill {
            display: inline-block;
            background: #e0f2fe;
            color: #0369a1;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
            margin-top: 5px;
        }

        /* Middle Scrollable Section (Only Note) */
        .sidebar-middle {
            flex: 1; /* Takes available space */
            padding: 1rem 1.5rem;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
            gap: 1rem;
        }

        /* Fixed Bottom Section (Totals, Payment, Actions) */
        .sidebar-fixed-bottom {
            background: #ffffff;
            border-top: 1px solid var(--border-color);
            z-index: 50;
            box-shadow: 0 -4px 15px rgba(0,0,0,0.03);
            flex-shrink: 0; /* Prevent shrinking */
        }

        .totals-section {
            padding: 1rem 1.5rem 0.5rem 1.5rem;
            background: #fdfdfd;
        }

        /* Summary Lines */
        .summary-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 0.4rem;
            font-size: 0.9rem;
            color: var(--text-muted);
        }
        .summary-item.total {
            font-size: 1.25rem;
            font-weight: 800;
            color: var(--text-dark);
            margin-top: 0.5rem;
            padding-top: 0.5rem;
            border-top: 2px dashed var(--border-color);
        }
        .tax-control {
            width: 50px;
            padding: 2px;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            text-align: center;
            font-size: 0.8rem;
            margin: 0 5px;
        }

        .payment-section {
            padding: 0.5rem 1.5rem;
        }
        
        .pay-box {
            background: #f0fdf4;
            border: 1px solid #bbf7d0;
            border-radius: 10px;
            padding: 0.8rem;
        }
        .pay-label {
            font-size: 0.75rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            color: #166534;
            font-weight: 700;
            margin-bottom: 0.3rem;
            display: block;
        }
        .pay-input-group {
            display: flex;
            align-items: center;
            background: #fff;
            border: 1px solid #166534;
            border-radius: 8px;
            overflow: hidden;
            height: 38px;
        }
        .currency-symbol {
            padding: 0 0.8rem;
            background: #166534;
            color: #fff;
            font-weight: bold;
            height: 100%;
            display: flex;
            align-items: center;
        }
        .pay-input {
            border: none;
            width: 100%;
            height: 100%;
            font-size: 1.1rem;
            font-weight: 700;
            padding: 0 10px;
            color: var(--text-dark);
        }
        .pay-input:focus { outline: none; }
        .due-text {
            text-align: end;
            font-size: 0.8rem;
            margin-top: 4px;
            color: var(--danger-color);
            font-weight: 600;
        }

        .sidebar-footer {
            padding: 0.8rem 1.5rem 1rem 1.5rem;
        }
        .action-grid {
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 8px;
            margin-bottom: 5px;
        }
        .btn-main {
            padding: 10px;
            border: none;
            border-radius: 8px;
            font-weight: 700;
            font-size: 0.95rem;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
            cursor: pointer;
            transition: transform 0.1s;
        }
        .btn-main:active { transform: scale(0.98); }
        .btn-save-print { background: var(--primary-color); color: #fff; grid-column: span 2; }
        .btn-save-print:hover { background: var(--primary-hover); }
        .btn-save { background: var(--success-color); color: #fff; }
        .btn-save:hover { background: #059669; }
        .btn-new { background: #f3f4f6; color: var(--text-dark); border: 1px solid var(--border-color); }
        .btn-new:hover { background: #e5e7eb; }

        .invoice-nav {
            display: flex;
            justify-content: center;
            gap: 1rem;
            margin-top: 2px;
        }
        .nav-arrow {
            color: var(--text-muted);
            cursor: pointer;
            padding: 2px;
        }
        .nav-arrow:hover { color: var(--primary-color); }

        /* Highlight text in search */
        .highlight { background: #fef9c3; color: #854d0e; padding: 0 1px; }
        
        /* Mobile Responsive */
        @media (max-width: 992px) {
            .pos-container { flex-direction: column; height: auto; overflow: auto; }
            .sidebar { width: 100%; height: auto; border-inline-start: none; border-top: 1px solid var(--border-color); order: 2; }
            .main-content { order: 1; min-height: 500px; }
            .table-container { min-height: 300px; }
            body { height: auto; overflow-y: auto; }
            .sidebar-middle { min-height: 60px; } /* Ensure note input is visible on mobile */
        }
    </style>
</head>
<body>

    <!-- Top Navigation Bar -->
    <nav class="pos-navbar">
        <div class="brand-logo">
            <i class="fa-solid fa-layer-group"></i>
            <span><?= $is_ar ? 'نظام المبيعات الذكي' : 'Smart POS' ?></span>
        </div>
        <div class="d-flex gap-2">
            <a href="index.php" class="nav-btn"><i class="fa fa-home"></i> <span><?= $is_ar ? 'الرئيسية' : 'Home' ?></span></a>
            <a href="sales.php" class="nav-btn"><i class="fa fa-clock-rotate-left"></i> <span><?= $is_ar ? 'السجل' : 'History' ?></span></a>
            <a href="?lang=<?= $is_ar ? 'en' : 'ar' ?>" class="nav-btn fw-bold">
                <?= $is_ar ? 'EN' : 'عربي' ?>
            </a>
        </div>
    </nav>

    <!-- Main App Container -->
    <form id="invoiceForm" onsubmit="return false;" class="pos-container">
        <input type="hidden" id="saleId" value="">

        <!-- LEFT COLUMN: Search & Products Table -->
        <div class="main-content">
            
            <!-- Search Bar -->
            <div class="search-area">
                <div class="search-input-group">
                    <i class="fa fa-magnifying-glass search-icon"></i>
                    <input id="productSearch" class="search-input" placeholder="<?= esc($is_ar ? 'ابحث عن اسم المنتج أو الباركود...' : 'Scan barcode or search product name...') ?>" autocomplete="off" autofocus>
                </div>
                <div id="suggestBox" class="suggestions-dropdown d-none">
                    <!-- JS Injected Suggestions -->
                </div>
            </div>

            <!-- Products Table -->
            <div class="table-container">
                <div class="table-scroll">
                    <table class="custom-table" id="itemsTable">
                        <thead>
                            <tr>
                                <th width="10%"><?= $is_ar ? 'الرمز' : 'SKU' ?></th>
                                <th width="25%"><?= $is_ar ? 'اسم المنتج' : 'Product Name' ?></th>
                                <th width="8%" class="text-center"><?= $is_ar ? 'متوفر' : 'Stock' ?></th>
                                
                                <?php if($is_admin): ?>
                                    <th width="10%" class="text-center text-danger"><?= $is_ar ? 'التكلفة' : 'Cost' ?></th>
                                <?php endif; ?>

                                <th width="10%" class="text-center"><?= $is_ar ? 'السعر' : 'Price' ?></th>
                                <th width="10%" class="text-center"><?= $is_ar ? 'الكمية' : 'Qty' ?></th>
                                <th width="10%" class="text-center"><?= $is_ar ? 'الخصم' : 'Disc' ?></th>
                                <th width="12%" class="text-end"><?= $is_ar ? 'الإجمالي' : 'Total' ?></th>
                                <th width="5%"></th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- Rows injected via JS -->
                        </tbody>
                    </table>
                    
                    <!-- Empty State -->
                    <div id="emptyState" class="empty-state">
                        <i class="fa fa-cart-plus"></i>
                        <h5><?= $is_ar ? 'الفاتورة فارغة' : 'Empty Invoice' ?></h5>
                        <p class="small"><?= $is_ar ? 'قم بالبحث أو مسح الباركود لإضافة منتجات' : 'Search or scan barcode to add products' ?></p>
                    </div>

                </div>
            </div>
        </div>

        <!-- RIGHT COLUMN: Sidebar (Customer, Totals, Actions) -->
        <div class="sidebar">
            
            <!-- 1. Header: Fixed -->
            <div class="sidebar-header">
                <div class="d-flex justify-content-between mb-2 text-muted small">
                    <div>
                        <i class="fa fa-hashtag"></i> 
                        <input type="text" id="invoiceNo" class="border-0 bg-transparent text-muted p-0" style="width:140px; font-size:0.85rem" readonly value="<?= esc('INV-'.date('YmdHis').'-'.substr(bin2hex(random_bytes(3)),0,6)) ?>">
                    </div>
                    <div>
                        <i class="fa fa-calendar"></i>
                        <input type="datetime-local" id="invoiceDate" class="border-0 bg-transparent text-muted p-0" style="font-size:0.85rem" value="<?= date('Y-m-d\TH:i') ?>">
                    </div>
                </div>

                <div class="customer-selector">
                    <div class="position-relative">
                        <i class="fa fa-user customer-icon"></i>
                        <input type="text" id="customerSearch" class="customer-input" placeholder="<?= esc($is_ar ? 'بحث عن عميل أو عميل نقدي...' : 'Search or Walk-in Customer...') ?>">
                        <input type="hidden" id="customerSelect" value="">
                    </div>
                    <div id="customerSuggest" class="suggestions-dropdown d-none"></div>
                    <div id="customerBalance" class="balance-pill d-none">
                        <?= $is_ar ? 'الرصيد: 0.00' : 'Balance: 0.00' ?>
                    </div>
                </div>
            </div>

            <!-- 2. Middle: Flexible (Note Input) -->
            <div class="sidebar-middle">
                <!-- Note -->
                <div>
                    <textarea id="note" class="form-control form-control-sm bg-light" rows="2" placeholder="<?= $is_ar ? 'ملاحظة على الفاتورة (اختياري)...' : 'Add a note (optional)...' ?>"></textarea>
                </div>
                <!-- Space filler -->
            </div>

            <!-- 3. Bottom: Fixed (Totals + Payment + Actions) -->
            <div class="sidebar-fixed-bottom">
                
                <!-- Totals -->
                <div class="totals-section">
                    <div class="summary-item">
                        <span><?= $is_ar ? 'المجموع الفرعي' : 'Subtotal' ?></span>
                        <span id="displaySubtotal" class="fw-bold">0.00</span>
                    </div>
                    
                    <div class="summary-item text-danger">
                        <span><?= $is_ar ? 'مجموع الخصم' : 'Total Discount' ?></span>
                        <span id="displayDiscount">-0.00</span>
                    </div>

                    <div class="summary-item">
                        <span class="d-flex align-items-center">
                            <?= $is_ar ? 'الضريبة' : 'Tax' ?> 
                            <span class="ms-2 me-1 text-muted">(%)</span>
                            <input id="taxRate" type="number" class="tax-control" value="0" min="0" step="0.1">
                        </span>
                        <span id="displayTax" class="fw-bold">0.00</span>
                    </div>
                    
                    <?php if($is_admin): ?>
                    <div class="summary-item text-success" style="font-size:0.85rem">
                        <span><?= $is_ar ? 'الربح المتوقع' : 'Est. Profit' ?> <i class="fa fa-arrow-trend-up"></i></span>
                        <span id="displayProfit">0.00</span>
                    </div>
                    <?php endif; ?>

                    <div class="summary-item total">
                        <span><?= $is_ar ? 'المبلغ الإجمالي' : 'Grand Total' ?></span>
                        <span class="text-primary" id="displayTotal">0.00</span>
                    </div>
                </div>

                <!-- Payment -->
                <div class="payment-section">
                    <div class="pay-box">
                        <label class="pay-label"><?= $is_ar ? 'الدفع المستلم' : 'Payment Received' ?></label>
                        <div class="pay-input-group">
                            <div class="currency">$</div>
                            <input id="amountPaid" type="number" class="pay-input" placeholder="0.00" step="0.01">
                        </div>
                        <div class="d-flex justify-content-between align-items-center mt-1">
                            <span class="badge bg-white border text-dark" id="paymentMethodBadge">Cash</span>
                            <span class="due-text">
                                <?= $is_ar ? 'المتبقي:' : 'Balance Due:' ?> 
                                <span id="displayRemaining">0.00</span>
                            </span>
                        </div>
                    </div>
                </div>

                <!-- Footer Actions -->
                <div class="sidebar-footer">
                    <div id="message" class="text-center small mb-2 fw-bold" style="min-height:20px"></div>

                    <div class="action-grid">
                        <button id="savePrintBtn" class="btn-main btn-save-print">
                            <i class="fa fa-print"></i> <?= $is_ar ? 'حفظ وطباعة' : 'Save & Print' ?>
                        </button>
                        <button id="saveBtn" class="btn-main btn-save">
                            <i class="fa fa-check"></i> <?= $is_ar ? 'حفظ' : 'Save' ?>
                        </button>
                        <button id="newBtn" class="btn-main btn-new" title="<?= $is_ar ? 'جديد' : 'New' ?>">
                            <i class="fa fa-plus"></i>
                        </button>
                    </div>

                    <div class="invoice-nav">
                        <div id="prevBtn" class="nav-arrow" title="Previous"><i class="fa fa-chevron-left fa-lg"></i></div>
                        <span class="text-muted small">•</span>
                        <div id="nextBtn" class="nav-arrow" title="Next"><i class="fa fa-chevron-right fa-lg"></i></div>
                    </div>
                </div>
            </div>

        </div>
    </form>

<script>
/* ====================================================================================
   FRONTEND LOGIC
   ==================================================================================== */

const qInput = document.getElementById('productSearch');
const suggestBox = document.getElementById('suggestBox');
const itemsTbody = document.querySelector('#itemsTable tbody');
const emptyState = document.getElementById('emptyState');
const customerSearch = document.getElementById('customerSearch');
const customerSelect = document.getElementById('customerSelect');
const customerSuggest = document.getElementById('customerSuggest');
const customerBalance = document.getElementById('customerBalance');
const taxRate = document.getElementById('taxRate');
const displaySubtotal = document.getElementById('displaySubtotal');
const displayDiscount = document.getElementById('displayDiscount');
const displayTax = document.getElementById('displayTax');
const displayTotal = document.getElementById('displayTotal');
const displayRemaining = document.getElementById('displayRemaining');
const displayProfit = document.getElementById('displayProfit');
const paymentMethodBadge = document.getElementById('paymentMethodBadge');
const amountPaidInput = document.getElementById('amountPaid');
const noteInput = document.getElementById('note');
const saveBtn = document.getElementById('saveBtn');
const savePrintBtn = document.getElementById('savePrintBtn');
const newBtn = document.getElementById('newBtn');
const prevBtn = document.getElementById('prevBtn');
const nextBtn = document.getElementById('nextBtn');
const saleIdInput = document.getElementById('saleId');
const message = document.getElementById('message');

const IS_ADMIN = <?= $is_admin ? 'true' : 'false' ?>;

function escapeHtml(s){ return s ? s.toString().replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;') : ''; }

function highlightSku(text, query) {
    if (!text) return '';
    if (!query) return escapeHtml(text);
    try {
        const escQuery = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
        const regex = new RegExp(escQuery, 'gi');
        const safe = escapeHtml(text);
        return safe.replace(regex, (m) => `<span class="highlight">${m}</span>`);
    } catch (e) {
        return escapeHtml(text);
    }
}

/* ---------- Product search/autocomplete ---------- */
let timer = null;
qInput.addEventListener('input', ()=>{
    const q = qInput.value.trim();
    suggestBox.innerHTML = '';
    if (timer) clearTimeout(timer);
    if (q.length < 1) { suggestBox.classList.add('d-none'); return; } 
    timer = setTimeout(async ()=>{
        try {
            const res = await fetch('?action=search&q=' + encodeURIComponent(q));
            const j = await res.json();
            if (j.success && j.results.length) {
                suggestBox.innerHTML = j.results.map(r => `
                    <div class="suggestion-item" 
                         data-id="${r.id}" 
                         data-sku="${escapeHtml(r.sku || '')}" 
                         data-name="${escapeHtml(r.name || '')}" 
                         data-price="${r.price}" 
                         data-cost="${r.cost}" 
                         data-stock="${r.stock}">
                        <div class="item-info">
                            <h6>
                                ${highlightSku(r.name, q)}
                                <?php if($is_admin): ?>
                                    <span class="cost-display">(<?= $is_ar ? 'ت:' : 'C:' ?> ${parseFloat(r.cost).toFixed(2)})</span>
                                <?php endif; ?>
                            </h6>
                            <div class="item-meta">
                                <span>${highlightSku(r.sku || 'No SKU', q)}</span>
                                <span class="badge-stock ${r.stock <= 0 ? 'low' : ''}">Qty: ${r.stock}</span>
                            </div>
                        </div>
                        <div class="item-price">$${parseFloat(r.price).toFixed(2)}</div>
                    </div>
                `).join('');
            } else {
                suggestBox.innerHTML = '<div class="p-3 text-center text-muted small">No products found</div>';
            }
            suggestBox.classList.remove('d-none');
        } catch(e){ console.error(e); }
    }, 200);
});

suggestBox.addEventListener('click', ev => {
    const item = ev.target.closest('.suggestion-item');
    if (!item) return;
    addRow(
        item.dataset.id,
        item.dataset.sku,
        item.dataset.name,
        item.dataset.price,
        item.dataset.cost,
        item.dataset.stock
    );
    qInput.value = '';
    suggestBox.classList.add('d-none');
    qInput.focus();
    calcTotals();
});

/* Close suggest when clicking outside */
document.addEventListener('click', function(e) {
    if (!suggestBox.contains(e.target) && e.target !== qInput) suggestBox.classList.add('d-none');
    if (!customerSuggest.contains(e.target) && e.target !== customerSearch) customerSuggest.classList.add('d-none');
});

/* ---------- Customer search/autocomplete ---------- */
let custTimer = null;
customerSearch.addEventListener('input', ()=>{
    const q = customerSearch.value.trim();
    customerSuggest.innerHTML = '';
    if (custTimer) clearTimeout(custTimer);
    if (q.length < 1) { 
        customerSuggest.classList.add('d-none'); 
        if(q.length === 0) { // Reset to walk-in
             customerSelect.value = '';
             customerBalance.classList.add('d-none');
             calcTotals();
        }
        return; 
    }
    custTimer = setTimeout(async ()=>{
        try {
            const res = await fetch('?action=search_customer&q=' + encodeURIComponent(q));
            const j = await res.json();
            let html = '';
            if (j.success && j.results.length) {
                html = j.results.map(c => `
                    <div class="suggestion-item" data-id="${c.id}" data-name="${escapeHtml(c.name)}" data-phone="${escapeHtml(c.phone||'')}">
                        <div class="item-info">
                            <h6 class="mb-1"><i class="fa fa-user-circle text-muted me-1"></i> ${escapeHtml(c.name)}</h6>
                            <div class="item-meta ms-3">${escapeHtml(c.phone||'')}</div>
                        </div>
                    </div>`).join('');
            }
            const nameEsc = escapeHtml(q);
            html += `<div class="suggestion-item text-primary" data-add="1" data-name="${nameEsc}">
                        <div class="d-flex align-items-center gap-2">
                             <i class="fa fa-plus-circle fa-lg"></i> 
                             <div>
                                <strong><?= $is_ar ? 'إضافة عميل جديد' : 'Add New Customer' ?></strong><br>
                                <span class="small text-dark">"${nameEsc}"</span>
                             </div>
                        </div>
                     </div>`;
            
            customerSuggest.innerHTML = html;
            customerSuggest.classList.remove('d-none');
        } catch(e){ console.error(e); }
    }, 200);
});

customerSuggest.addEventListener('click', ev=>{
    const div = ev.target.closest('.suggestion-item');
    if (!div) return;
    
    if (div.dataset.add) {
        const name = div.dataset.name || customerSearch.value.trim();
        fetch('?action=add_customer', {
            method: 'POST',
            headers: {'Content-Type':'application/json'},
            body: JSON.stringify({name: name, phone: ''})
        }).then(r=>r.json()).then(j=>{
            if (j.success) {
                customerSearch.value = j.name;
                customerSelect.value = j.id;
                customerBalance.textContent = '<?= $is_ar ? "الرصيد: 0.00" : "Balance: 0.00" ?>';
                customerBalance.classList.remove('d-none');
                customerSuggest.classList.add('d-none');
                calcTotals();
            } else {
                alert('Error: ' + (j.error||'add failed'));
            }
        });
        return;
    }

    const id = div.dataset.id;
    const name = div.dataset.name;
    customerSearch.value = name;
    customerSelect.value = id;
    customerSuggest.classList.add('d-none');
    
    // Update balance
    fetch('?action=get_customer_balance&id=' + encodeURIComponent(id))
        .then(r=>r.json())
        .then(j=>{
            if (j.success) {
                customerBalance.classList.remove('d-none');
                customerBalance.innerHTML = `<?= $is_ar ? 'الرصيد:' : 'Balance:' ?> ${parseFloat(j.balance).toFixed(2)}`;
                if(j.balance > 0) customerBalance.classList.add('text-danger');
                else customerBalance.classList.remove('text-danger');
            }
            calcTotals();
        });
});

/* ---------- Rows management ---------- */
function addRow(id, sku, name, price, cost, stock = 0){
    emptyState.classList.add('d-none'); // Hide empty state
    
    // Check if row exists
    const existingRow = Array.from(itemsTbody.querySelectorAll('tr')).find(tr => tr.dataset.productId === id);
    if(existingRow) {
        const qtyInput = existingRow.querySelector('.qty-input');
        qtyInput.value = parseFloat(qtyInput.value) + 1;
        
        // Trigger calc to check stock
        calcTotals();
        
        // Highlight effect
        existingRow.style.backgroundColor = '#e0e7ff';
        setTimeout(()=> existingRow.style.backgroundColor = '', 300);
        return;
    }

    const tr = document.createElement('tr');
    tr.dataset.productId = id;
    tr.dataset.stock = stock; 
    
    // NEW: Add Cost Cell if admin
    let costCell = '';
    if(IS_ADMIN) {
        costCell = `<td class="text-center"><input type="number" class="cost-input unit-cost" value="${parseFloat(cost).toFixed(2)}" step="0.01" readonly tabindex="-1"></td>`;
    } else {
        // Keep hidden input for calculations if not admin (for profit calc)
        costCell = `<input type="hidden" class="unit-cost" value="${parseFloat(cost).toFixed(2)}">`;
    }

    tr.innerHTML = `
        <td class="text-muted small fw-bold font-monospace">${escapeHtml(sku)}</td>
        <td class="fw-bold text-dark">${escapeHtml(name)}</td>
        <td class="text-center text-muted small stock-display">${stock}</td>
        
        ${IS_ADMIN ? costCell : ''}
        
        <td class="text-center"><input type="number" class="price-input unit-price" value="${parseFloat(price).toFixed(2)}" step="0.01"></td>
        <td class="text-center"><input type="number" class="qty-input qty" value="1" step="0.01" min="0.01"></td>
        <td class="text-center"><input type="number" class="disc-input discount" value="0" step="0.01" min="0"></td>
        
        <td class="sub text-end fw-bold text-primary">0.00</td>
        <td class="text-center">
            <button type="button" class="btn-remove remove-row"><i class="fa fa-times"></i></button>
            ${!IS_ADMIN ? costCell : ''} 
        </td>
    `;

    itemsTbody.insertBefore(tr, itemsTbody.firstChild); 
    
    // Event listeners
    tr.querySelectorAll('input').forEach(inp => {
        inp.addEventListener('input', calcTotals);
        inp.addEventListener('focus', function() { this.select(); }); 
    });
    tr.querySelector('.remove-row').addEventListener('click', ()=>{ 
        tr.remove(); 
        if(itemsTbody.children.length === 0) emptyState.classList.remove('d-none');
        calcTotals(); 
    });
    
    calcTotals();
}

/* ---------- Totals calculation ---------- */
function calcTotals(){
    let subtotal = 0, totalDiscount = 0, totalProfit = 0;
    
    document.querySelectorAll('#itemsTable tbody tr').forEach(tr=>{
        const price = parseFloat(tr.querySelector('.unit-price').value) || 0;
        const cost = parseFloat(tr.querySelector('.unit-cost').value) || 0; // Grab cost
        const qtyInp = tr.querySelector('.qty');
        const qty = parseFloat(qtyInp.value) || 0;
        const discount = parseFloat(tr.querySelector('.discount').value) || 0;
        const stock = parseFloat(tr.dataset.stock) || 0;

        // Stock Validation UI
        if(qty > stock) {
            qtyInp.classList.add('stock-warning');
        } else {
            qtyInp.classList.remove('stock-warning');
        }
        
        const lineTotal = price * qty;
        const lineSubtotal = Math.max(0, lineTotal - discount);
        
        // Profit Calc per line: (Price - Cost) * Qty - Discount
        const lineProfit = ((price - cost) * qty) - discount;

        tr.querySelector('.sub').textContent = lineSubtotal.toFixed(2);
        subtotal += lineSubtotal;
        totalDiscount += discount;
        totalProfit += lineProfit;
    });

    const tax = parseFloat(taxRate.value) || 0;
    const taxAmount = parseFloat((subtotal * (tax/100)).toFixed(2));
    const grand = parseFloat((subtotal + taxAmount).toFixed(2));
    const paidNow = parseFloat(amountPaidInput.value) || 0;
    const remaining = parseFloat(Math.max(0, grand - paidNow).toFixed(2));

    displaySubtotal.textContent = subtotal.toFixed(2);
    displayDiscount.textContent = totalDiscount.toFixed(2);
    displayTax.textContent = taxAmount.toFixed(2);
    displayTotal.textContent = grand.toFixed(2);
    displayRemaining.textContent = remaining.toFixed(2);
    
    if(displayProfit) {
        displayProfit.textContent = totalProfit.toFixed(2);
        // Change color if loss
        if(totalProfit < 0) displayProfit.parentElement.className = 'summary-item text-danger fw-bold';
        else displayProfit.parentElement.className = 'summary-item text-success';
    }

    // Payment Method Logic
    const hasCustomer = customerSelect.value && parseInt(customerSelect.value) > 0;
    let method = 'Cash';
    
    if (!hasCustomer) {
        method = 'Cash (Walk-in)';
        paymentMethodBadge.className = 'badge bg-secondary border text-white';
    } else {
        if (paidNow >= grand && grand > 0) {
            method = 'Paid (Full)';
            paymentMethodBadge.className = 'badge bg-success border text-white';
        } else if (paidNow > 0) {
            method = 'Partial Payment';
            paymentMethodBadge.className = 'badge bg-warning border text-dark';
        } else {
            method = 'Credit / Debt';
            paymentMethodBadge.className = 'badge bg-danger border text-white';
        }
    }
    paymentMethodBadge.textContent = method;
}

amountPaidInput.addEventListener('input', calcTotals);
taxRate.addEventListener('input', calcTotals);

/* ---------- Save ---------- */
async function saveInvoice(printAfter=false){
    const rows = Array.from(document.querySelectorAll('#itemsTable tbody tr'));
    if (rows.length === 0) { alert('<?= $is_ar ? 'الرجاء إضافة منتجات للفاتورة' : 'Please add products first' ?>'); return; }
    
    const items = [];
    for (const tr of rows) {
        const pid = tr.dataset.productId ? parseInt(tr.dataset.productId) : null;
        if (!pid) continue;
        const unit_price = parseFloat(tr.querySelector('.unit-price').value) || 0;
        const qty = parseFloat(tr.querySelector('.qty').value) || 0;
        const discount = parseFloat(tr.querySelector('.discount').value) || 0;
        if (qty <= 0) continue;
        items.push({product_id: pid, unit_price, qty, discount});
    }

    const payload = {
        sale_id: saleIdInput.value ? parseInt(saleIdInput.value) : null,
        customer_id: customerSelect.value ? parseInt(customerSelect.value) : null,
        datetime: document.getElementById('invoiceDate').value.replace('T',' '),
        paid_now: parseFloat(amountPaidInput.value) || 0,
        tax_rate: parseFloat(taxRate.value) || 0,
        note: noteInput.value || '',
        items: items
    };

    message.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Processing...';
    
    try {
        const res = await fetch('?action=save', {
            method: 'POST',
            headers: {'Content-Type':'application/json'},
            body: JSON.stringify(payload)
        });
        const j = await res.json();
        
        if (j.success) {
            message.innerHTML = `<span class="text-success"><i class="fa fa-check-circle"></i> Saved Invoice #${j.invoice_no}</span>`;
            
            if (printAfter) {
                window.open('sales_print.php?id=' + encodeURIComponent(j.sale_id) + '&lang=<?= $is_ar ? 'ar' : 'en' ?>', '_blank');
            }

            setTimeout(()=>{
                window.location.href = window.location.pathname + '?lang=<?= $lang ?>'; 
            }, 1000);

        } else {
            message.innerHTML = `<span class="text-danger"><i class="fa fa-circle-exclamation"></i> ${j.error || 'Error'}</span>`;
        }
    } catch(e) {
        console.error(e);
        message.innerHTML = `<span class="text-danger">Connection Failed</span>`;
    }
}

saveBtn.addEventListener('click', ()=>saveInvoice(false));
savePrintBtn.addEventListener('click', ()=>saveInvoice(true));

/* ---------- Reset / New ---------- */
newBtn.addEventListener('click', ()=>{
    if(confirm('<?= $is_ar ? 'بدء فاتورة جديدة؟ سيتم مسح البيانات الحالية.' : 'Start new invoice? Current data will be cleared.' ?>')) {
        location.reload(); 
    }
});

/* ---------- Navigation ---------- */
async function loadSaleIntoForm(id) {
    message.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Loading...';
    const res = await fetch('?action=load_sale&id=' + encodeURIComponent(id));
    const j = await res.json();
    message.innerHTML = '';
    
    if (!j.success) { alert('Cannot load invoice'); return; }
    
    const s = j.sale;
    saleIdInput.value = s.id;
    document.getElementById('invoiceNo').value = s.invoice_no;
    document.getElementById('invoiceDate').value = s.created_at ? s.created_at.replace(' ','T').slice(0,16) : '';
    
    itemsTbody.innerHTML = '';
    emptyState.classList.add('d-none');
    
    (j.items || []).forEach(it=>{
        addRow(
            it.product_id, 
            it.sku || '', 
            it.name || ('#'+it.product_id), 
            parseFloat(it.unit_price).toFixed(2), 
            parseFloat(it.cost || 0).toFixed(2),
            parseFloat(it.stock || 0)
        );
        const tr = itemsTbody.firstElementChild; 
        tr.querySelector('.unit-price').value = parseFloat(it.unit_price).toFixed(2);
        tr.querySelector('.qty').value = parseFloat(it.qty).toFixed(2);
        // Recalc discount
        const lineTotal = parseFloat(it.unit_price) * parseFloat(it.qty);
        const savedSub = parseFloat(it.subtotal);
        const discVal = (lineTotal - savedSub);
        tr.querySelector('.discount').value = discVal > 0 ? discVal.toFixed(2) : 0;
    });

    amountPaidInput.value = parseFloat(s.paid).toFixed(2);
    noteInput.value = s.note || '';
    
    if (s.customer_id) {
        customerSelect.value = s.customer_id;
        customerSearch.value = s.customer_name || '';
        customerBalance.classList.remove('d-none');
        customerBalance.innerHTML = '...'; 
        fetch('?action=get_customer_balance&id=' + s.customer_id).then(r=>r.json()).then(res=>{
             if (res.success) customerBalance.innerHTML = `<?= $is_ar ? 'الرصيد:' : 'Balance:' ?> ${parseFloat(res.balance).toFixed(2)}`;
             calcTotals();
        });
    } else {
        customerSelect.value = '';
        customerSearch.value = '';
        customerBalance.classList.add('d-none');
        calcTotals();
    }
}

prevBtn.addEventListener('click', async ()=>{
    let sid = saleIdInput.value ? parseInt(saleIdInput.value) : null;
    if (!sid) {
        const r = await fetch('?action=get_latest_sale');
        const j = await r.json();
        if (j.success && j.latest_id) loadSaleIntoForm(j.latest_id);
        else alert('No records / No sales yet');
        return;
    }
    const res = await fetch('?action=get_adjacent_sale&sale_id=' + sid + '&dir=prev');
    const j = await res.json();
    if (j.success && j.adjacent_id) loadSaleIntoForm(j.adjacent_id);
    else alert('End of list (Oldest)');
});

nextBtn.addEventListener('click', async ()=>{
    const sid = saleIdInput.value ? parseInt(saleIdInput.value) : null;
    if (!sid) return;
    const res = await fetch('?action=get_adjacent_sale&sale_id=' + sid + '&dir=next');
    const j = await res.json();
    if (j.success && j.adjacent_id) loadSaleIntoForm(j.adjacent_id);
    else alert('You are at the newest invoice');
});

/* Auto add from PHP GET param */
document.addEventListener('DOMContentLoaded', function(){
    /* 1. Check for Auto-Add Product */
    <?php if (!empty($autoAddProduct)): ?>
    let p = <?= $autoAddProduct ?>;
    addRow(p.id, p.sku, p.name, p.price, p.cost, p.stock);
    calcTotals();
    <?php endif; ?>

    /* 2. Check for Edit ID in URL */
    const urlParams = new URLSearchParams(window.location.search);
    const editId = urlParams.get('id');
    if (editId) {
        loadSaleIntoForm(editId);
    }
});

/* Initialize */
calcTotals();
</script>
</body>
</html>