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

// Helpers
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; }

// Validate & Sanitize dates
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');
}

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

// Parse dates with validation
 $from = validateDate($_GET['from'] ?? '');
 $to = validateDate($_GET['to'] ?? '');

// Ensure from <= to
if ($from > $to) { $temp = $from; $from = $to; $to = $temp; }

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

// AJAX endpoints
 $action = $_GET['action'] ?? '';

// ============================================
// DATA ENDPOINT
// ============================================
if ($action === 'data') {
    try {
        // --- Previous Period for Comparison ---
        $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 period 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 period 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);

        // Calculate percentages
        $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;

        // Cash in/out current
        $stmt = $pdo->prepare("SELECT `type`, COALESCE(SUM(amount),0) AS sum_amount
                               FROM cash_transactions WHERE created_at BETWEEN ? AND ? GROUP BY `type`");
        $stmt->execute([$from_dt, $to_dt]);
        $cashRows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $cash_in = 0; $cash_out = 0;
        foreach ($cashRows as $r) {
            if ($r['type'] === 'in') $cash_in += (float)$r['sum_amount'];
            else $cash_out += (float)$r['sum_amount'];
        }

        // Cash in/out previous
        $stmt = $pdo->prepare("SELECT `type`, COALESCE(SUM(amount),0) AS sum_amount
                               FROM cash_transactions WHERE created_at BETWEEN ? AND ? GROUP BY `type`");
        $stmt->execute([$prev_from_dt, $prev_to_dt]);
        $prevCashRows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $prev_cash_in = 0; $prev_cash_out = 0;
        foreach ($prevCashRows as $r) {
            if ($r['type'] === 'in') $prev_cash_in += (float)$r['sum_amount'];
            else $prev_cash_out += (float)$r['sum_amount'];
        }
        $cash_in_change = $prev_cash_in > 0 ? (($cash_in - $prev_cash_in) / $prev_cash_in) * 100 : 0;
        $cash_out_change = $prev_cash_out > 0 ? (($cash_out - $prev_cash_out) / $prev_cash_out) * 100 : 0;

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

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

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

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

        // 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 transactions list
        $stmt = $pdo->prepare("SELECT * 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);

        // Chart data - daily aggregates
        $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;
        }

        json_out([
            'success' => true,
            'from' => $from,
            'to' => $to,
            'period_label' => $is_ar 
                ? "من $from إلى $to" 
                : "$from → $to",
            '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),
                'cash_in' => $cash_in,
                'cash_out' => $cash_out,
                'cash_in_change' => round($cash_in_change, 1),
                'cash_out_change' => round($cash_out_change, 1),
                'cash_balance' => $cash_balance,
                'debts_total' => $debts_total,
                'inventory_value' => $inventory_value,
                'total_balance' => $total_balance
            ],
            'lists' => ['sales' => $sales_list, 'cash_transactions' => $cash_list],
            '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 ? 'تقرير مالي' : 'Financial Report']);
        fputcsv($out, [$is_ar ? 'من تاريخ' : 'From', $from, $is_ar ? 'إلى تاريخ' : 'To', $to]);
        fputcsv($out, [$is_ar ? 'تاريخ التصدير' : 'Export Date', date('Y-m-d H:i:s')]);
        fputcsv($out, []);

        $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([$from_dt, $to_dt]); $r = $stmt->fetch(PDO::FETCH_ASSOC);

        $stmt = $pdo->prepare("SELECT `type`, COALESCE(SUM(amount),0) AS amt FROM cash_transactions WHERE created_at BETWEEN ? AND ? GROUP BY `type`");
        $stmt->execute([$from_dt, $to_dt]);
        $in=0; $outv=0;
        foreach($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
            if($row['type']=='in') $in=(float)$row['amt']; else $outv=(float)$row['amt'];
        }

        $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_csv = (float)$stmt->fetchColumn();
        $stmt = $pdo->query("SELECT COALESCE(SUM(CASE WHEN balance>0 THEN balance ELSE 0 END),0) FROM customers");
        $debts_total_csv = (float)$stmt->fetchColumn();
        $stmt = $pdo->query("SELECT COALESCE(SUM(COALESCE(stock,0) * COALESCE(cost,0)),0) FROM products");
        $inventory_value_csv = (float)$stmt->fetchColumn();

        fputcsv($out, [$is_ar ? 'ملخص' : 'Summary']);
        fputcsv($out, [$is_ar ? 'إجمالي المبيعات' : 'Sales Total', $r['sales_sum']]);
        fputcsv($out, [$is_ar ? 'صافي الأرباح' : 'Net Profit', $r['profit_sum']]);
        fputcsv($out, [$is_ar ? 'وارد نقدي' : 'Cash In', $in]);
        fputcsv($out, [$is_ar ? 'صادر نقدي' : 'Cash Out', $outv]);
        fputcsv($out, [$is_ar ? 'رصيد الصندوق' : 'Cash Balance', $cash_balance_csv]);
        fputcsv($out, [$is_ar ? 'ديون العملاء' : 'Customer Debts', $debts_total_csv]);
        fputcsv($out, [$is_ar ? 'قيمة المخزون' : 'Inventory Value', $inventory_value_csv]);
        fputcsv($out, [$is_ar ? 'الرصيد العام' : 'Total Balance', $cash_balance_csv + $debts_total_csv + $inventory_value_csv]);
        fputcsv($out, []);

        fputcsv($out, [$is_ar ? 'تفاصيل المبيعات' : 'Sales Details']);
        fputcsv($out, [$is_ar ? 'فاتورة' : 'Invoice', $is_ar ? 'العميل' : 'Customer', $is_ar ? 'المجموع' : 'Total', $is_ar ? 'المدفوع' : 'Paid', $is_ar ? 'طريقة الدفع' : 'Payment', $is_ar ? 'الربح' : 'Profit', $is_ar ? 'التاريخ' : 'Date']);
        $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");
        $stmt->execute([$from_dt, $to_dt]);
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            fputcsv($out, [$row['invoice_no'], $row['customer_name'] ?? '', $row['total'], $row['paid'], $row['payment_method'], $row['profit'], $row['created_at']]);
        }
        fputcsv($out, []);

        fputcsv($out, [$is_ar ? 'حركة الصندوق' : 'Cash Transactions']);
        fputcsv($out, [$is_ar ? 'النوع' : 'Type', $is_ar ? 'المبلغ' : 'Amount', $is_ar ? 'الوصف' : 'Description', $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['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 Overview' ?></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>
    /* ============================================
       CSS VARIABLES & BASE
       ============================================ */
    :root {
      --font-ar: 'Cairo', sans-serif;
      --font-en: 'Inter', sans-serif;
      --bg-body: #f0f2f5;
      --card-bg: #ffffff;
      --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;
      --text-main: #0f172a;
      --text-secondary: #475569;
      --text-muted: #94a3b8;
      --border-color: #e2e8f0;
      --shadow-sm: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
      --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
      --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
      --radius-sm: 8px;
      --radius-md: 12px;
      --radius-lg: 16px;
      --transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
    }

    /* Dark Mode Variables */
    [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 0 rgba(0, 0, 0, 0.3);
      --shadow-md: 0 4px 6px -1px rgba(0, 0, 0, 0.4);
      --shadow-lg: 0 10px 15px -3px rgba(0, 0, 0, 0.5);
      --primary-light: #1e1b4b;
      --success-light: #052e16;
      --danger-light: #450a0a;
      --warning-light: #451a03;
      --info-light: #082f49;
    }

    /* ============================================
       BASE STYLES
       ============================================ */
    * { box-sizing: border-box; }
    
    body {
      background-color: var(--bg-body);
      font-family: var(--font-en);
      color: var(--text-main);
      padding-bottom: 60px;
      transition: background-color 0.3s, color 0.3s;
      min-height: 100vh;
    }

    [dir="rtl"] body { font-family: var(--font-ar); }

    ::selection {
      background: var(--primary);
      color: white;
    }

    ::-webkit-scrollbar { width: 6px; height: 6px; }
    ::-webkit-scrollbar-track { background: transparent; }
    ::-webkit-scrollbar-thumb { background: var(--text-muted); border-radius: 3px; }
    ::-webkit-scrollbar-thumb:hover { background: var(--text-secondary); }

    /* ============================================
       NAVBAR
       ============================================ */
    .navbar {
      background: var(--card-bg) !important;
      box-shadow: var(--shadow-sm);
      padding: 0.75rem 1.25rem;
      position: sticky;
      top: 0;
      z-index: 1000;
      transition: var(--transition);
    }

    .navbar .brand-icon {
      width: 40px;
      height: 40px;
      background: linear-gradient(135deg, var(--primary), #7c3aed);
      border-radius: var(--radius-sm);
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-size: 1.2rem;
    }

    .nav-actions .btn {
      border-radius: var(--radius-sm);
      font-weight: 500;
      padding: 0.5rem 1rem;
      transition: var(--transition);
      border: 1px solid var(--border-color);
      color: var(--text-secondary);
      background: var(--card-bg);
    }

    .nav-actions .btn:hover {
      border-color: var(--primary);
      color: var(--primary);
      transform: translateY(-1px);
    }

    .theme-toggle {
      width: 38px;
      height: 38px;
      padding: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: var(--radius-sm) !important;
      font-size: 1.1rem;
    }

    /* ============================================
       MAIN CONTAINER
       ============================================ */
    .main-container {
      max-width: 1440px;
      margin: 1.5rem auto;
      padding: 0 1.5rem;
    }

    /* ============================================
       FILTER BAR
       ============================================ */
    .filter-bar {
      background: var(--card-bg);
      padding: 1.25rem 1.5rem;
      border-radius: var(--radius-lg);
      border: 1px solid var(--border-color);
      margin-bottom: 1.75rem;
      box-shadow: var(--shadow-sm);
      transition: var(--transition);
    }

    .quick-filters .btn {
      padding: 0.4rem 0.85rem;
      font-size: 0.8rem;
      font-weight: 500;
      border-radius: 20px;
      border: 1px solid var(--border-color);
      color: var(--text-secondary);
      background: transparent;
      transition: var(--transition);
      white-space: nowrap;
    }

    .quick-filters .btn:hover,
    .quick-filters .btn.active {
      background: var(--primary);
      color: white;
      border-color: var(--primary);
      transform: translateY(-1px);
    }

    .form-control, .form-select {
      border: 1px solid var(--border-color);
      border-radius: var(--radius-sm);
      padding: 0.5rem 0.75rem;
      font-size: 0.9rem;
      color: var(--text-main);
      background: var(--card-bg);
      transition: var(--transition);
    }

    .form-control:focus, .form-select:focus {
      border-color: var(--primary);
      box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.15);
    }

    .action-btns .btn {
      border-radius: var(--radius-sm);
      font-weight: 600;
      padding: 0.5rem 1.25rem;
      transition: var(--transition);
      font-size: 0.875rem;
    }

    .action-btns .btn-primary {
      background: linear-gradient(135deg, var(--primary), #6366f1);
      border: none;
      box-shadow: 0 2px 4px rgba(79, 70, 229, 0.3);
    }

    .action-btns .btn-primary:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(79, 70, 229, 0.4);
    }

    .action-btns .btn-outline-success {
      border: 1px solid var(--success);
      color: var(--success);
    }

    .action-btns .btn-outline-success:hover {
      background: var(--success);
      color: white;
      transform: translateY(-2px);
    }

    .action-btns .btn-outline-info {
      border: 1px solid var(--info);
      color: var(--info);
    }

    .action-btns .btn-outline-info:hover {
      background: var(--info);
      color: white;
      transform: translateY(-2px);
    }

    /* ============================================
       STAT CARDS
       ============================================ */
    .stat-card {
      background: var(--card-bg);
      border: 1px solid var(--border-color);
      border-radius: var(--radius-md);
      padding: 1.5rem;
      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.primary::before { background: linear-gradient(90deg, var(--primary), #7c3aed); }
    .stat-card.success::before { background: linear-gradient(90deg, var(--success), #22c55e); }
    .stat-card.info::before { background: linear-gradient(90deg, var(--info), #0ea5e9); }
    .stat-card.dark::before { background: linear-gradient(90deg, #475569, #64748b); }

    .stat-icon {
      width: 52px;
      height: 52px;
      border-radius: var(--radius-sm);
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 1.4rem;
      flex-shrink: 0;
    }

    .icon-blue { background: var(--primary-light); color: var(--primary); }
    .icon-green { background: var(--success-light); color: var(--success); }
    .icon-purple { background: var(--primary-light); color: #7c3aed; }
    .icon-info { background: var(--info-light); color: var(--info); }

    .stat-label {
      font-size: 0.8rem;
      color: var(--text-muted);
      font-weight: 500;
      margin-bottom: 4px;
      text-transform: uppercase;
      letter-spacing: 0.025em;
    }

    .stat-value {
      font-size: 1.6rem;
      font-weight: 700;
      color: var(--text-main);
      line-height: 1.2;
    }

    .change-badge {
      display: inline-flex;
      align-items: center;
      gap: 2px;
      padding: 2px 8px;
      border-radius: 20px;
      font-size: 0.72rem;
      font-weight: 600;
      margin-top: 6px;
    }

    .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); }

    /* Dark special card */
    .stat-card.dark-card {
      background: linear-gradient(135deg, #1e293b, #334155);
      border-color: transparent;
    }

    [data-theme="dark"] .stat-card.dark-card {
      background: linear-gradient(135deg, #0f172a, #1e293b);
    }

    .stat-card.dark-card .stat-label { color: #94a3b8; }
    .stat-card.dark-card .stat-value { color: #ffffff; }

    /* ============================================
       MINI STAT CARDS (ROW 2)
       ============================================ */
    .mini-stat {
      background: var(--card-bg);
      border: 1px solid var(--border-color);
      border-radius: var(--radius-md);
      padding: 1rem 1.25rem;
      transition: var(--transition);
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .mini-stat:hover {
      transform: translateY(-2px);
      box-shadow: var(--shadow-md);
    }

    .mini-stat-label {
      font-size: 0.75rem;
      color: var(--text-muted);
      font-weight: 500;
      margin-bottom: 2px;
    }

    .mini-stat-value {
      font-size: 1.2rem;
      font-weight: 700;
    }

    /* ============================================
       CHARTS
       ============================================ */
    .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: 1.25rem 1.5rem;
      border-bottom: 1px solid var(--border-color);
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .chart-title {
      font-weight: 600;
      font-size: 0.95rem;
      margin: 0;
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .chart-body {
      padding: 1.25rem 1.5rem;
      position: relative;
      height: 320px;
    }

    /* ============================================
       TABLES
       ============================================ */
    .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: 1rem 1.25rem;
      border-bottom: 1px solid var(--border-color);
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-wrap: wrap;
      gap: 0.75rem;
    }

    .table-title {
      font-weight: 600;
      font-size: 0.95rem;
      margin: 0;
    }

    .table-search {
      position: relative;
    }

    .table-search input {
      padding-left: 2.5rem;
      padding-right: 0.75rem;
      border: 1px solid var(--border-color);
      border-radius: var(--radius-sm);
      font-size: 0.85rem;
      background: var(--card-bg);
      color: var(--text-main);
      width: 200px;
      transition: var(--transition);
    }

    [dir="rtl"] .table-search input {
      padding-left: 0.75rem;
      padding-right: 2.5rem;
    }

    .table-search input:focus {
      border-color: var(--primary);
      box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.15);
      outline: none;
    }

    .table-search i {
      position: absolute;
      left: 0.75rem;
      top: 50%;
      transform: translateY(-50%);
      color: var(--text-muted);
      font-size: 0.9rem;
    }

    [dir="rtl"] .table-search i {
      left: auto;
      right: 0.75rem;
    }

    .table-responsive {
      max-height: 420px;
      overflow-y: auto;
      flex: 1;
    }

    .table-custom {
      margin: 0;
      font-size: 0.875rem;
    }

    .table-custom thead th {
      background: var(--bg-body);
      color: var(--text-muted);
      font-weight: 600;
      font-size: 0.75rem;
      text-transform: uppercase;
      letter-spacing: 0.05em;
      border-bottom: 2px solid var(--border-color);
      padding: 0.75rem 1rem;
      position: sticky;
      top: 0;
      z-index: 2;
    }

    .table-custom tbody td {
      padding: 0.75rem 1rem;
      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 tbody tr:last-child td { border-bottom: none; }

    .badge-type {
      padding: 0.35em 0.75em;
      border-radius: 6px;
      font-weight: 600;
      font-size: 0.72rem;
      display: inline-flex;
      align-items: center;
      gap: 4px;
    }

    .badge-in { background: var(--success-light); color: var(--success); }
    .badge-out { background: var(--danger-light); color: var(--danger); }

    /* Empty State */
    .empty-state {
      text-align: center;
      padding: 3rem 1rem;
      color: var(--text-muted);
    }

    .empty-state i {
      font-size: 3rem;
      opacity: 0.3;
      margin-bottom: 1rem;
      display: block;
    }

    .empty-state p {
      margin: 0;
      font-size: 0.9rem;
    }

    /* ============================================
       SKELETON LOADING
       ============================================ */
    .skeleton {
      background: linear-gradient(90deg, var(--border-color) 25%, transparent 50%, var(--border-color) 75%);
      background-size: 200% 100%;
      animation: skeleton-loading 1.5s infinite;
      border-radius: var(--radius-sm);
    }

    @keyframes skeleton-loading {
      0% { background-position: 200% 0; }
      100% { background-position: -200% 0; }
    }

    .skeleton-card {
      background: var(--card-bg);
      border: 1px solid var(--border-color);
      border-radius: var(--radius-md);
      padding: 1.5rem;
    }

    /* ============================================
       TOAST NOTIFICATION
       ============================================ */
    .toast-container {
      position: fixed;
      top: 80px;
      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: 0.85rem 1.25rem;
      box-shadow: var(--shadow-lg);
      display: flex;
      align-items: center;
      gap: 0.75rem;
      margin-bottom: 0.5rem;
      min-width: 280px;
      animation: toast-in 0.3s ease-out;
      color: var(--text-main);
    }

    .custom-toast.toast-out {
      animation: toast-out 0.3s ease-in forwards;
    }

    @keyframes toast-in {
      from { opacity: 0; transform: translateX(100%); }
      to { opacity: 1; transform: translateX(0); }
    }

    [dir="rtl"] @keyframes toast-in {
      from { opacity: 0; transform: translateX(-100%); }
      to { opacity: 1; transform: translateX(0); }
    }

    @keyframes toast-out {
      from { opacity: 1; transform: translateX(0); }
      to { opacity: 0; transform: translateX(100%); }
    }

    /* ============================================
       COMPARISON BADGE
       ============================================ */
    .comparison-label {
      display: inline-flex;
      align-items: center;
      gap: 6px;
      background: var(--bg-body);
      padding: 0.4rem 0.85rem;
      border-radius: 20px;
      font-size: 0.75rem;
      color: var(--text-muted);
      border: 1px solid var(--border-color);
    }

    /* ============================================
       FOOTER
       ============================================ */
    .footer {
      text-align: center;
      padding: 2rem 0;
      color: var(--text-muted);
      font-size: 0.8rem;
    }

    .footer a {
      color: var(--text-secondary);
      text-decoration: none;
    }

    .footer a:hover { color: var(--primary); }

    /* ============================================
       PRINT STYLES
       ============================================ */
    @media print {
      .navbar, .filter-bar, .nav-actions, .action-btns, .table-search, .no-print { display: none !important; }
      body { background: white; }
      .stat-card, .chart-card, .table-card { box-shadow: none; border: 1px solid #ddd; }
      .main-container { max-width: 100%; }
    }

    /* ============================================
       RESPONSIVE
       ============================================ */
    @media (max-width: 768px) {
      .main-container { padding: 0 1rem; margin: 1rem auto; }
      .filter-bar { padding: 1rem; }
      .stat-value { font-size: 1.3rem; }
      .chart-body { height: 250px; }
      .table-search input { width: 150px; }
      .quick-filters { overflow-x: auto; flex-wrap: nowrap; }
    }

    @media (max-width: 576px) {
      .stat-value { font-size: 1.1rem; }
      .stat-icon { width: 42px; height: 42px; font-size: 1.1rem; }
    }

    /* ============================================
       ANIMATIONS
       ============================================ */
    .fade-in {
      animation: fadeIn 0.4s ease-out;
    }

    @keyframes fadeIn {
      from { opacity: 0; transform: translateY(10px); }
      to { opacity: 1; transform: translateY(0); }
    }

    .count-up {
      display: inline-block;
    }
  </style>
</head>
<body class="<?= $is_ar ? 'rtl' : 'ltr' ?>">

  <!-- Toast Container -->
  <div class="toast-container" id="toastContainer"></div>

  <!-- Navbar -->
  <nav class="navbar">
    <div class="container-fluid">
      <div class="d-flex align-items-center gap-3">
        <div class="brand-icon">
          <i class="bi bi-wallet2"></i>
        </div>
        <div>
          <span class="fw-bold fs-5 d-block" style="line-height:1.2"><?= $is_ar ? 'التقرير المالي' : 'Financial Report' ?></span>
          <small class="text-muted" style="font-size:0.75rem"><?= $is_ar ? 'نظرة شاملة على الأداء المالي' : 'Complete financial performance overview' ?></small>
        </div>
      </div>
      <div class="nav-actions d-flex gap-2">
        <a href="index.php" class="btn d-flex align-items-center gap-2 no-print">
          <i class="bi bi-grid-1x2"></i>
          <span class="d-none d-sm-inline"><?= $is_ar ? 'الرئيسية' : 'Dashboard' ?></span>
        </a>
        <button class="btn theme-toggle no-print" id="themeToggle" title="<?= $is_ar ? 'تبديل الوضع الليلي' : 'Toggle dark mode' ?>">
          <i class="bi bi-moon-stars"></i>
        </button>
        <a href="?lang=<?= $lang==='ar' ? 'en' : 'ar' ?>&from=<?=esc($from)?>&to=<?=esc($to)?>" class="btn no-print">
          <span class="fw-bold"><?= $is_ar ? 'EN' : 'عربي' ?></span>
        </a>
      </div>
    </div>
  </nav>

  <!-- Main Content -->
  <div class="main-container">
    
    <!-- Filter Bar -->
    <div class="filter-bar fade-in no-print">
      <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-calendar-range me-1"></i>
            <?= $is_ar ? 'فلاتر سريعة' : 'Quick Filters' ?>
          </label>
          <div class="quick-filters d-flex gap-2 flex-wrap">
            <button class="btn active" data-range="today"><?= $is_ar ? 'اليوم' : 'Today' ?></button>
            <button class="btn" data-range="yesterday"><?= $is_ar ? 'أمس' : 'Yesterday' ?></button>
            <button class="btn" data-range="week"><?= $is_ar ? 'هذا الأسبوع' : 'This Week' ?></button>
            <button class="btn" data-range="month"><?= $is_ar ? 'هذا الشهر' : 'This Month' ?></button>
            <button class="btn" data-range="lastmonth"><?= $is_ar ? 'الشهر الماضي' : 'Last Month' ?></button>
            <button class="btn" data-range="year"><?= $is_ar ? 'هذا العام' : 'This Year' ?></button>
          </div>
        </div>
        <div class="col-lg-5">
          <label class="form-label small fw-semibold text-muted mb-2">
            <i class="bi bi-funnel me-1"></i>
            <?= $is_ar ? 'نطاق مخصص' : 'Custom Range' ?>
          </label>
          <div class="d-flex gap-2">
            <input type="date" id="fromDate" class="form-control" value="<?= esc($from) ?>">
            <span class="align-self-center text-muted">→</span>
            <input type="date" id="toDate" class="form-control" value="<?= esc($to) ?>">
          </div>
        </div>
        <div class="col-lg-3">
          <div class="action-btns d-flex gap-2">
            <button type="button" id="applyBtn" class="btn btn-primary flex-grow-1">
              <i class="bi bi-search me-1"></i> <?= $is_ar ? 'عرض' : 'Apply' ?>
            </button>
            <button type="button" id="printBtn" class="btn btn-outline-info" title="<?= $is_ar ? 'طباعة' : 'Print' ?>">
              <i class="bi bi-printer"></i>
            </button>
            <a id="exportCsv" href="#" class="btn btn-outline-success" title="<?= $is_ar ? 'تصدير CSV' : 'Export CSV' ?>">
              <i class="bi bi-file-earmark-spreadsheet"></i>
            </a>
          </div>
        </div>
      </div>
    </div>

    <!-- Comparison Label -->
    <div class="mb-3" id="comparisonArea" style="display:none;">
      <span class="comparison-label" id="comparisonLabel">
        <i class="bi bi-arrow-left-right"></i>
        <span id="comparisonText"></span>
      </span>
    </div>

    <!-- Summary Cards -->
    <div id="summary">
      <!-- Skeleton Loading -->
      <div class="row g-3 mb-4">
        <div class="col-md-6 col-xl-3"><div class="skeleton-card"><div class="skeleton" style="height:20px;width:60%;margin-bottom:10px"></div><div class="skeleton" style="height:32px;width:80%"></div></div></div>
        <div class="col-md-6 col-xl-3"><div class="skeleton-card"><div class="skeleton" style="height:20px;width:60%;margin-bottom:10px"></div><div class="skeleton" style="height:32px;width:80%"></div></div></div>
        <div class="col-md-6 col-xl-3"><div class="skeleton-card"><div class="skeleton" style="height:20px;width:60%;margin-bottom:10px"></div><div class="skeleton" style="height:32px;width:80%"></div></div></div>
        <div class="col-md-6 col-xl-3"><div class="skeleton-card"><div class="skeleton" style="height:20px;width:60%;margin-bottom:10px"></div><div class="skeleton" style="height:32px;width:80%"></div></div></div>
      </div>
      <div class="row g-3 mb-4">
        <div class="col-md-3"><div class="skeleton-card"><div class="skeleton" style="height:16px;width:50%;margin-bottom:8px"></div><div class="skeleton" style="height:24px;width:70%"></div></div></div>
        <div class="col-md-3"><div class="skeleton-card"><div class="skeleton" style="height:16px;width:50%;margin-bottom:8px"></div><div class="skeleton" style="height:24px;width:70%"></div></div></div>
        <div class="col-md-3"><div class="skeleton-card"><div class="skeleton" style="height:16px;width:50%;margin-bottom:8px"></div><div class="skeleton" style="height:24px;width:70%"></div></div></div>
        <div class="col-md-3"><div class="skeleton-card"><div class="skeleton" style="height:16px;width:50%;margin-bottom:8px"></div><div class="skeleton" style="height:24px;width:70%"></div></div></div>
      </div>
    </div>

    <!-- Charts -->
    <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>

    <!-- Tables -->
    <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 Details' ?>
            </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>
            </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 Transactions' ?>
            </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 ? 'الوصف' : 'Description' ?></th>
                  <th class="text-end"><?= $is_ar ? 'المبلغ' : 'Amount' ?></th>
                  <th><?= $is_ar ? 'التاريخ' : 'Date' ?></th>
                </tr>
              </thead>
              <tbody></tbody>
            </table>
          </div>
        </div>
      </div>
    </div>

    <!-- Footer -->
    <div class="footer">
      <p class="mb-1">&copy; <?= date('Y') ?> BOB & POS System</p>
      <small><?= $is_ar ? 'تقرير مالي متكامل' : 'Comprehensive Financial Report' ?></small>
    </div>
  </div>

<script>
// ============================================
// CONFIGURATION
// ============================================
const lang = "<?= $is_ar ? 'ar' : 'en' ?>";
const isRTL = lang === 'ar';

const texts = {
  sales: lang === 'ar' ? 'إجمالي المبيعات' : 'Total Sales',
  profit: lang === 'ar' ? 'صافي الأرباح' : 'Net Profit',
  cashBalance: lang === 'ar' ? 'رصيد الصندوق الحالي' : 'Current Cash Balance',
  totalBalance: lang === 'ar' ? 'الرصيد العام (أصول)' : 'Total Balance (Assets)',
  cashIn: lang === 'ar' ? 'وارد نقدي' : 'Cash In',
  cashOut: lang === 'ar' ? 'صادر نقدي' : 'Cash Out',
  debts: lang === 'ar' ? 'ديون العملاء' : 'Cust. Debts',
  inventory: lang === 'ar' ? 'قيمة المخزون' : 'Inventory Val',
  invoices: lang === 'ar' ? 'فاتورة' : 'Invoice',
  vsPrev: lang === 'ar' ? 'مقارنة بالفترة السابقة' : 'vs previous period',
  noData: lang === 'ar' ? 'لا توجد بيانات' : 'No data found',
  loading: lang === 'ar' ? 'جاري التحميل...' : 'Loading...',
  error: lang === 'ar' ? 'حدث خطأ أثناء التحميل' : 'Error loading data',
  exportSuccess: lang === 'ar' ? 'تم تحميل التقرير بنجاح' : 'Report downloaded successfully',
  inLabel: lang === 'ar' ? 'قبض' : 'In',
  outLabel: lang === 'ar' ? 'صرف' : 'Out',
  chartSales: lang === 'ar' ? 'المبيعات' : 'Sales',
  chartProfit: lang === 'ar' ? 'الأرباح' : 'Profit',
  chartIn: lang === 'ar' ? 'وارد' : 'Cash In',
  chartOut: lang === 'ar' ? 'صادر' : 'Cash Out'
};

// ============================================
// DOM ELEMENTS
// ============================================
const elFrom = document.getElementById('fromDate');
const elTo = document.getElementById('toDate');
const applyBtn = document.getElementById('applyBtn');
const printBtn = document.getElementById('printBtn');
const exportCsv = document.getElementById('exportCsv');
const summaryEl = document.getElementById('summary');
const comparisonArea = document.getElementById('comparisonArea');
const comparisonText = document.getElementById('comparisonText');
const themeToggle = document.getElementById('themeToggle');
const salesChartCtx = document.getElementById('salesChart').getContext('2d');
const cashChartCtx = document.getElementById('cashChart').getContext('2d');

let salesChart = null;
let cashChart = null;
let currentSalesData = [];
let currentCashData = [];

// ============================================
// HELPERS
// ============================================
const formatMoney = (amount) => {
    return new Intl.NumberFormat(isRTL ? 'ar-SA' : 'en-US', { 
        style: 'decimal', 
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    }).format(amount);
};

const getChangeBadge = (change) => {
    if (change === 0) return `<span class="change-badge neutral"><i class="bi bi-dash"></i> 0%</span>`;
    const isUp = change > 0;
    const icon = isUp ? 'bi-arrow-up-short' : 'bi-arrow-down-short';
    const cls = isUp ? 'up' : 'down';
    return `<span class="change-badge ${cls}"><i class="bi ${icon}"></i> ${Math.abs(change)}%</span>`;
};

const showToast = (message, type = 'info') => {
    const container = document.getElementById('toastContainer');
    const icons = { success: 'bi-check-circle-fill text-success', error: 'bi-x-circle-fill text-danger', info: 'bi-info-circle-fill text-info' };
    const toast = document.createElement('div');
    toast.className = 'custom-toast';
    toast.innerHTML = `<i class="bi ${icons[type]} fs-5"></i><span style="font-size:0.875rem">${message}</span>`;
    container.appendChild(toast);
    setTimeout(() => {
        toast.classList.add('toast-out');
        setTimeout(() => toast.remove(), 300);
    }, 3000);
};

const debounce = (func, wait) => {
    let timeout;
    return function executedFunction(...args) {
        const later = () => { clearTimeout(timeout); func(...args); };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
};

const getEmptyState = (message) => `
    <tr>
        <td colspan="5" class="empty-state">
            <i class="bi bi-inbox"></i>
            <p>${message}</p>
        </td>
    </tr>
`;

// ============================================
// DATE HELPERS
// ============================================
const getToday = () => {
    const d = new Date();
    return d.toISOString().split('T')[0];
};

const getDateRange = (range) => {
    const today = new Date();
    const from = new Date();
    
    switch(range) {
        case 'today':
            return [getToday(), getToday()];
        case 'yesterday':
            const yesterday = new Date(today);
            yesterday.setDate(yesterday.getDate() - 1);
            return [yesterday.toISOString().split('T')[0], yesterday.toISOString().split('T')[0]];
        case 'week':
            const dayOfWeek = today.getDay();
            const startOfWeek = new Date(today);
            startOfWeek.setDate(today.getDate() - (dayOfWeek === 0 ? 6 : dayOfWeek - 1));
            return [startOfWeek.toISOString().split('T')[0], getToday()];
        case 'month':
            return [`${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-01`, getToday()];
        case 'lastmonth':
            const lastMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1);
            const lastMonthEnd = new Date(today.getFullYear(), today.getMonth(), 0);
            return [lastMonth.toISOString().split('T')[0], lastMonthEnd.toISOString().split('T')[0]];
        case 'year':
            return [`${today.getFullYear()}-01-01`, getToday()];
        default:
            return [getToday(), getToday()];
    }
};

// ============================================
// THEME TOGGLE
// ============================================
const savedTheme = localStorage.getItem('theme');
if (savedTheme) {
    document.documentElement.setAttribute('data-theme', savedTheme);
    updateThemeIcon(savedTheme);
}

function updateThemeIcon(theme) {
    const icon = themeToggle.querySelector('i');
    icon.className = theme === 'dark' ? 'bi bi-sun' : 'bi bi-moon-stars';
}

themeToggle.addEventListener('click', () => {
    const current = document.documentElement.getAttribute('data-theme');
    const next = current === 'dark' ? 'light' : 'dark';
    document.documentElement.setAttribute('data-theme', next);
    localStorage.setItem('theme', next);
    updateThemeIcon(next);
    
    // Update charts
    if (salesChart) {
        salesChart.options.scales.x.ticks.color = getComputedStyle(document.documentElement).getPropertyValue('--text-muted').trim();
        salesChart.options.scales.y.ticks.color = getComputedStyle(document.documentElement).getPropertyValue('--text-muted').trim();
        salesChart.options.plugins.legend.labels.color = getComputedStyle(document.documentElement).getPropertyValue('--text-secondary').trim();
        salesChart.update();
    }
    if (cashChart) {
        cashChart.options.scales.x.ticks.color = getComputedStyle(document.documentElement).getPropertyValue('--text-muted').trim();
        cashChart.options.scales.y.ticks.color = getComputedStyle(document.documentElement).getPropertyValue('--text-muted').trim();
        cashChart.options.plugins.legend.labels.color = getComputedStyle(document.documentElement).getPropertyValue('--text-secondary').trim();
        cashChart.update();
    }
});

// ============================================
// QUICK FILTERS
// ============================================
document.querySelectorAll('.quick-filters .btn').forEach(btn => {
    btn.addEventListener('click', () => {
        document.querySelectorAll('.quick-filters .btn').forEach(b => b.classList.remove('active'));
        btn.classList.add('active');
        const range = btn.dataset.range;
        const [from, to] = getDateRange(range);
        elFrom.value = from;
        elTo.value = to;
        loadData();
    });
});

// ============================================
// PRINT
// ============================================
printBtn.addEventListener('click', () => {
    window.print();
});

// ============================================
// TABLE SEARCH
// ============================================
const salesSearchInput = document.getElementById('salesSearch');
const cashSearchInput = document.getElementById('cashSearch');

const filterTable = (input, data, tableId, renderFn) => {
    const query = input.value.toLowerCase();
    const filtered = data.filter(row => {
        return Object.values(row).some(val => 
            String(val).toLowerCase().includes(query)
        );
    });
    renderFn(filtered);
};

salesSearchInput.addEventListener('input', debounce((e) => {
    filterTable(e.target, currentSalesData, 'salesTable', renderSalesTable);
}, 300));

cashSearchInput.addEventListener('input', debounce((e) => {
    filterTable(e.target, currentCashData, 'cashTable', renderCashTable);
}, 300));

// ============================================
// RENDER FUNCTIONS
// ============================================
function renderSalesTable(data) {
    const tbody = document.querySelector('#salesTable tbody');
    if (data.length === 0) {
        tbody.innerHTML = getEmptyState(texts.noData);
        return;
    }
    tbody.innerHTML = data.map(row => `
        <tr>
            <td class="fw-semibold" style="color:var(--primary)">#${row.invoice_no}</td>
            <td>${row.customer_name || '<span style="color:var(--text-muted)">—</span>'}</td>
            <td class="text-end fw-semibold">${formatMoney(row.total)}</td>
            <td class="text-end" style="color:var(--success)">${formatMoney(row.profit)}</td>
            <td style="color:var(--text-muted);font-size:0.8rem">${row.created_at.substring(0, 16)}</td>
        </tr>
    `).join('');
}

function renderCashTable(data) {
    const tbody = document.querySelector('#cashTable tbody');
    if (data.length === 0) {
        tbody.innerHTML = getEmptyState(texts.noData);
        return;
    }
    tbody.innerHTML = data.map(row => {
        const isIn = row.type === 'in';
        const badge = isIn 
            ? `<span class="badge-type badge-in"><i class="bi bi-arrow-down-short"></i>${texts.inLabel}</span>`
            : `<span class="badge-type badge-out"><i class="bi bi-arrow-up-short"></i>${texts.outLabel}</span>`;
        return `
            <tr>
                <td>${badge}</td>
                <td>${row.description || '<span style="color:var(--text-muted)">—</span>'}</td>
                <td class="text-end fw-semibold" style="color:${isIn ? 'var(--success)' : 'var(--danger)'}">${formatMoney(row.amount)}</td>
                <td style="color:var(--text-muted);font-size:0.8rem">${row.created_at.substring(0, 16)}</td>
            </tr>
        `;
    }).join('');
}

// ============================================
// LOAD DATA
// ============================================
async function loadData() {
    const from = elFrom.value;
    const to = elTo.value;

    // Update export link
    exportCsv.href = `?action=export&from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`;

    // Show loading
    summaryEl.style.opacity = '0.6';

    try {
        const res = await fetch(`?action=data&from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`);
        const j = await res.json();

        if (!j.success) {
            showToast(j.error || texts.error, 'error');
            return;
        }

        const s = j.summary;

        // Show comparison
        comparisonArea.style.display = 'block';
        comparisonText.textContent = j.comparison.prev_label;

        // Update summary cards
        summaryEl.innerHTML = `
          <div class="row g-3 mb-4 fade-in">
            <div class="col-md-6 col-xl-3">
              <div class="stat-card primary">
                <div class="d-flex align-items-start gap-3">
                  <div class="stat-icon icon-blue"><i class="bi bi-cart-check"></i></div>
                  <div>
                    <div class="stat-label">${texts.sales}</div>
                    <div class="stat-value">${formatMoney(s.sales_sum)}</div>
                    ${getChangeBadge(s.sales_change)}
                  </div>
                </div>
              </div>
            </div>
            <div class="col-md-6 col-xl-3">
              <div class="stat-card success">
                <div class="d-flex align-items-start gap-3">
                  <div class="stat-icon icon-green"><i class="bi bi-graph-up-arrow"></i></div>
                  <div>
                    <div class="stat-label">${texts.profit}</div>
                    <div class="stat-value" style="color:var(--success)">${formatMoney(s.profit_sum)}</div>
                    ${getChangeBadge(s.profit_change)}
                  </div>
                </div>
              </div>
            </div>
            <div class="col-md-6 col-xl-3">
              <div class="stat-card info">
                <div class="d-flex align-items-start gap-3">
                  <div class="stat-icon icon-purple"><i class="bi bi-wallet-fill"></i></div>
                  <div>
                    <div class="stat-label">${texts.cashBalance}</div>
                    <div class="stat-value">${formatMoney(s.cash_balance)}</div>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-md-6 col-xl-3">
              <div class="stat-card dark-card dark">
                <div class="d-flex align-items-start gap-3">
                  <div class="stat-icon" style="background:rgba(255,255,255,0.1);color:#fff"><i class="bi bi-safe"></i></div>
                  <div>
                    <div class="stat-label" style="color:#94a3b8">${texts.totalBalance}</div>
                    <div class="stat-value" style="color:#fff">${formatMoney(s.total_balance)}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="row g-3 mb-4 fade-in">
            <div class="col-md-6 col-xl-3">
              <div class="mini-stat">
                <div>
                  <div class="mini-stat-label">${texts.cashIn}</div>
                  <div class="mini-stat-value" style="color:var(--success)">${formatMoney(s.cash_in)}</div>
                  ${getChangeBadge(s.cash_in_change)}
                </div>
                <i class="bi bi-arrow-down-circle fs-2" style="color:var(--success);opacity:0.6"></i>
              </div>
            </div>
            <div class="col-md-6 col-xl-3">
              <div class="mini-stat">
                <div>
                  <div class="mini-stat-label">${texts.cashOut}</div>
                  <div class="mini-stat-value" style="color:var(--danger)">${formatMoney(s.cash_out)}</div>
                  ${getChangeBadge(s.cash_out_change)}
                </div>
                <i class="bi bi-arrow-up-circle fs-2" style="color:var(--danger);opacity:0.6"></i>
              </div>
            </div>
            <div class="col-md-6 col-xl-3">
              <div class="mini-stat">
                <div>
                  <div class="mini-stat-label">${texts.debts}</div>
                  <div class="mini-stat-value" style="color:var(--warning)">${formatMoney(s.debts_total)}</div>
                </div>
                <i class="bi bi-person-exclamation fs-2" style="color:var(--warning);opacity:0.6"></i>
              </div>
            </div>
            <div class="col-md-6 col-xl-3">
              <div class="mini-stat">
                <div>
                  <div class="mini-stat-label">${texts.inventory}</div>
                  <div class="mini-stat-value" style="color:var(--info)">${formatMoney(s.inventory_value)}</div>
                </div>
                <i class="bi bi-box-seam fs-2" style="color:var(--info);opacity:0.6"></i>
              </div>
            </div>
          </div>
        `;

        // Store data for search
        currentSalesData = j.lists.sales;
        currentCashData = j.lists.cash_transactions;

        // Render tables
        renderSalesTable(currentSalesData);
        renderCashTable(currentCashData);

        // Chart config
        const textColor = getComputedStyle(document.documentElement).getPropertyValue('--text-muted').trim() || '#94a3b8';
        const gridColor = getComputedStyle(document.documentElement).getPropertyValue('--border-color').trim() || '#e2e8f0';

        Chart.defaults.font.family = isRTL ? "'Cairo', sans-serif" : "'Inter', sans-serif";

        // Sales Chart
        if (salesChart) salesChart.destroy();
        salesChart = new Chart(salesChartCtx, {
            type: 'line',
            data: {
                labels: j.charts.dates,
                datasets: [
                    {
                        label: texts.chartSales,
                        data: j.charts.sales_by_date,
                        borderColor: '#4f46e5',
                        backgroundColor: 'rgba(79, 70, 229, 0.08)',
                        fill: true,
                        tension: 0.4,
                        borderWidth: 2.5,
                        pointRadius: 3,
                        pointBackgroundColor: '#4f46e5',
                        pointBorderColor: '#fff',
                        pointBorderWidth: 2,
                        pointHoverRadius: 6
                    },
                    {
                        label: texts.chartProfit,
                        data: j.charts.profit_by_date,
                        borderColor: '#22c55e',
                        backgroundColor: 'rgba(34, 197, 94, 0.08)',
                        fill: true,
                        tension: 0.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: textColor, 
                            usePointStyle: true, 
                            pointStyle: 'circle',
                            padding: 20,
                            font: { size: 12, weight: '500' }
                        }
                    },
                    tooltip: {
                        backgroundColor: 'rgba(15, 23, 42, 0.9)',
                        titleColor: '#fff',
                        bodyColor: '#cbd5e1',
                        borderColor: 'rgba(255,255,255,0.1)',
                        borderWidth: 1,
                        cornerRadius: 8,
                        padding: 12,
                        callbacks: {
                            label: (ctx) => ` ${ctx.dataset.label}: ${formatMoney(ctx.parsed.y)}`
                        }
                    }
                },
                scales: {
                    x: { 
                        grid: { display: false },
                        ticks: { color: textColor, font: { size: 11 } }
                    },
                    y: { 
                        grid: { color: gridColor, borderDash: [4, 4] },
                        ticks: { 
                            color: textColor, 
                            font: { size: 11 },
                            callback: (val) => formatMoney(val)
                        },
                        beginAtZero: true
                    }
                }
            }
        });

        // Cash Chart
        if (cashChart) cashChart.destroy();
        cashChart = new Chart(cashChartCtx, {
            type: 'bar',
            data: {
                labels: j.charts.dates,
                datasets: [
                    {
                        label: texts.chartIn,
                        data: j.charts.cash_in_by_date,
                        backgroundColor: 'rgba(34, 197, 94, 0.8)',
                        hoverBackgroundColor: '#16a34a',
                        borderRadius: 6,
                        borderSkipped: false,
                        barPercentage: 0.7,
                        categoryPercentage: 0.7
                    },
                    {
                        label: texts.chartOut,
                        data: j.charts.cash_out_by_date,
                        backgroundColor: 'rgba(239, 68, 68, 0.8)',
                        hoverBackgroundColor: '#dc2626',
                        borderRadius: 6,
                        borderSkipped: false,
                        barPercentage: 0.7,
                        categoryPercentage: 0.7
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: { mode: 'index', intersect: false },
                plugins: {
                    legend: { 
                        position: 'top', 
                        align: 'end',
                        labels: { 
                            color: textColor, 
                            usePointStyle: true, 
                            pointStyle: 'rectRounded',
                            padding: 20,
                            font: { size: 12, weight: '500' }
                        }
                    },
                    tooltip: {
                        backgroundColor: 'rgba(15, 23, 42, 0.9)',
                        titleColor: '#fff',
                        bodyColor: '#cbd5e1',
                        borderColor: 'rgba(255,255,255,0.1)',
                        borderWidth: 1,
                        cornerRadius: 8,
                        padding: 12,
                        callbacks: {
                            label: (ctx) => ` ${ctx.dataset.label}: ${formatMoney(ctx.parsed.y)}`
                        }
                    }
                },
                scales: {
                    x: { 
                        grid: { display: false },
                        ticks: { color: textColor, font: { size: 11 } }
                    },
                    y: { 
                        grid: { color: gridColor, borderDash: [4, 4] },
                        ticks: { 
                            color: textColor, 
                            font: { size: 11 },
                            callback: (val) => formatMoney(val)
                        },
                        beginAtZero: true
                    }
                }
            }
        });

        showToast(`${lang === 'ar' ? 'تم تحديث البيانات' : 'Data updated'}`, 'success');

    } catch (e) {
        console.error(e);
        showToast(texts.error, '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><?= $is_ar ? 'خطأ!' : 'Error!' ?></strong>
                    <p class="mb-0 mt-1">${texts.error}</p>
                </div>
            </div>
        `;
    } finally {
        summaryEl.style.opacity = '1';
    }
}

// ============================================
// EVENT LISTENERS
// ============================================
applyBtn.addEventListener('click', loadData);

// Auto-load on Enter key
[elFrom, elTo].forEach(input => {
    input.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') loadData();
    });
});

// Initial load
loadData();
</script>

</body>
</html>