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

function esc($v) { return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }
function json_out($data) { header('Content-Type: application/json; charset=utf-8'); echo json_encode($data, JSON_UNESCAPED_UNICODE); exit; }
function validateDate($date) {
    if (!$date) return date('Y-m-d');
    $d = DateTime::createFromFormat('Y-m-d', $date);
    return $d && $d->format('Y-m-d') === $date ? $date : date('Y-m-d');
}

 $lang = ($_GET['lang'] ?? 'en') === 'ar' ? 'ar' : 'en';
 $is_ar = $lang === 'ar';

 $from = validateDate($_GET['from'] ?? '');
 $to = validateDate($_GET['to'] ?? '');
if ($from > $to) { $temp = $from; $from = $to; $to = $temp; }

 $from_dt = $from . ' 00:00:00';
 $to_dt = $to . ' 23:59:59';

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

// ============================================
// DATA ENDPOINT
// ============================================
if ($action === 'data') {
    try {
        // Previous period
        $days_diff = (strtotime($to) - strtotime($from)) / 86400 + 1;
        $prev_from = date('Y-m-d', strtotime($from . " -{$days_diff} days"));
        $prev_to = date('Y-m-d', strtotime($from . " -1 day"));
        $prev_from_dt = $prev_from . ' 00:00:00';
        $prev_to_dt = $prev_to . ' 23:59:59';

        // Current sales
        $stmt = $pdo->prepare("SELECT COALESCE(SUM(total),0) AS sales_sum, COALESCE(SUM(profit),0) AS profit_sum, COUNT(*) AS invoices_count
                               FROM sales WHERE created_at BETWEEN ? AND ?");
        $stmt->execute([$from_dt, $to_dt]);
        $salesRow = $stmt->fetch(PDO::FETCH_ASSOC);

        // Previous sales
        $stmt = $pdo->prepare("SELECT COALESCE(SUM(total),0) AS sales_sum, COALESCE(SUM(profit),0) AS profit_sum
                               FROM sales WHERE created_at BETWEEN ? AND ?");
        $stmt->execute([$prev_from_dt, $prev_to_dt]);
        $prevSalesRow = $stmt->fetch(PDO::FETCH_ASSOC);

        $sales_change = $prevSalesRow['sales_sum'] > 0 ? (($salesRow['sales_sum'] - $prevSalesRow['sales_sum']) / $prevSalesRow['sales_sum']) * 100 : 0;
        $profit_change = $prevSalesRow['profit_sum'] > 0 ? (($salesRow['profit_sum'] - $prevSalesRow['profit_sum']) / $prevSalesRow['profit_sum']) * 100 : 0;

        $profit_margin = $salesRow['sales_sum'] > 0 ? ($salesRow['profit_sum'] / $salesRow['sales_sum']) * 100 : 0;
        $avg_invoice = $salesRow['invoices_count'] > 0 ? $salesRow['sales_sum'] / $salesRow['invoices_count'] : 0;

        // ===== CASH OUT BY CATEGORY =====
        $stmt = $pdo->prepare("SELECT COALESCE(category, 'other_expense') AS category, COALESCE(SUM(amount),0) AS sum_amount
                               FROM cash_transactions 
                               WHERE created_at BETWEEN ? AND ? AND `type` = 'out'
                               GROUP BY category");
        $stmt->execute([$from_dt, $to_dt]);
        $expenseByCategory = [];
        foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $r) {
            $expenseByCategory[$r['category']] = (float)$r['sum_amount'];
        }

        // Extract specific categories
        $purchases_paid = (float)($expenseByCategory['purchase'] ?? 0);
        $supplier_payments = (float)($expenseByCategory['supplier_payment'] ?? 0);
        $profit_withdrawals = (float)($expenseByCategory['profit_withdrawal'] ?? 0);
        $operating_expenses = (float)($expenseByCategory['expense'] ?? 0);
        $corrections = (float)($expenseByCategory['correction'] ?? 0);
        $other_expenses = (float)($expenseByCategory['other_expense'] ?? 0);

        // Total cash out
        $total_cash_out = array_sum($expenseByCategory);

        // Cash in by category
        $stmt = $pdo->prepare("SELECT COALESCE(category, 'other_income') AS category, COALESCE(SUM(amount),0) AS sum_amount
                               FROM cash_transactions 
                               WHERE created_at BETWEEN ? AND ? AND `type` = 'in'
                               GROUP BY category");
        $stmt->execute([$from_dt, $to_dt]);
        $incomeByCategory = [];
        foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $r) {
            $incomeByCategory[$r['category']] = (float)$r['sum_amount'];
        }
        $supplier_receipts = (float)($incomeByCategory['supplier_receipt'] ?? 0);
        $total_cash_in = array_sum($incomeByCategory);

        // Net profit calculation (الربح الصافي الحقيقي)
        // ربح المبيعات - المشتريات المدفوعة - المصاريف التشغيلية - دفعات الموردين
        $net_profit = $salesRow['profit_sum'] - $operating_expenses - $corrections;

        // Supplier balance (from suppliers table)
        $has_suppliers = false;
        try { $res = $pdo->query("SHOW TABLES LIKE 'suppliers'")->fetchColumn(); if ($res) $has_suppliers = true; } catch (Exception $e){}
        
        $supplier_debt = 0;
        if ($has_suppliers) {
            $stmt = $pdo->query("SELECT COALESCE(SUM(CASE WHEN balance > 0 THEN balance ELSE 0 END),0) FROM suppliers");
            $supplier_debt = (float)$stmt->fetchColumn();
        }

        // Customer debts
        $stmt = $pdo->query("SELECT COALESCE(SUM(CASE WHEN balance>0 THEN balance ELSE 0 END),0) FROM customers");
        $debts_total = (float)$stmt->fetchColumn();

        // Inventory
        $stmt = $pdo->query("SELECT COALESCE(SUM(COALESCE(stock,0) * COALESCE(cost,0)),0) FROM products");
        $inventory_value = (float)$stmt->fetchColumn();

        // Cash balance (all time)
        $stmt = $pdo->query("SELECT COALESCE(SUM(CASE WHEN `type`='in' THEN amount WHEN `type`='out' THEN -amount ELSE 0 END),0) FROM cash_transactions");
        $cash_balance = (float)$stmt->fetchColumn();

        $total_balance = $cash_balance + $debts_total + $inventory_value;

        // Purchases totals (from purchases table)
        $has_purchases = false;
        try { $res = $pdo->query("SHOW TABLES LIKE 'purchases'")->fetchColumn(); if ($res) $has_purchases = true; } catch (Exception $e){}
        
        $purchases_total = 0;
        $purchases_unpaid = 0;
        if ($has_purchases) {
            $stmt = $pdo->prepare("SELECT COALESCE(SUM(total),0), COALESCE(SUM(total - paid),0) FROM purchases WHERE created_at BETWEEN ? AND ?");
            $stmt->execute([$from_dt, $to_dt]);
            $pRow = $stmt->fetch(PDO::FETCH_NUM);
            $purchases_total = (float)$pRow[0];
            $purchases_unpaid = (float)$pRow[1];
        }

        // Sales list
        $stmt = $pdo->prepare("SELECT s.*, c.name AS customer_name FROM sales s LEFT JOIN customers c ON c.id = s.customer_id
                               WHERE s.created_at BETWEEN ? AND ? ORDER BY s.created_at DESC LIMIT 200");
        $stmt->execute([$from_dt, $to_dt]);
        $sales_list = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Cash list (with category)
        $stmt = $pdo->prepare("SELECT *, COALESCE(category, 'other') AS cat FROM cash_transactions WHERE created_at BETWEEN ? AND ? ORDER BY created_at DESC LIMIT 200");
        $stmt->execute([$from_dt, $to_dt]);
        $cash_list = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $sales_total_sum = 0; $sales_profit_sum = 0;
        foreach ($sales_list as $sl) { $sales_total_sum += (float)$sl['total']; $sales_profit_sum += (float)$sl['profit']; }

        $cash_total_in = 0; $cash_total_out = 0;
        foreach ($cash_list as $cl) { if ($cl['type'] === 'in') $cash_total_in += (float)$cl['amount']; else $cash_total_out += (float)$cl['amount']; }

        // Chart data
        $start = new DateTime($from);
        $end = new DateTime($to);
        $period = new DatePeriod($start, new DateInterval('P1D'), $end->modify('+1 day'));
        $dates = [];
        foreach ($period as $dt) $dates[] = $dt->format('Y-m-d');

        $stmt = $pdo->prepare("SELECT DATE(created_at) AS d, COALESCE(SUM(total),0) AS sales, COALESCE(SUM(profit),0) AS profit
                               FROM sales WHERE created_at BETWEEN ? AND ? GROUP BY DATE(created_at)");
        $stmt->execute([$from_dt, $to_dt]);
        $dailySales = [];
        foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $r) $dailySales[$r['d']] = $r;
        $sales_by_date = []; $profit_by_date = [];
        foreach ($dates as $d) {
            $sales_by_date[] = isset($dailySales[$d]) ? (float)$dailySales[$d]['sales'] : 0;
            $profit_by_date[] = isset($dailySales[$d]) ? (float)$dailySales[$d]['profit'] : 0;
        }

        $stmt = $pdo->prepare("SELECT DATE(created_at) AS d, `type`, COALESCE(SUM(amount),0) AS amt
                               FROM cash_transactions WHERE created_at BETWEEN ? AND ? GROUP BY DATE(created_at), `type`");
        $stmt->execute([$from_dt, $to_dt]);
        $dailyCash = [];
        foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $r) {
            $d = $r['d'];
            if (!isset($dailyCash[$d])) $dailyCash[$d] = ['in'=>0,'out'=>0];
            $dailyCash[$d][$r['type']] = (float)$r['amt'];
        }
        $cash_in_by_date = []; $cash_out_by_date = [];
        foreach ($dates as $d) {
            $cash_in_by_date[] = isset($dailyCash[$d]) ? $dailyCash[$d]['in'] : 0;
            $cash_out_by_date[] = isset($dailyCash[$d]) ? $dailyCash[$d]['out'] : 0;
        }

        // Payment methods
        $stmt = $pdo->prepare("SELECT payment_method, COALESCE(SUM(total),0) AS total, COUNT(*) AS count
                               FROM sales WHERE created_at BETWEEN ? AND ? GROUP BY payment_method ORDER BY total DESC");
        $stmt->execute([$from_dt, $to_dt]);
        $payment_methods = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // Top customers
        $stmt = $pdo->prepare("SELECT c.name, COALESCE(SUM(s.total),0) AS total, COUNT(s.id) AS invoices
                               FROM sales s JOIN customers c ON c.id = s.customer_id
                               WHERE s.created_at BETWEEN ? AND ? AND c.name IS NOT NULL AND c.name != ''
                               GROUP BY s.customer_id ORDER BY total DESC LIMIT 5");
        $stmt->execute([$from_dt, $to_dt]);
        $top_customers = $stmt->fetchAll(PDO::FETCH_ASSOC);

        json_out([
            'success' => true,
            'from' => $from, 'to' => $to,
            'generated_at' => date('Y-m-d H:i:s'),
            'comparison' => [
                'prev_from' => $prev_from, 'prev_to' => $prev_to,
                'prev_label' => $is_ar ? "مقارنة: $prev_from → $prev_to" : "vs: $prev_from → $prev_to"
            ],
            'summary' => [
                'sales_sum' => (float)$salesRow['sales_sum'],
                'profit_sum' => (float)$salesRow['profit_sum'],
                'invoices_count' => (int)$salesRow['invoices_count'],
                'sales_change' => round($sales_change, 1),
                'profit_change' => round($profit_change, 1),
                'profit_margin' => round($profit_margin, 1),
                'avg_invoice' => round($avg_invoice, 2),
                
                // Cash flow
                'cash_in' => $total_cash_in,
                'cash_out' => $total_cash_out,
                'cash_balance' => $cash_balance,
                
                // ===== BREAKDOWN BY CATEGORY =====
                'purchases_paid' => $purchases_paid,
                'supplier_payments' => $supplier_payments,
                'operating_expenses' => $operating_expenses,
                'profit_withdrawals' => $profit_withdrawals,
                'corrections' => $corrections,
                'other_expenses' => $other_expenses,
                'supplier_receipts' => $supplier_receipts,
                
                // Purchases totals
                'purchases_total' => $purchases_total,
                'purchases_unpaid' => $purchases_unpaid,
                
                // Net profit (الربح الصافي الحقيقي)
                'net_profit' => round($net_profit, 2),
                
                // Balances
                'debts_total' => $debts_total,
                'supplier_debt' => $supplier_debt,
                'inventory_value' => $inventory_value,
                'total_balance' => $total_balance
            ],
            'analytics' => [
                'payment_methods' => $payment_methods,
                'top_customers' => $top_customers
            ],
            'lists' => [
                'sales' => $sales_list,
                'cash_transactions' => $cash_list,
                'sales_totals' => ['total' => $sales_total_sum, 'profit' => $sales_profit_sum],
                'cash_totals' => ['in' => $cash_total_in, 'out' => $cash_total_out]
            ],
            'charts' => [
                'dates' => $dates,
                'sales_by_date' => $sales_by_date,
                'profit_by_date' => $profit_by_date,
                'cash_in_by_date' => $cash_in_by_date,
                'cash_out_by_date' => $cash_out_by_date
            ]
        ]);
    } catch (Exception $e) {
        json_out(['success' => false, 'error' => $e->getMessage()]);
    }
}

// ============================================
// CSV EXPORT
// ============================================
if ($action === 'export') {
    try {
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="cash_report_'.$from.'_to_'.$to.'.csv"');
        $out = fopen('php://output', 'w');
        fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF));
        
        fputcsv($out, [$is_ar ? 'تقرير مالي شامل' : 'Comprehensive Financial Report']);
        fputcsv($out, [$is_ar ? 'من' : 'From', $from, $is_ar ? 'إلى' : 'To', $to]);
        fputcsv($out, [$is_ar ? 'تصدير' : 'Exported', date('Y-m-d H:i:s')]);
        fputcsv($out, []);

        // Sales
        $stmt = $pdo->prepare("SELECT COALESCE(SUM(total),0) AS s, COALESCE(SUM(profit),0) AS p, COUNT(*) AS c FROM sales WHERE created_at BETWEEN ? AND ?");
        $stmt->execute([$from_dt, $to_dt]); $r = $stmt->fetch(PDO::FETCH_ASSOC);

        // Cash by category
        $stmt = $pdo->prepare("SELECT `type`, COALESCE(category,'other') AS cat, COALESCE(SUM(amount),0) AS a FROM cash_transactions WHERE created_at BETWEEN ? AND ? GROUP BY `type`, cat ORDER BY `type`, a DESC");
        $stmt->execute([$from_dt, $to_dt]);

        fputcsv($out, [$is_ar ? 'ملخص' : 'Summary']);
        fputcsv($out, [$is_ar ? 'المبيعات' : 'Sales', $r['s'], $is_ar ? 'الأرباح' : 'Profit', $r['p'], $is_ar ? 'فواتير' : 'Invoices', $r['c']]);
        fputcsv($out, []);
        
        fputcsv($out, [$is_ar ? 'تفصيل الصندوق' : 'Cash Breakdown']);
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            fputcsv($out, [$row['type'], $row['cat'], $row['a']]);
        }
        fputcsv($out, []);

        // Sales details
        fputcsv($out, [$is_ar ? 'المبيعات' : 'Sales Details']);
        fputcsv($out, [$is_ar ? 'فاتورة' : 'Inv', $is_ar ? 'العميل' : 'Customer', $is_ar ? 'المجموع' : 'Total', $is_ar ? 'الربح' : 'Profit', $is_ar ? 'التاريخ' : 'Date']);
        $stmt = $pdo->prepare("SELECT s.*, c.name AS cn FROM sales s LEFT JOIN customers c ON c.id=s.customer_id WHERE s.created_at BETWEEN ? AND ? ORDER BY s.created_at DESC");
        $stmt->execute([$from_dt, $to_dt]);
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)) fputcsv($out, [$row['invoice_no'], $row['cn']??'', $row['total'], $row['profit'], $row['created_at']]);
        fputcsv($out, []);

        // Cash transactions
        fputcsv($out, [$is_ar ? 'حركة الصندوق' : 'Cash Transactions']);
        fputcsv($out, [$is_ar ? 'النوع' : 'Type', $is_ar ? 'التصنيف' : 'Category', $is_ar ? 'المبلغ' : 'Amount', $is_ar ? 'الوصف' : 'Desc', $is_ar ? 'التاريخ' : 'Date']);
        $stmt = $pdo->prepare("SELECT * FROM cash_transactions WHERE created_at BETWEEN ? AND ? ORDER BY created_at DESC");
        $stmt->execute([$from_dt, $to_dt]);
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)) fputcsv($out, [$row['type'], $row['category']??'', $row['amount'], $row['description'], $row['created_at']]);
        
        fclose($out); exit;
    } catch (Exception $e) { die('Export failed: '.$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 ? 'التقرير المالي' : 'Financial Report' ?> | BOB POS</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;500;600;700;800&family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
  <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
  <style>
    :root{--font-ar:'Cairo',sans-serif;--font-en:'Inter',sans-serif;--bg-body:#f0f2f5;--card-bg:#fff;--primary:#4f46e5;--primary-light:#eef2ff;--success:#16a34a;--success-light:#f0fdf4;--danger:#dc2626;--danger-light:#fef2f2;--warning:#d97706;--warning-light:#fffbeb;--info:#0284c7;--info-light:#f0f9ff;--purple:#7c3aed;--purple-light:#f5f3ff;--text-main:#0f172a;--text-secondary:#475569;--text-muted:#94a3b8;--border-color:#e2e8f0;--shadow-sm:0 1px 2px rgba(0,0,0,.05);--shadow-md:0 4px 6px -1px rgba(0,0,0,.1);--shadow-lg:0 10px 15px -3px rgba(0,0,0,.1);--radius-sm:8px;--radius-md:12px;--radius-lg:16px;--transition:all .2s cubic-bezier(.4,0,.2,1)}
    [data-theme="dark"]{--bg-body:#0f172a;--card-bg:#1e293b;--text-main:#f1f5f9;--text-secondary:#cbd5e1;--text-muted:#64748b;--border-color:#334155;--shadow-sm:0 1px 2px rgba(0,0,0,.3);--shadow-md:0 4px 6px rgba(0,0,0,.4);--shadow-lg:0 10px 15px rgba(0,0,0,.5);--primary-light:#1e1b4b;--success-light:#052e16;--danger-light:#450a0a;--warning-light:#451a03;--info-light:#082f49;--purple-light:#2e1065}
    *{box-sizing:border-box}body{background:var(--bg-body);font-family:var(--font-en);color:var(--text-main);transition:background .3s,color .3s;min-height:100vh;margin:0}
    [dir="rtl"] body{font-family:var(--font-ar)}
    ::selection{background:var(--primary);color:#fff}
    ::-webkit-scrollbar{width:5px;height:5px}::-webkit-scrollbar-track{background:transparent}::-webkit-scrollbar-thumb{background:var(--text-muted);border-radius:3px}
    .navbar{background:var(--card-bg)!important;box-shadow:var(--shadow-sm);padding:.65rem 1rem;position:sticky;top:0;z-index:1000;transition:var(--transition)}
    .brand-icon{width:38px;height:38px;background:linear-gradient(135deg,var(--primary),#7c3aed);border-radius:var(--radius-sm);display:flex;align-items:center;justify-content:center;color:#fff;font-size:1.1rem}
    .nav-btn{border-radius:var(--radius-sm);font-weight:500;padding:.45rem .85rem;transition:var(--transition);border:1px solid var(--border-color);color:var(--text-secondary);background:var(--card-bg);cursor:pointer;font-size:.875rem;display:inline-flex;align-items:center;gap:6px;text-decoration:none}
    .nav-btn:hover{border-color:var(--primary);color:var(--primary);transform:translateY(-1px)}
    .theme-btn{width:36px;height:36px;padding:0;display:flex;align-items:center;justify-content:center;border-radius:var(--radius-sm)!important;font-size:1rem}
    .shortcut-hint{font-size:.65rem;color:var(--text-muted);background:var(--bg-body);padding:1px 5px;border-radius:3px;margin-inline-start:4px;border:1px solid var(--border-color)}
    .main-container{max-width:1480px;margin:1.25rem auto;padding:0 1.25rem}
    .filter-bar{background:var(--card-bg);padding:1.1rem 1.25rem;border-radius:var(--radius-lg);border:1px solid var(--border-color);margin-bottom:1.5rem;box-shadow:var(--shadow-sm);transition:var(--transition)}
    .quick-btn{padding:.35rem .75rem;font-size:.78rem;font-weight:500;border-radius:20px;border:1px solid var(--border-color);color:var(--text-secondary);background:transparent;transition:var(--transition);white-space:nowrap;cursor:pointer}
    .quick-btn:hover,.quick-btn.active{background:var(--primary);color:#fff;border-color:var(--primary);transform:translateY(-1px)}
    .form-control{border:1px solid var(--border-color);border-radius:var(--radius-sm);padding:.45rem .7rem;font-size:.875rem;color:var(--text-main);background:var(--card-bg);transition:var(--transition)}
    .form-control:focus{border-color:var(--primary);box-shadow:0 0 0 3px rgba(79,70,229,.15)}
    .act-btn{border-radius:var(--radius-sm);font-weight:600;padding:.45rem 1.1rem;transition:var(--transition);font-size:.82rem;cursor:pointer;display:inline-flex;align-items:center;gap:5px;border:none}
    .btn-apply{background:linear-gradient(135deg,var(--primary),#6366f1);color:#fff;box-shadow:0 2px 8px rgba(79,70,229,.3)}
    .btn-apply:hover{transform:translateY(-2px);box-shadow:0 4px 12px rgba(79,70,229,.4)}
    .btn-apply.loading{pointer-events:none;opacity:.7}
    .btn-outline-exp{border:1px solid var(--success);color:var(--success);background:transparent}
    .btn-outline-exp:hover{background:var(--success);color:#fff;transform:translateY(-2px)}
    .btn-outline-prt{border:1px solid var(--info);color:var(--info);background:transparent}
    .btn-outline-prt:hover{background:var(--info);color:#fff;transform:translateY(-2px)}
    .status-bar{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:.5rem;margin-bottom:1rem;padding:0 .25rem}
    .comp-badge{display:inline-flex;align-items:center;gap:5px;background:var(--card-bg);padding:.35rem .75rem;border-radius:20px;font-size:.73rem;color:var(--text-muted);border:1px solid var(--border-color)}
    .last-updated{font-size:.75rem;color:var(--text-muted);display:flex;align-items:center;gap:5px}
    .pulse-dot{width:6px;height:6px;border-radius:50%;background:var(--success);animation:pulse 2s infinite}
    @keyframes pulse{0%,100%{opacity:1}50%{opacity:.4}}
    .stat-card{background:var(--card-bg);border:1px solid var(--border-color);border-radius:var(--radius-md);padding:1.35rem;transition:var(--transition);position:relative;overflow:hidden}
    .stat-card::before{content:'';position:absolute;top:0;left:0;right:0;height:3px;border-radius:var(--radius-md) var(--radius-md) 0 0;opacity:0;transition:var(--transition)}
    .stat-card:hover{transform:translateY(-4px);box-shadow:var(--shadow-lg)}
    .stat-card:hover::before{opacity:1}
    .stat-card.c-primary::before{background:linear-gradient(90deg,var(--primary),#7c3aed)}
    .stat-card.c-success::before{background:linear-gradient(90deg,var(--success),#22c55e)}
    .stat-card.c-info::before{background:linear-gradient(90deg,var(--info),#0ea5e9)}
    .stat-card.c-dark::before{background:linear-gradient(90deg,#475569,#64748b)}
    .stat-card.c-warning::before{background:linear-gradient(90deg,var(--warning),#f59e0b)}
    .stat-card.c-danger::before{background:linear-gradient(90deg,var(--danger),#ef4444)}
    .stat-card.c-purple::before{background:linear-gradient(90deg,#7c3aed,#a78bfa)}
    .stat-icon{width:48px;height:48px;border-radius:var(--radius-sm);display:flex;align-items:center;justify-content:center;font-size:1.3rem;flex-shrink:0}
    .ic-blue{background:var(--primary-light);color:var(--primary)}
    .ic-green{background:var(--success-light);color:var(--success)}
    .ic-purple{background:var(--purple-light);color:var(--purple)}
    .ic-info{background:var(--info-light);color:var(--info)}
    .ic-orange{background:var(--warning-light);color:var(--warning)}
    .ic-red{background:var(--danger-light);color:var(--danger)}
    .stat-label{font-size:.75rem;color:var(--text-muted);font-weight:500;margin-bottom:3px;text-transform:uppercase;letter-spacing:.03em}
    .stat-value{font-size:1.5rem;font-weight:700;line-height:1.2}
    .change-badge{display:inline-flex;align-items:center;gap:2px;padding:2px 7px;border-radius:20px;font-size:.7rem;font-weight:600;margin-top:5px}
    .change-badge.up{background:var(--success-light);color:var(--success)}
    .change-badge.down{background:var(--danger-light);color:var(--danger)}
    .change-badge.neutral{background:var(--warning-light);color:var(--warning)}
    .stat-extra{font-size:.72rem;color:var(--text-muted);margin-top:4px}
    .dark-card{background:linear-gradient(135deg,#1e293b,#334155);border-color:transparent}
    [data-theme="dark"] .dark-card{background:linear-gradient(135deg,#0f172a,#1e293b)}
    .dark-card .stat-label{color:#94a3b8}.dark-card .stat-value{color:#fff}
    .mini-stat{background:var(--card-bg);border:1px solid var(--border-color);border-radius:var(--radius-md);padding:.9rem 1.1rem;transition:var(--transition);display:flex;align-items:center;justify-content:space-between}
    .mini-stat:hover{transform:translateY(-2px);box-shadow:var(--shadow-md)}
    .mini-label{font-size:.72rem;color:var(--text-muted);font-weight:500;margin-bottom:2px}
    .mini-value{font-size:1.15rem;font-weight:700}
    .analytics-card{background:var(--card-bg);border:1px solid var(--border-color);border-radius:var(--radius-md);box-shadow:var(--shadow-sm);transition:var(--transition);height:100%;display:flex;flex-direction:column}
    .analytics-card:hover{box-shadow:var(--shadow-md)}
    .analytics-header{padding:1rem 1.25rem;border-bottom:1px solid var(--border-color);display:flex;justify-content:space-between;align-items:center}
    .analytics-title{font-weight:600;font-size:.9rem;margin:0;display:flex;align-items:center;gap:7px}
    .analytics-body{padding:1rem 1.25rem;flex:1;overflow-y:auto}
    .customer-item{display:flex;align-items:center;gap:.75rem;padding:.6rem 0;border-bottom:1px solid var(--border-color)}
    .customer-item:last-child{border-bottom:none}
    .customer-rank{width:24px;height:24px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:.7rem;font-weight:700;flex-shrink:0}
    .rank-1{background:linear-gradient(135deg,#fbbf24,#f59e0b);color:#fff}
    .rank-2{background:linear-gradient(135deg,#9ca3af,#6b7280);color:#fff}
    .rank-3{background:linear-gradient(135deg,#d97706,#b45309);color:#fff}
    .rank-other{background:var(--bg-body);color:var(--text-muted)}
    .customer-info{flex:1;min-width:0}
    .customer-name{font-size:.85rem;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
    .customer-invoices{font-size:.72rem;color:var(--text-muted)}
    .customer-total{font-size:.85rem;font-weight:700;color:var(--primary);white-space:nowrap}
    .expense-item{display:flex;align-items:center;gap:.75rem;padding:.5rem 0;border-bottom:1px solid var(--border-color)}
    .expense-item:last-child{border-bottom:none}
    .expense-dot{width:8px;height:8px;border-radius:50%;flex-shrink:0}
    .expense-info{flex:1;min-width:0}
    .expense-name{font-size:.82rem;font-weight:500}
    .expense-bar{height:5px;border-radius:3px;background:var(--bg-body);margin-top:3px;overflow:hidden}
    [data-theme="dark"] .expense-bar{background:#334155}
    .expense-fill{height:100%;border-radius:3px;transition:width .6s ease}
    .expense-amount{font-size:.82rem;font-weight:600;white-space:nowrap}
    .payment-item{display:flex;align-items:center;gap:.75rem;padding:.5rem 0}
    .payment-dot{width:10px;height:10px;border-radius:50%;flex-shrink:0}
    .payment-info{flex:1}
    .payment-name{font-size:.82rem;font-weight:500}
    .payment-bar{height:6px;border-radius:3px;background:var(--bg-body);margin-top:4px;overflow:hidden}
    [data-theme="dark"] .payment-bar{background:#334155}
    .payment-fill{height:100%;border-radius:3px;transition:width .6s ease}
    .payment-amount{font-size:.82rem;font-weight:600;white-space:nowrap}
    .chart-card{background:var(--card-bg);border:1px solid var(--border-color);border-radius:var(--radius-md);box-shadow:var(--shadow-sm);transition:var(--transition);height:100%}
    .chart-card:hover{box-shadow:var(--shadow-md)}
    .chart-header{padding:1rem 1.25rem;border-bottom:1px solid var(--border-color);display:flex;justify-content:space-between;align-items:center}
    .chart-title{font-weight:600;font-size:.9rem;margin:0;display:flex;align-items:center;gap:7px}
    .chart-body{padding:1rem 1.25rem;position:relative;height:300px}
    .table-card{background:var(--card-bg);border:1px solid var(--border-color);border-radius:var(--radius-md);box-shadow:var(--shadow-sm);transition:var(--transition);height:100%;display:flex;flex-direction:column}
    .table-card:hover{box-shadow:var(--shadow-md)}
    .table-header{padding:.85rem 1.1rem;border-bottom:1px solid var(--border-color);display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:.6rem}
    .table-title{font-weight:600;font-size:.9rem;margin:0}
    .table-search{position:relative}
    .table-search input{padding-left:2.2rem;padding-right:.7rem;border:1px solid var(--border-color);border-radius:var(--radius-sm);font-size:.82rem;background:var(--card-bg);color:var(--text-main);width:180px;transition:var(--transition)}
    [dir="rtl"] .table-search input{padding-left:.7rem;padding-right:2.2rem}
    .table-search input:focus{border-color:var(--primary);box-shadow:0 0 0 3px rgba(79,70,229,.15);outline:none}
    .table-search i{position:absolute;left:.7rem;top:50%;transform:translateY(-50%);color:var(--text-muted);font-size:.85rem}
    [dir="rtl"] .table-search i{left:auto;right:.7rem}
    .table-responsive{max-height:400px;overflow-y:auto;flex:1}
    .table-custom{margin:0;font-size:.85rem}
    .table-custom thead th{background:var(--bg-body);color:var(--text-muted);font-weight:600;font-size:.72rem;text-transform:uppercase;letter-spacing:.05em;border-bottom:2px solid var(--border-color);padding:.65rem .85rem;position:sticky;top:0;z-index:2}
    .table-custom tbody td{padding:.6rem .85rem;border-bottom:1px solid var(--border-color);vertical-align:middle;color:var(--text-secondary);transition:var(--transition)}
    .table-custom tbody tr:hover td{background:var(--primary-light)}
    .table-custom tfoot td{padding:.65rem .85rem;background:var(--bg-body);font-weight:700;border-top:2px solid var(--border-color);color:var(--text-main);font-size:.85rem;position:sticky;bottom:0;z-index:2}
    .badge-type{padding:.3em .65em;border-radius:5px;font-weight:600;font-size:.7rem;display:inline-flex;align-items:center;gap:3px}
    .badge-in{background:var(--success-light);color:var(--success)}
    .badge-out{background:var(--danger-light);color:var(--danger)}
    .badge-cat{padding:.2em .5em;border-radius:4px;font-size:.65rem;font-weight:500;margin-inline-start:4px}
    .cat-purchase{background:var(--purple-light);color:var(--purple)}
    .cat-supplier{background:var(--info-light);color:var(--info)}
    .cat-profit{background:var(--warning-light);color:var(--warning)}
    .cat-expense{background:var(--danger-light);color:var(--danger)}
    .cat-correction{background:var(--bg-body);color:var(--text-muted)}
    .cat-receipt{background:var(--success-light);color:var(--success)}
    .cat-other{background:var(--bg-body);color:var(--text-muted)}
    .empty-state{text-align:center;padding:2.5rem 1rem;color:var(--text-muted)}
    .empty-state i{font-size:2.5rem;opacity:.3;margin-bottom:.75rem;display:block}
    .empty-state p{margin:0;font-size:.85rem}
    .skeleton{background:linear-gradient(90deg,var(--border-color) 25%,transparent 50%,var(--border-color) 75%);background-size:200% 100%;animation:skel 1.5s infinite;border-radius:var(--radius-sm)}
    @keyframes skel{0%{background-position:200% 0}100%{background-position:-200% 0}}
    .skel-card{background:var(--card-bg);border:1px solid var(--border-color);border-radius:var(--radius-md);padding:1.35rem}
    .toast-container{position:fixed;top:75px;right:20px;z-index:9999}
    [dir="rtl"] .toast-container{right:auto;left:20px}
    .custom-toast{background:var(--card-bg);border:1px solid var(--border-color);border-radius:var(--radius-sm);padding:.75rem 1.1rem;box-shadow:var(--shadow-lg);display:flex;align-items:center;gap:.6rem;margin-bottom:.4rem;min-width:260px;animation:toastIn .3s ease-out;color:var(--text-main);font-size:.85rem}
    .custom-toast.out{animation:toastOut .3s ease-in forwards}
    @keyframes toastIn{from{opacity:0;transform:translateX(100%)}to{opacity:1;transform:translateX(0)}}
    [dir="rtl"] @keyframes toastIn{from{opacity:0;transform:translateX(-100%)}to{opacity:1;transform:translateX(0)}}
    @keyframes toastOut{from{opacity:1;transform:translateX(0)}to{opacity:0;transform:translateX(100%)}}
    .footer{text-align:center;padding:1.5rem 0;color:var(--text-muted);font-size:.78rem}
    @media print{.navbar,.filter-bar,.nav-actions,.table-search,.no-print{display:none!important}body{background:#fff}.stat-card,.chart-card,.table-card,.analytics-card{box-shadow:none;border:1px solid #ddd;break-inside:avoid}.main-container{max-width:100%}.chart-body{height:200px}}
    .fade-in{animation:fadeIn .4s ease-out}
    @keyframes fadeIn{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}
    @media(max-width:768px){.main-container{padding:0 .75rem;margin:.75rem auto}.stat-value{font-size:1.25rem}.chart-body{height:240px}.table-search input{width:140px}.shortcut-hint{display:none}}
    @media(max-width:576px){.stat-value{font-size:1.05rem}.stat-icon{width:40px;height:40px;font-size:1rem}.mini-value{font-size:1rem}}
  </style>
</head>
<body class="<?= $is_ar ? 'rtl' : 'ltr' ?>">
<div class="toast-container" id="toastContainer"></div>
<nav class="navbar" role="navigation" aria-label="Main navigation">
  <div class="container-fluid d-flex justify-content-between align-items-center">
    <div class="d-flex align-items-center gap-3">
      <div class="brand-icon" aria-hidden="true"><i class="bi bi-wallet2"></i></div>
      <div>
        <span class="fw-bold fs-5 d-block" style="line-height:1.15"><?= $is_ar ? 'التقرير المالي' : 'Financial Report' ?></span>
        <small class="text-muted" style="font-size:.7rem"><?= $is_ar ? 'نظرة شاملة على الأداء' : 'Complete performance overview' ?></small>
      </div>
    </div>
    <div class="d-flex gap-2 no-print">
      <a href="index.php" class="nav-btn" aria-label="Home"><i class="bi bi-grid-1x2"></i><span class="d-none d-sm-inline"><?= $is_ar ? 'الرئيسية' : 'Home' ?></span></a>
      <a href="suppliers.php" class="nav-btn" aria-label="Suppliers"><i class="bi bi-truck"></i><span class="d-none d-sm-inline"><?= $is_ar ? 'الموردين' : 'Suppliers' ?></span></a>
      <a href="purchase_invoice.php" class="nav-btn" aria-label="Purchases"><i class="bi bi-bag"></i><span class="d-none d-sm-inline"><?= $is_ar ? 'المشتريات' : 'Purchases' ?></span></a>
      <button class="nav-btn theme-btn no-print" id="themeToggle" aria-label="Toggle theme"><i class="bi bi-moon-stars"></i></button>
      <a href="?lang=<?= $lang==='ar' ? 'en' : 'ar' ?>&from=<?=esc($from)?>&to=<?=esc($to)?>" class="nav-btn no-print" aria-label="Language"><span class="fw-bold"><?= $is_ar ? 'EN' : 'عربي' ?></span></a>
    </div>
  </div>
</nav>
<div class="main-container">
  <div class="filter-bar fade-in no-print" role="search" aria-label="Date filter">
    <div class="row align-items-end g-3">
      <div class="col-lg-4">
        <label class="form-label small fw-semibold text-muted mb-2"><i class="bi bi-lightning me-1"></i><?= $is_ar ? 'فلاتر سريعة' : 'Quick Filters' ?></label>
        <div class="d-flex gap-2 flex-wrap">
          <button class="quick-btn active" data-range="today"><?= $is_ar ? 'اليوم' : 'Today' ?></button>
          <button class="quick-btn" data-range="yesterday"><?= $is_ar ? 'أمس' : 'Yesterday' ?></button>
          <button class="quick-btn" data-range="week"><?= $is_ar ? 'الأسبوع' : 'Week' ?></button>
          <button class="quick-btn" data-range="month"><?= $is_ar ? 'الشهر' : 'Month' ?></button>
          <button class="quick-btn" data-range="lastmonth"><?= $is_ar ? 'الشهر الماضي' : 'Last Month' ?></button>
          <button class="quick-btn" data-range="year"><?= $is_ar ? 'العام' : 'Year' ?></button>
        </div>
      </div>
      <div class="col-lg-4">
        <label class="form-label small fw-semibold text-muted mb-2" for="fromDate"><i class="bi bi-calendar3 me-1"></i><?= $is_ar ? 'نطاق مخصص' : 'Custom Range' ?></label>
        <div class="d-flex gap-2 align-items-center">
          <input type="date" id="fromDate" class="form-control" value="<?= esc($from) ?>" aria-label="From">
          <span class="text-muted">→</span>
          <input type="date" id="toDate" class="form-control" value="<?= esc($to) ?>" aria-label="To">
        </div>
      </div>
      <div class="col-lg-4">
        <div class="d-flex gap-2 flex-wrap">
          <button type="button" id="applyBtn" class="act-btn btn-apply flex-grow-1"><i class="bi bi-search"></i> <?= $is_ar ? 'عرض' : 'Apply' ?><span class="shortcut-hint">Enter</span></button>
          <button type="button" id="printBtn" class="act-btn btn-outline-prt" aria-label="Print"><i class="bi bi-printer"></i></button>
          <a id="exportCsv" href="#" class="act-btn btn-outline-exp" aria-label="Export"><i class="bi bi-file-earmark-spreadsheet"></i></a>
        </div>
      </div>
    </div>
  </div>
  <div class="status-bar" id="statusBar" style="display:none">
    <span class="comp-badge" id="compBadge"><i class="bi bi-arrow-left-right"></i><span id="compText"></span></span>
    <span class="last-updated" id="lastUpdated"><span class="pulse-dot"></span><span id="updatedText"></span></span>
  </div>
  <div id="summary">
    <div class="row g-3 mb-3"><div class="col-md-6 col-xl-3"><div class="skel-card"><div class="skeleton" style="height:16px;width:55%;margin-bottom:8px"></div><div class="skeleton" style="height:28px;width:75%"></div></div></div><div class="col-md-6 col-xl-3"><div class="skel-card"><div class="skeleton" style="height:16px;width:55%;margin-bottom:8px"></div><div class="skeleton" style="height:28px;width:75%"></div></div></div><div class="col-md-6 col-xl-3"><div class="skel-card"><div class="skeleton" style="height:16px;width:55%;margin-bottom:8px"></div><div class="skeleton" style="height:28px;width:75%"></div></div></div><div class="col-md-6 col-xl-3"><div class="skel-card"><div class="skeleton" style="height:16px;width:55%;margin-bottom:8px"></div><div class="skeleton" style="height:28px;width:75%"></div></div></div></div>
    <div class="row g-3 mb-3"><div class="col-md-3"><div class="skel-card"><div class="skeleton" style="height:14px;width:45%;margin-bottom:6px"></div><div class="skeleton" style="height:22px;width:65%"></div></div></div><div class="col-md-3"><div class="skel-card"><div class="skeleton" style="height:14px;width:45%;margin-bottom:6px"></div><div class="skeleton" style="height:22px;width:65%"></div></div></div><div class="col-md-3"><div class="skel-card"><div class="skeleton" style="height:14px;width:45%;margin-bottom:6px"></div><div class="skeleton" style="height:22px;width:65%"></div></div></div><div class="col-md-3"><div class="skel-card"><div class="skeleton" style="height:14px;width:45%;margin-bottom:6px"></div><div class="skeleton" style="height:22px;width:65%"></div></div></div></div>
  </div>
  <div class="row g-4 mb-4" id="analyticsRow" style="display:none">
    <div class="col-lg-4">
      <div class="analytics-card fade-in">
        <div class="analytics-header"><h6 class="analytics-title"><span style="color:var(--danger)"><i class="bi bi-arrow-down-circle"></i></span><?= $is_ar ? 'تفصيل المصروفات' : 'Expense Breakdown' ?></h6></div>
        <div class="analytics-body" id="expenseBreakdown"></div>
      </div>
    </div>
    <div class="col-lg-4">
      <div class="analytics-card fade-in">
        <div class="analytics-header"><h6 class="analytics-title"><span style="color:var(--primary)"><i class="bi bi-trophy"></i></span><?= $is_ar ? 'أفضل العملاء' : 'Top Customers' ?></h6></div>
        <div class="analytics-body" id="topCustomersBody"></div>
      </div>
    </div>
    <div class="col-lg-4">
      <div class="analytics-card fade-in">
        <div class="analytics-header"><h6 class="analytics-title"><span style="color:var(--success)"><i class="bi bi-credit-card"></i></span><?= $is_ar ? 'طرق الدفع' : 'Payment Methods' ?></h6></div>
        <div class="analytics-body d-flex align-items-center justify-content-center" style="padding:1rem"><div style="width:100%;max-width:220px;position:relative;height:220px"><canvas id="paymentChart"></canvas></div></div>
      </div>
    </div>
  </div>
  <div class="row g-4 mb-4">
    <div class="col-lg-6"><div class="chart-card fade-in"><div class="chart-header"><h6 class="chart-title"><span style="color:var(--primary)"><i class="bi bi-graph-up"></i></span><?= $is_ar ? 'المبيعات والأرباح' : 'Sales & Profit' ?></h6></div><div class="chart-body"><canvas id="salesChart"></canvas></div></div></div>
    <div class="col-lg-6"><div class="chart-card fade-in"><div class="chart-header"><h6 class="chart-title"><span style="color:var(--success)"><i class="bi bi-cash-stack"></i></span><?= $is_ar ? 'حركة النقدية' : 'Cash Flow' ?></h6></div><div class="chart-body"><canvas id="cashChart"></canvas></div></div></div>
  </div>
  <div class="row g-4">
    <div class="col-lg-6">
      <div class="table-card fade-in">
        <div class="table-header"><h6 class="table-title"><i class="bi bi-receipt me-2 text-primary"></i><?= $is_ar ? 'المبيعات' : 'Sales' ?></h6><div class="table-search no-print"><i class="bi bi-search"></i><input type="text" id="salesSearch" placeholder="<?= $is_ar ? 'بحث...' : 'Search...' ?>"></div></div>
        <div class="table-responsive"><table class="table table-custom table-hover" id="salesTable"><thead><tr><th><?= $is_ar ? 'فاتورة' : 'Inv' ?></th><th><?= $is_ar ? 'العميل' : 'Customer' ?></th><th class="text-end"><?= $is_ar ? 'المجموع' : 'Total' ?></th><th class="text-end"><?= $is_ar ? 'الربح' : 'Profit' ?></th><th><?= $is_ar ? 'التاريخ' : 'Date' ?></th></tr></thead><tbody></tbody><tfoot id="salesFoot" style="display:none"></tfoot></table></div>
      </div>
    </div>
    <div class="col-lg-6">
      <div class="table-card fade-in">
        <div class="table-header"><h6 class="table-title"><i class="bi bi-arrow-left-right me-2 text-success"></i><?= $is_ar ? 'حركة الصندوق' : 'Cash Movements' ?></h6><div class="table-search no-print"><i class="bi bi-search"></i><input type="text" id="cashSearch" placeholder="<?= $is_ar ? 'بحث...' : 'Search...' ?>"></div></div>
        <div class="table-responsive"><table class="table table-custom table-hover" id="cashTable"><thead><tr><th><?= $is_ar ? 'النوع' : 'Type' ?></th><th><?= $is_ar ? 'التصنيف' : 'Category' ?></th><th><?= $is_ar ? 'الوصف' : 'Desc' ?></th><th class="text-end"><?= $is_ar ? 'المبلغ' : 'Amount' ?></th><th><?= $is_ar ? 'التاريخ' : 'Date' ?></th></tr></thead><tbody></tbody><tfoot id="cashFoot" style="display:none"></tfoot></table></div>
      </div>
    </div>
  </div>
  <div class="footer"><p class="mb-0">&copy; <?= date('Y') ?> BOB & POS System</p></div>
</div>
<script>
const lang="<?= $is_ar?'ar':'en'?>",isRTL=lang==='ar';
const T={sales:lang==='ar'?'إجمالي المبيعات':'Total Sales',profit:lang==='ar'?'صافي أرباح المبيعات':'Sales Profit',netProfit:lang==='ar'?'الربح الصافي الحقيقي':'Net Profit',cashBal:lang==='ar'?'رصيد الصندوق':'Cash Balance',totalBal:lang==='ar'?'الرصيد العام':'Total Balance',cashIn:lang==='ar'?'وارد نقدي':'Cash In',cashOut:lang==='ar'?'إجمالي المصروفات':'Total Out',debts:lang==='ar'?'ديون العملاء':'Cust. Debts',suppDebt:lang==='ar'?'ديون الموردين':'Supp. Debts',inventory:lang==='ar'?'قيمة المخزون':'Inventory',margin:lang==='ar'?'هامش الربح':'Margin',avgInv:lang==='ar'?'متوسط الفاتورة':'Avg Invoice',invoices:lang==='ar'?'فاتورة':'invoices',noData:lang==='ar'?'لا توجد بيانات':'No data',inL:lang==='ar'?'قبض':'In',outL:lang==='ar'?'صرف':'Out',chartSales:lang==='ar'?'المبيعات':'Sales',chartProfit:lang==='ar'?'الأرباح':'Profit',chartIn:lang==='ar'?'وارد':'In',chartOut:lang==='ar'?'صادر':'Out',updated:lang==='ar'?'آخر تحديث':'Last updated',at:lang==='ar'?'في':'at',total:lang==='ar'?'الإجمالي':'Total',noExp:lang==='ar'?'لا توجد مصروفات':'No expenses',other:lang==='ar'?'أخرى':'Other',cash:lang==='ar'?'نقدي':'Cash',card:lang==='ar'?'بطاقة':'Card',debt:lang==='ar'?'آجل':'Credit',errLoad:lang==='ar'?'خطأ':'Error loading',dataUpdated:lang==='ar'?'تم تحديث البيانات':'Data updated',
  catPurchase:lang==='ar'?'شراء بضاعة':'Purchases',catSupplier:lang==='ar'?'دفع مورد':'Supplier Pay',catProfit:lang==='ar'?'سحب أرباح':'Profit Draw',catExpense:lang==='ar'?'مصاريف تشغيلية':'Op. Expenses',catCorrection:lang==='ar'?'تصحيح':'Correction',catReceipt:lang==='ar'?'استلام من مورد':'Supp. Receipt',catOther:lang==='ar'?'أخرى':'Other',catOtherIn:lang==='ar'?'وارد أخرى':'Other In'};
const $=s=>document.querySelector(s),$$=s=>document.querySelectorAll(s);
const elFrom=$('#fromDate'),elTo=$('#toDate'),applyBtn=$('#applyBtn'),printBtn=$('#printBtn'),exportCsv=$('#exportCsv');
const summaryEl=$('#summary'),statusBar=$('#statusBar'),analyticsRow=$('#analyticsRow');
const salesChartCtx=$('#salesChart').getContext('2d'),cashChartCtx=$('#cashChart').getContext('2d'),paymentChartCtx=$('#paymentChart').getContext('2d');
let salesChart=null,cashChart=null,paymentChart=null,currentSalesData=[],currentCashData=[],salesTotals={},cashTotals={};
const fmt=n=>new Intl.NumberFormat(isRTL?'ar-SA':'en-US',{style:'decimal',minimumFractionDigits:2,maximumFractionDigits:2}).format(n);
const changeBadge=c=>{if(c===0)return`<span class="change-badge neutral"><i class="bi bi-dash"></i>0%</span>`;const u=c>0;return`<span class="change-badge ${u?'up':'down'}"><i class="bi bi-arrow${u?'-up':'-down'}-short"></i>${Math.abs(c)}%</span>`};
const toast=(msg,type='info')=>{const c=$('#toastContainer'),icons={success:'bi-check-circle-fill text-success',error:'bi-x-circle-fill text-danger',info:'bi-info-circle-fill text-info'};const t=document.createElement('div');t.className='custom-toast';t.innerHTML=`<i class="bi ${icons[type]} fs-5"></i><span>${msg}</span>`;c.appendChild(t);setTimeout(()=>{t.classList.add('out');setTimeout(()=>t.remove(),300)},3000)};
const debounce=(fn,w)=>{let t;return(...a)=>{clearTimeout(t);t=setTimeout(()=>fn(...a),w)}};
const emptyRow=s=>`<tr><td colspan="${s||5}" class="empty-state"><i class="bi bi-inbox"></i><p>${T.noData}</p></td></tr>`;
function animateValue(el,start,end,dur){const range=end-start;const st=performance.now();function up(ct){const el2=ct-st;const p=Math.min(el2/dur,1);const e=1-Math.pow(1-p,3);el.textContent=fmt(start+range*e);if(p<1)requestAnimationFrame(up)}requestAnimationFrame(up)}
const savedTheme=localStorage.getItem('theme');if(savedTheme)document.documentElement.setAttribute('data-theme',savedTheme);
function updateThemeIcon(t){$('#themeToggle i').className=t==='dark'?'bi bi-sun':'bi bi-moon-stars'}updateThemeIcon(savedTheme||'light');
 $('#themeToggle').addEventListener('click',()=>{const c=document.documentElement.getAttribute('data-theme'),n=c==='dark'?'light':'dark';document.documentElement.setAttribute('data-theme',n);localStorage.setItem('theme',n);updateThemeIcon(n);[salesChart,cashChart,paymentChart].forEach(ch=>{if(!ch)return;const tc=getComputedStyle(document.documentElement).getPropertyValue('--text-muted').trim();if(ch.options.scales?.x?.ticks)ch.options.scales.x.ticks.color=tc;if(ch.options.scales?.y?.ticks)ch.options.scales.y.ticks.color=tc;if(ch.options.plugins?.legend?.labels)ch.options.plugins.legend.labels.color=tc;ch.update()})});
const getToday=()=>new Date().toISOString().split('T')[0];
const getDateRange=r=>{const t=new Date();switch(r){case'today':return[getToday(),getToday()];case'yesterday':const y=new Date(t);y.setDate(y.getDate()-1);const ys=y.toISOString().split('T')[0];return[ys,ys];case'week':const dw=t.getDay(),sw=new Date(t);sw.setDate(t.getDate()-(dw===0?6:dw-1));return[sw.toISOString().split('T')[0],getToday()];case'month':return[`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,'0')}-01`,getToday()];case'lastmonth':const lm=new Date(t.getFullYear(),t.getMonth()-1,1),lme=new Date(t.getFullYear(),t.getMonth(),0);return[lm.toISOString().split('T')[0],lme.toISOString().split('T')[0]];case'year':return[`${t.getFullYear()}-01-01`,getToday()];default:return[getToday(),getToday()]}};
 $$('.quick-btn').forEach(b=>b.addEventListener('click',()=>{$$('.quick-btn').forEach(x=>x.classList.remove('active'));b.classList.add('active');const[f,t]=getDateRange(b.dataset.range);elFrom.value=f;elTo.value=t;loadData()}));
printBtn.addEventListener('click',()=>window.print());
const salesSearch=$('#salesSearch'),cashSearch=$('#cashSearch');
salesSearch.addEventListener('input',debounce(e=>{const q=e.target.value.toLowerCase();renderSalesTable(currentSalesData.filter(r=>Object.values(r).some(v=>String(v).toLowerCase().includes(q))))},250));
cashSearch.addEventListener('input',debounce(e=>{const q=e.target.value.toLowerCase();renderCashTable(currentCashData.filter(r=>Object.values(r).some(v=>String(v).toLowerCase().includes(q))))},250));

function getCatBadge(cat){const m={purchase:{l:T.catPurchase,c:'cat-purchase'},supplier_payment:{l:T.catSupplier,c:'cat-supplier'},profit_withdrawal:{l:T.catProfit,c:'cat-profit'},expense:{l:T.catExpense,c:'cat-expense'},correction:{l:T.catCorrection,c:'cat-correction'},supplier_receipt:{l:T.catReceipt,c:'cat-receipt'},other_expense:{l:T.catOther,c:'cat-other'},other_income:{l:T.catOtherIn,c:'cat-other'},other:{l:T.catOther,c:'cat-other'}};const i=m[cat]||m.other;return`<span class="badge-cat ${i.c}">${i.l}</span>`}

function renderSalesTable(data){const tb=$('#salesTable tbody'),foot=$('#salesFoot');if(!data.length){tb.innerHTML=emptyRow(5);foot.style.display='none';return}tb.innerHTML=data.map(r=>`<tr><td class="fw-semibold" style="color:var(--primary)">#${r.invoice_no}</td><td>${r.customer_name||'<span style="color:var(--text-muted)">—</span>'}</td><td class="text-end fw-semibold">${fmt(r.total)}</td><td class="text-end" style="color:var(--success)">${fmt(r.profit)}</td><td style="color:var(--text-muted);font-size:.78rem">${r.created_at.substring(0,16)}</td></tr>`).join('');foot.innerHTML=`<tr><td colspan="2" class="fw-bold">${T.total} (${data.length})</td><td class="text-end fw-bold">${fmt(salesTotals.total)}</td><td class="text-end fw-bold" style="color:var(--success)">${fmt(salesTotals.profit)}</td><td></td></tr>`;foot.style.display=''}

function renderCashTable(data){const tb=$('#cashTable tbody'),foot=$('#cashFoot');if(!data.length){tb.innerHTML=emptyRow(5);foot.style.display='none';return}tb.innerHTML=data.map(r=>{const isIn=r.type==='in';return`<tr><td><span class="badge-type ${isIn?'badge-in':'badge-out'}"><i class="bi bi-arrow${isIn?'-down':'-up'}-short"></i>${isIn?T.inL:T.outL}</span></td><td>${getCatBadge(r.cat||r.category)}</td><td class="small" style="max-width:150px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${r.description||'—'}</td><td class="text-end fw-semibold" style="color:${isIn?'var(--success)':'var(--danger)'}">${fmt(r.amount)}</td><td style="color:var(--text-muted);font-size:.78rem">${r.created_at.substring(0,16)}</td></tr>`}).join('');foot.innerHTML=`<tr><td colspan="4" class="fw-bold">${T.total}</td><td class="text-end fw-bold"><span style="color:var(--success)">${fmt(cashTotals.in)}</span> / <span style="color:var(--danger)">${fmt(cashTotals.out)}</span></td></tr>`;foot.style.display=''}

function renderExpenseBreakdown(s){const el=$('#expenseBreakdown');const items=[{l:T.catPurchase,v:s.purchases_paid,c:'#7c3aed'},{l:T.catSupplier,v:s.supplier_payments,c:'#0284c7'},{l:T.catExpense,v:s.operating_expenses,c:'#dc2626'},{l:T.catProfit,v:s.profit_withdrawals,c:'#d97706'},{l:T.catCorrection,v:s.corrections,c:'#94a3b8'},{l:T.catOther,v:s.other_expenses,c:'#64748b'}].filter(i=>i.v>0);if(!items.length){el.innerHTML=`<div class="empty-state"><i class="bi bi-check-circle"></i><p>${T.noExp}</p></div>`;return}const mx=Math.max(...items.map(i=>i.v));el.innerHTML=items.map(i=>`<div class="expense-item"><div class="expense-dot" style="background:${i.c}"></div><div class="expense-info"><div class="expense-name">${i.l}</div><div class="expense-bar"><div class="expense-fill" style="width:${mx>0?(i.v/mx)*100:0}%;background:${i.c}"></div></div></div><div class="expense-amount">${fmt(i.v)}</div></div>`).join('')}

function renderTopCustomers(data){const el=$('#topCustomersBody');if(!data.length){el.innerHTML=`<div class="empty-state"><i class="bi bi-people"></i><p>${T.noData}</p></div>`;return}el.innerHTML=data.map((r,i)=>{const rc=i===0?'rank-1':i===1?'rank-2':i===2?'rank-3':'rank-other';return`<div class="customer-item"><div class="customer-rank ${rc}">${i+1}</div><div class="customer-info"><div class="customer-name">${r.name}</div><div class="customer-invoices">${r.invoices} ${T.invoices}</div></div><div class="customer-total">${fmt(r.total)}</div></div>`}).join('')}

async function loadData(){
  const from=elFrom.value,to=elTo.value;
  exportCsv.href=`?action=export&from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`;
  summaryEl.style.opacity='.5';applyBtn.classList.add('loading');applyBtn.innerHTML='<i class="bi bi-arrow-repeat spin"></i> <?= $is_ar ? 'جاري...' : 'Loading...' ?>';
  try{
    const res=await fetch(`?action=data&from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`);const j=await res.json();
    if(!j.success){toast(j.error||T.errLoad,'error');return}
    const s=j.summary;
    statusBar.style.display='flex';$('#compText').textContent=j.comparison.prev_label;$('#updatedText').textContent=`${T.updated} ${T.at} ${j.generated_at}`;
    
    const netClr=s.net_profit>=0?'var(--success)':'var(--danger)';
    summaryEl.innerHTML=`
      <div class="row g-3 mb-3 fade-in">
        <div class="col-md-6 col-xl-3"><div class="stat-card c-primary"><div class="d-flex align-items-start gap-3"><div class="stat-icon ic-blue"><i class="bi bi-cart-check"></i></div><div><div class="stat-label">${T.sales}</div><div class="stat-value" data-target="${s.sales_sum}">0</div>${changeBadge(s.sales_change)}<div class="stat-extra">${s.invoices_count} ${T.invoices} · ${T.avgInv}: ${fmt(s.avg_invoice)}</div></div></div></div></div>
        <div class="col-md-6 col-xl-3"><div class="stat-card c-success"><div class="d-flex align-items-start gap-3"><div class="stat-icon ic-green"><i class="bi bi-graph-up-arrow"></i></div><div><div class="stat-label">${T.profit}</div><div class="stat-value" style="color:var(--success)" data-target="${s.profit_sum}">0</div>${changeBadge(s.profit_change)}<div class="stat-extra">${T.margin}: ${s.profit_margin}%</div></div></div></div></div>
        <div class="col-md-6 col-xl-3"><div class="stat-card c-warning"><div class="d-flex align-items-start gap-3"><div class="stat-icon ic-orange"><i class="bi bi-piggy-bank"></i></div><div><div class="stat-label">${T.netProfit}</div><div class="stat-value" style="color:${netClr}" data-target="${s.net_profit}">0</div><div class="stat-extra">${T.profit} − ${T.catExpense}</div></div></div></div></div>
        <div class="col-md-6 col-xl-3"><div class="stat-card dark-card c-dark"><div class="d-flex align-items-start gap-3"><div class="stat-icon" style="background:rgba(255,255,255,.1);color:#fff"><i class="bi bi-safe"></i></div><div><div class="stat-label" style="color:#94a3b8">${T.totalBal}</div><div class="stat-value" style="color:#fff" data-target="${s.total_balance}">0</div></div></div></div></div>
      </div>
      <div class="row g-3 mb-3 fade-in">
        <div class="col-md-3"><div class="mini-stat"><div><div class="mini-label">${T.cashIn}</div><div class="mini-value" style="color:var(--success)" data-target="${s.cash_in}">0</div></div><i class="bi bi-arrow-down-circle fs-2" style="color:var(--success);opacity:.5"></i></div></div>
        <div class="col-md-3"><div class="mini-stat"><div><div class="mini-label">${T.cashOut}</div><div class="mini-value" style="color:var(--danger)" data-target="${s.cash_out}">0</div></div><i class="bi bi-arrow-up-circle fs-2" style="color:var(--danger);opacity:.5"></i></div></div>
        <div class="col-md-3"><div class="mini-stat"><div><div class="mini-label">${T.cashBal}</div><div class="mini-value" data-target="${s.cash_balance}">0</div></div><i class="bi bi-wallet-fill fs-2" style="color:var(--primary);opacity:.5"></i></div></div>
        <div class="col-md-3"><div class="mini-stat"><div><div class="mini-label">${T.debts} / ${T.suppDebt}</div><div class="mini-value" style="color:var(--warning)">${fmt(s.debts_total)}</div><div class="mini-label">${T.suppDebt}: ${fmt(s.supplier_debt)}</div></div><i class="bi bi-people fs-2" style="color:var(--warning);opacity:.5"></i></div></div>
      </div>`;

    $$('[data-target]').forEach(el=>{const t=parseFloat(el.dataset.target);if(!isNaN(t))animateValue(el,0,t,800)});
    analyticsRow.style.display='';
    renderExpenseBreakdown(s);
    renderTopCustomers(j.analytics.top_customers);

    // Payment chart
    const pmD=j.analytics.payment_methods,pmL=pmD.map(r=>r.payment_method==='cash'?T.cash:r.payment_method==='card'?T.card:r.payment_method==='debt'?T.debt:r.payment_method),pmV=pmD.map(r=>r.total),pmC=['#4f46e5','#22c55e','#f59e0b','#ef4444','#0ea5e9','#8b5cf6'];
    if(paymentChart)paymentChart.destroy();
    paymentChart=new Chart(paymentChartCtx,{type:'doughnut',data:{labels:pmL,datasets:[{data:pmV,backgroundColor:pmC.slice(0,pmL.length),borderWidth:0,hoverOffset:8}]},options:{responsive:true,maintainAspectRatio:false,cutout:'65%',plugins:{legend:{position:'bottom',labels:{color:getComputedStyle(document.documentElement).getPropertyValue('--text-muted').trim(),padding:12,usePointStyle:true,pointStyle:'circle',font:{size:11,family:isRTL?'Cairo':'Inter'}}},tooltip:{backgroundColor:'rgba(15,23,42,.9)',cornerRadius:8,padding:10,callbacks:{label:ctx=>` ${ctx.label}: ${fmt(ctx.parsed)}`}}}}});

    currentSalesData=j.lists.sales;currentCashData=j.lists.cash_transactions;salesTotals=j.lists.sales_totals;cashTotals=j.lists.cash_totals;
    renderSalesTable(currentSalesData);renderCashTable(currentCashData);

    const tc=getComputedStyle(document.documentElement).getPropertyValue('--text-muted').trim()||'#94a3b8',gc=getComputedStyle(document.documentElement).getPropertyValue('--border-color').trim()||'#e2e8f0';
    Chart.defaults.font.family=isRTL?'Cairo, sans-serif':'Inter, sans-serif';

    if(salesChart)salesChart.destroy();
    salesChart=new Chart(salesChartCtx,{type:'line',data:{labels:j.charts.dates,datasets:[{label:T.chartSales,data:j.charts.sales_by_date,borderColor:'#4f46e5',backgroundColor:'rgba(79,70,229,.08)',fill:true,tension:.4,borderWidth:2.5,pointRadius:3,pointBackgroundColor:'#4f46e5',pointBorderColor:'#fff',pointBorderWidth:2,pointHoverRadius:6},{label:T.chartProfit,data:j.charts.profit_by_date,borderColor:'#22c55e',backgroundColor:'rgba(34,197,94,.08)',fill:true,tension:.4,borderWidth:2.5,pointRadius:3,pointBackgroundColor:'#22c55e',pointBorderColor:'#fff',pointBorderWidth:2,pointHoverRadius:6}]},options:{responsive:true,maintainAspectRatio:false,interaction:{mode:'index',intersect:false},plugins:{legend:{position:'top',align:'end',labels:{color:tc,usePointStyle:true,pointStyle:'circle',padding:16,font:{size:11,weight:'500'}}},tooltip:{backgroundColor:'rgba(15,23,42,.9)',titleColor:'#fff',bodyColor:'#cbd5e1',borderRadius:8,padding:10,callbacks:{label:ctx=>` ${ctx.dataset.label}: ${fmt(ctx.parsed.y)}`}}},scales:{x:{grid:{display:false},ticks:{color:tc,font:{size:10},maxRotation:45}},y:{grid:{color:gc,borderDash:[4,4]},ticks:{color:tc,font:{size:10},callback:v=>fmt(v)},beginAtZero:true}}}});

    if(cashChart)cashChart.destroy();
    cashChart=new Chart(cashChartCtx,{type:'bar',data:{labels:j.charts.dates,datasets:[{label:T.chartIn,data:j.charts.cash_in_by_date,backgroundColor:'rgba(34,197,94,.8)',hoverBackgroundColor:'#16a34a',borderRadius:5,borderSkipped:false,barPercentage:.7},{label:T.chartOut,data:j.charts.cash_out_by_date,backgroundColor:'rgba(239,68,68,.8)',hoverBackgroundColor:'#dc2626',borderRadius:5,borderSkipped:false,barPercentage:.7}]},options:{responsive:true,maintainAspectRatio:false,interaction:{mode:'index',intersect:false},plugins:{legend:{position:'top',align:'end',labels:{color:tc,usePointStyle:true,pointStyle:'rectRounded',padding:16,font:{size:11,weight:'500'}}},tooltip:{backgroundColor:'rgba(15,23,42,.9)',titleColor:'#fff',bodyColor:'#cbd5e1',borderRadius:8,padding:10,callbacks:{label:ctx=>` ${ctx.dataset.label}: ${fmt(ctx.parsed.y)}`}}},scales:{x:{grid:{display:false},ticks:{color:tc,font:{size:10},maxRotation:45}},y:{grid:{color:gc,borderDash:[4,4]},ticks:{color:tc,font:{size:10},callback:v=>fmt(v)},beginAtZero:true}}}});

    toast(T.dataUpdated,'success');
  }catch(e){console.error(e);toast(T.errLoad,'error');summaryEl.innerHTML=`<div class="alert alert-danger d-flex align-items-center fade-in" style="border-radius:var(--radius-md)"><i class="bi bi-exclamation-triangle-fill fs-5 me-2"></i><div><strong>Error!</strong><p class="mb-0 mt-1">${T.errLoad}</p></div></div>`}
  finally{summaryEl.style.opacity='1';applyBtn.classList.remove('loading');applyBtn.innerHTML='<i class="bi bi-search"></i> <?= $is_ar ? "عرض" : "Apply" ?><span class="shortcut-hint">Enter</span>'}
}
applyBtn.addEventListener('click',loadData);
[elFrom,elTo].forEach(i=>i.addEventListener('keydown',e=>{if(e.key==='Enter')loadData()}));
document.addEventListener('keydown',e=>{if(e.target.tagName==='INPUT')return;if(e.key==='p'&&(e.ctrlKey||e.metaKey)){e.preventDefault();window.print()}if(e.key==='e'&&(e.ctrlKey||e.metaKey)){e.preventDefault();exportCsv.click()}if(e.key==='r'&&!e.ctrlKey&&!e.metaKey){e.preventDefault();loadData()}});
loadData();
</script>
</body>
</html>