<?php
/**
 * dashboard.php
 * Enhanced Professional Version
 */

require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/src/auth.php';
require_once __DIR__ . '/src/functions.php';

require_login();

// --- إعدادات المستخدم ---
 $avatar = $_SESSION['avatar'] ?? 'assets/img/avatar.png';
if (!preg_match('#^assets/img/#', $avatar) || !file_exists(__DIR__ . '/' . $avatar)) {
    $avatar = 'assets/img/avatar.png';
}
 $username = $_SESSION['username'] ?? 'Admin';

// --- إعدادات اللغة ---
 $lang = $_GET['lang'] ?? ($_SESSION['lang'] ?? 'en');
 $lang = in_array($lang, ['en','ar']) ? $lang : 'en';
 $_SESSION['lang'] = $lang;
 $dir = $lang === 'ar' ? 'rtl' : 'ltr';

function esc($v){ return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }

// --- معالجة AJAX ---
if (isset($_GET['ajax_stats'])) {
    header('Content-Type: application/json; charset=utf-8');
    try {
        $totalProducts = (int)$pdo->query("SELECT COUNT(*) FROM products")->fetchColumn();
        $lowStockCount = (int)$pdo->query("SELECT COUNT(*) FROM products WHERE stock <= 5")->fetchColumn();
        $outOfStock = (int)$pdo->query("SELECT COUNT(*) FROM products WHERE stock <= 0")->fetchColumn();
        $totalCustomers = (int)$pdo->query("SELECT COUNT(*) FROM customers")->fetchColumn();
        
        $stmt = $pdo->prepare("
            SELECT 
                COUNT(*) as invoices_count, 
                COALESCE(SUM(total),0) as sales_sum, 
                COALESCE(SUM(profit),0) as profit_sum 
            FROM sales 
            WHERE DATE(created_at) = CURDATE()
        ");
        $stmt->execute();
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        $todayInvoices = (int)($row['invoices_count'] ?? 0);
        $todaySales    = (float)($row['sales_sum'] ?? 0);
        $todayProfit   = (float)($row['profit_sum'] ?? 0);

        $stmt = $pdo->query("
            SELECT 
                COALESCE(SUM(CASE WHEN type='in' THEN amount ELSE 0 END), 0) AS total_in,
                COALESCE(SUM(CASE WHEN type='out' THEN amount ELSE 0 END), 0) AS total_out,
                COALESCE(SUM(CASE WHEN type='in' THEN amount ELSE -amount END), 0) AS balance
            FROM cash_transactions
        ");
        $c = $stmt->fetch(PDO::FETCH_ASSOC);
        
        // ديون العملاء
        $debtsTotal = (float)$pdo->query("SELECT COALESCE(SUM(CASE WHEN balance>0 THEN balance ELSE 0 END),0) FROM customers")->fetchColumn();
        
        echo json_encode([
            'ok' => 1,
            'todayInvoices' => $todayInvoices,
            'todaySales'    => round($todaySales, 2),
            'todayProfit'   => round($todayProfit, 2),
            'totalProducts' => $totalProducts,
            'lowStockCount' => $lowStockCount,
            'outOfStock'    => $outOfStock,
            'totalCustomers'=> $totalCustomers,
            'cashIn'        => round($c['total_in'], 2),
            'cashOut'       => round($c['total_out'], 2),
            'cashBalance'   => round($c['balance'], 2),
            'debtsTotal'    => round($debtsTotal, 2),
            'time'          => date('h:i A')
        ]);
    } catch (Exception $e) {
        echo json_encode(['ok'=>0, 'error'=>$e->getMessage()]);
    }
    exit;
}

// --- البيانات الأولية ---
try {
    $totalProducts = (int)$pdo->query("SELECT COUNT(*) FROM products")->fetchColumn();
    $lowStockCount = (int)$pdo->query("SELECT COUNT(*) FROM products WHERE stock <= 5")->fetchColumn();
    $outOfStock = (int)$pdo->query("SELECT COUNT(*) FROM products WHERE stock <= 0")->fetchColumn();
    $totalCustomers = (int)$pdo->query("SELECT COUNT(*) FROM customers")->fetchColumn();
    
    $row = $pdo->query("SELECT COUNT(*) as c, COALESCE(SUM(total),0) as s, COALESCE(SUM(profit),0) as p FROM sales WHERE DATE(created_at) = CURDATE()")->fetch(PDO::FETCH_ASSOC);
    $todayInvoices = $row['c']; $todaySales = $row['s']; $todayProfit = $row['p'];

    $c = $pdo->query("SELECT COALESCE(SUM(CASE WHEN type='in' THEN amount ELSE 0 END), 0) as i, COALESCE(SUM(CASE WHEN type='out' THEN amount ELSE 0 END), 0) as o, COALESCE(SUM(CASE WHEN type='in' THEN amount ELSE -amount END), 0) as b FROM cash_transactions")->fetch(PDO::FETCH_ASSOC);
    $cashIn = $c['i']; $cashOut = $c['o']; $cashBalance = $c['b'];
    
    $debtsTotal = (float)$pdo->query("SELECT COALESCE(SUM(CASE WHEN balance>0 THEN balance ELSE 0 END),0) FROM customers")->fetchColumn();

} catch(Exception $e){
    $db_error = $e->getMessage();
    $totalProducts = $lowStockCount = $outOfStock = $totalCustomers = $todayInvoices = 0;
    $todaySales = $todayProfit = $cashIn = $cashOut = $cashBalance = $debtsTotal = 0;
}

// --- النصوص ---
 $T = [
  'en'=>[
    'title'=>'Dashboard',
    'welcome'=>'Welcome back',
    'stats_sales'=>'Today Sales',
    'stats_invoices'=>'Invoices',
    'stats_products'=>'Products',
    'stats_customers'=>'Customers',
    'stats_cash'=>'Cash Balance',
    'stats_debts'=>'Customer Debts',
    'low_stock'=>'Low Stock',
    'out_of_stock'=>'Out of Stock',
    'updated'=>'Updated',
    'today_date'=>'Today',
    'sections'=>'Quick Actions',
    'sale_inv'=>'New Sale Invoice',
    'sale_list'=>'Sales History',
    'purch_inv'=>'Purchase Invoice',
    'add_prod'=>'Add Product',
    'prod_list'=>'Products List',
    'stock_audit'=>'Stock Audit',
    'cust_add'=>'Customers',
    'cust_debt'=>'Customer Debts',
    'suppliers'=>'Suppliers',
    'add_bal'=>'Add Balance',
    'withdraw'=>'Withdraw',
    'cash_rep'=>'Financial Report',
    'users'=>'Users',
    'backup'=>'Backup',
    'logout'=>'Logout',
    'profile'=>'Profile',
    'settings'=>'Settings',
    'view_report'=>'View Report'
  ],
  'ar'=>[
    'title'=>'لوحة القيادة',
    'welcome'=>'مرحباً بعودتك',
    'stats_sales'=>'مبيعات اليوم',
    'stats_invoices'=>'فاتورة',
    'stats_products'=>'المنتجات',
    'stats_customers'=>'العملاء',
    'stats_cash'=>'رصيد الصندوق',
    'stats_debts'=>'ديون العملاء',
    'low_stock'=>'مخزون منخفض',
    'out_of_stock'=>'نفذ من المخزون',
    'updated'=>'تحديث',
    'today_date'=>'اليوم',
    'sections'=>'الوصول السريع',
    'sale_inv'=>'فاتورة بيع جديدة',
    'sale_list'=>'سجل المبيعات',
    'purch_inv'=>'فاتورة مشتريات',
    'add_prod'=>'إضافة منتج',
    'prod_list'=>'قائمة المنتجات',
    'stock_audit'=>'جرد ونواقص',
    'cust_add'=>'إدارة العملاء',
    'cust_debt'=>'ديون العملاء',
    'suppliers'=>'الموردين',
    'add_bal'=>'إيداع رصيد',
    'withdraw'=>'سحب رصيد',
    'cash_rep'=>'التقرير المالي',
    'users'=>'المستخدمين',
    'backup'=>'نسخة احتياطية',
    'logout'=>'خروج',
    'profile'=>'الملف الشخصي',
    'settings'=>'الإعدادات',
    'view_report'=>'عرض التقرير'
  ]
];
 $t = $T[$lang];

// الثيم - نستخدم localStorage بس
 $initialTheme = 'dark';
if (isset($_COOKIE['bo_theme']) && $_COOKIE['bo_theme'] === 'light') {
    $initialTheme = 'light';
}
?>
<!doctype html>
<html lang="<?= esc($lang) ?>" dir="<?= $dir ?>">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title><?= esc($t['title']) ?> - Top Accessories</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@400;500;600;700;800&family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
  
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">

  <style>
    :root {
      --bg-body: #0F111A;
      --bg-sidebar: #151922;
      --bg-card: #1C212E;
      --bg-hover: #232938;
      --text-main: #FFFFFF;
      --text-muted: #8E95A9;
      --border: rgba(255,255,255,0.05);
      --border-highlight: rgba(255,255,255,0.1);
      --primary: #4361EE;
      --primary-glow: rgba(67, 97, 238, 0.3);
      --danger: #ff4757;
      --success: #2ed573;
      --warning: #FF9F43;
      --sidebar-w: 280px;
      --glass-bg: rgba(21, 25, 34, 0.7);
      --card-radius: 20px;
      --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    }
    
    body.light {
      --bg-body: #F4F7FE;
      --bg-sidebar: #FFFFFF;
      --bg-card: #FFFFFF;
      --bg-hover: #F8F9FA;
      --text-main: #2B3674;
      --text-muted: #A3AED0;
      --border: rgba(0,0,0,0.04);
      --border-highlight: rgba(0,0,0,0.08);
      --primary: #4318FF;
      --primary-glow: rgba(67, 24, 255, 0.15);
      --glass-bg: rgba(255, 255, 255, 0.8);
    }

    body {
      background: var(--bg-body);
      color: var(--text-main);
      font-family: 'Poppins', 'Cairo', sans-serif;
      transition: background 0.4s ease, color 0.4s ease;
      overflow-x: hidden;
    }

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

    /* --- Sidebar --- */
    .sidebar {
      width: var(--sidebar-w);
      height: 100vh;
      background: var(--bg-sidebar);
      position: fixed;
      top: 0; 
      <?= $dir === 'rtl' ? 'right:0;' : 'left:0;' ?>
      z-index: 1050;
      transition: transform 0.4s ease;
      display: flex; flex-direction: column;
      border-<?= $dir === 'rtl' ? 'left' : 'right' ?>: 1px solid var(--border);
    }
    
    .logo-area {
      padding: 25px 30px;
      display: flex; align-items: center; gap: 14px;
      border-bottom: 1px solid var(--border);
    }
    .logo-icon {
      width: 46px; height: 46px;
      background: linear-gradient(135deg, var(--primary), #3A8DFF);
      border-radius: 13px;
      display: flex; align-items: center; justify-content: center;
      color: #fff; font-size: 1.1rem; font-weight: 800;
      box-shadow: 0 8px 16px var(--primary-glow);
      flex-shrink: 0;
    }
    .logo-text { font-size: 1.05rem; font-weight: 700; letter-spacing: 0.3px; }

    .nav-links { flex: 1; overflow-y: auto; padding: 15px 20px; }
    .nav-section-label {
      display: block; margin-bottom: 10px; padding: 0 14px;
      font-size: 0.7rem; font-weight: 700; text-transform: uppercase;
      color: var(--text-muted); opacity: 0.6; letter-spacing: 1px;
    }
    .nav-item {
      display: flex; align-items: center; gap: 13px;
      padding: 12px 16px;
      margin-bottom: 4px;
      color: var(--text-muted);
      text-decoration: none;
      border-radius: 12px;
      transition: var(--transition);
      font-weight: 500; font-size: 0.9rem;
    }
    .nav-item:hover {
      background: var(--bg-hover);
      color: var(--text-main);
      transform: translateX(<?= $dir === 'rtl' ? '-3px' : '3px' ?>);
    }
    .nav-item.active {
      background: var(--primary);
      color: #fff;
      box-shadow: 0 6px 14px var(--primary-glow);
    }
    .nav-item i { width: 20px; text-align: center; font-size: 1rem; }
    .nav-badge {
      margin-inline-start: auto;
      background: var(--danger);
      color: #fff;
      font-size: 0.65rem;
      font-weight: 700;
      padding: 2px 7px;
      border-radius: 10px;
      min-width: 20px;
      text-align: center;
    }

    /* --- Main Content --- */
    .main-wrapper {
      margin-<?= $dir === 'rtl' ? 'right' : 'left' ?>: var(--sidebar-w);
      padding: 25px 30px;
      transition: margin 0.4s ease;
      min-height: 100vh;
    }

    /* --- Topbar --- */
    .topbar {
      display: flex; justify-content: space-between; align-items: center;
      margin-bottom: 30px;
      padding: 12px 20px;
      background: var(--glass-bg);
      backdrop-filter: blur(12px);
      -webkit-backdrop-filter: blur(12px);
      border-radius: 16px;
      border: 1px solid var(--border);
      position: sticky; top: 10px; z-index: 990;
    }
    
    .btn-icon {
      width: 40px; height: 40px;
      display: inline-flex; align-items: center; justify-content: center;
      border-radius: 50%;
      border: none;
      background: var(--bg-body);
      color: var(--text-muted);
      cursor: pointer;
      transition: 0.3s;
      font-size: 1rem;
    }
    .btn-icon:hover { background: var(--bg-hover); color: var(--primary); }
    
    .datetime-box {
      display: flex; align-items: center; gap: 10px;
      padding: 8px 16px;
      background: var(--bg-body);
      border-radius: 12px;
      border: 1px solid var(--border);
    }
    .datetime-box .date-part {
      font-size: 0.75rem;
      color: var(--text-muted);
      font-weight: 500;
    }
    .datetime-box .time-part {
      font-size: 1rem;
      font-weight: 700;
      font-variant-numeric: tabular-nums;
      letter-spacing: 0.5px;
    }
    .time-separator {
      animation: blink 1s step-end infinite;
    }
    @keyframes blink {
      50% { opacity: 0; }
    }

    .user-profile {
      display: flex; align-items: center; gap: 10px;
      padding: 5px 10px 5px 5px;
      background: var(--bg-body);
      border-radius: 30px;
      cursor: pointer;
      transition: 0.3s;
      border: 1px solid transparent;
    }
    .user-profile:hover { border-color: var(--border-highlight); background: var(--bg-hover); }
    .user-profile img { width: 36px; height: 36px; border-radius: 50%; object-fit: cover; }

    /* --- Stats Cards --- */
    .stat-card {
      background: var(--bg-card);
      border: 1px solid var(--border);
      border-radius: var(--card-radius);
      padding: 22px;
      position: relative;
      overflow: hidden;
      height: 100%;
      transition: var(--transition);
      cursor: default;
    }
    .stat-card:hover { 
      transform: translateY(-4px); 
      box-shadow: 0 12px 24px rgba(0,0,0,0.08); 
      border-color: var(--border-highlight); 
    }
    .stat-card.clickable:hover { cursor: pointer; }
    
    .icon-box {
      width: 48px; height: 48px;
      border-radius: 14px;
      display: flex; align-items: center; justify-content: center;
      font-size: 1.3rem;
      flex-shrink: 0;
    }
    
    .st-blue .icon-box { background: rgba(67, 97, 238, 0.12); color: #4361EE; }
    .st-orange .icon-box { background: rgba(255, 159, 67, 0.12); color: #FF9F43; }
    .st-green .icon-box { background: rgba(46, 213, 115, 0.12); color: #2ed573; }
    .st-red .icon-box { background: rgba(255, 71, 87, 0.12); color: #ff4757; }
    .st-purple .icon-box { background: rgba(108, 92, 231, 0.12); color: #6c5ce7; }

    .stat-title { 
      font-size: 0.8rem; 
      color: var(--text-muted); 
      font-weight: 500; 
      margin-bottom: 6px;
    }
    .stat-val { 
      font-size: 1.75rem; 
      font-weight: 700; 
      color: var(--text-main); 
      letter-spacing: -0.5px;
      line-height: 1.2;
      transition: color 0.3s;
    }
    .stat-sub { 
      font-size: 0.75rem; 
      display: flex; 
      align-items: center; 
      gap: 6px; 
      font-weight: 500;
      margin-top: 10px;
      padding-top: 10px;
      border-top: 1px solid var(--border);
    }
    .stat-badge {
      display: inline-flex;
      align-items: center;
      gap: 4px;
      padding: 3px 8px;
      border-radius: 6px;
      font-size: 0.72rem;
      font-weight: 600;
    }
    .stat-badge.badge-danger { background: rgba(255,71,87,0.12); color: #ff4757; }
    .stat-badge.badge-success { background: rgba(46,213,115,0.12); color: #2ed573; }
    .stat-badge.badge-warning { background: rgba(255,159,67,0.12); color: #FF9F43; }
    .stat-badge.badge-primary { background: var(--primary-glow); color: var(--primary); }
    
    .stat-link {
      position: absolute;
      bottom: 0;
      right: 0;
      left: 0;
      padding: 8px;
      text-align: center;
      font-size: 0.72rem;
      font-weight: 600;
      color: var(--primary);
      background: var(--primary-glow);
      opacity: 0;
      transition: opacity 0.3s;
      text-decoration: none;
    }
    .stat-card.clickable:hover .stat-link { opacity: 1; }

    /* --- Action Tiles --- */
    .tile {
      display: block;
      text-decoration: none;
      color: #fff !important;
      border-radius: var(--card-radius);
      padding: 22px;
      height: 100%;
      position: relative;
      overflow: hidden;
      transition: var(--transition);
      box-shadow: 0 8px 16px rgba(0,0,0,0.05);
      border: 0;
    }
    .tile:hover { transform: translateY(-6px) scale(1.01); box-shadow: 0 16px 32px rgba(0,0,0,0.12); }
    .tile::before {
      content: ''; position: absolute; inset: 0;
      background: linear-gradient(to bottom, rgba(255,255,255,0.12), transparent);
      opacity: 0; transition: 0.3s;
    }
    .tile:hover::before { opacity: 1; }
    
    .tile-icon { font-size: 2rem; margin-bottom: 12px; filter: drop-shadow(0 3px 5px rgba(0,0,0,0.1)); }
    .tile h5 { font-size: 1.1rem; font-weight: 700; margin: 0; }
    .tile small { opacity: 0.85; font-size: 0.8rem; display: block; margin-top: 4px; font-weight: 400; }

    .g-orange { background: linear-gradient(135deg, #FF9F43, #FF6B6B); }
    .g-blue   { background: linear-gradient(135deg, #4facfe, #00f2fe); }
    .g-violet { background: linear-gradient(135deg, #667eea, #764ba2); }
    .g-teal   { background: linear-gradient(135deg, #20E3B2, #0fb9b1); color: #0F111A !important; }
    .g-purple { background: linear-gradient(135deg, #a18cd1, #fbc2eb); color: #4b3b75 !important; }
    .g-cyan   { background: linear-gradient(135deg, #00c6fb, #005bea); }
    .g-red    { background: linear-gradient(135deg, #ff6b6b, #ee5253); }
    .g-emerald{ background: linear-gradient(135deg, #00b09b, #96c93d); }
    .g-dark   { background: linear-gradient(135deg, #434343, #2b2b2b); }
    .g-indigo { background: linear-gradient(135deg, #6c5ce7, #a29bfe); }
    .g-coral  { background: linear-gradient(135deg, #e17055, #fab1a0); }
    .g-pink   { background: linear-gradient(135deg, #d63031, #ff7675); }

    /* Dropdown */
    .dropdown-menu { 
      background: var(--bg-card); 
      border: 1px solid var(--border); 
      box-shadow: 0 12px 36px rgba(0,0,0,0.12); 
      border-radius: 12px;
      padding: 8px;
    }
    .dropdown-item { 
      color: var(--text-main); 
      padding: 9px 14px; 
      border-radius: 8px; 
      font-weight: 500;
      font-size: 0.88rem;
      transition: 0.2s;
    }
    .dropdown-item:hover { background: var(--bg-hover); color: var(--primary); }

    /* Number animation */
    .animate-number {
      transition: opacity 0.2s;
    }
    .animate-number.updating {
      opacity: 0.5;
    }

    /* Mobile */
    @media (max-width: 991px) {
      .sidebar { transform: translateX(<?= $dir === 'rtl' ? '100%' : '-100%' ?>); }
      .sidebar.open { transform: translateX(0); box-shadow: 0 0 50px rgba(0,0,0,0.5); }
      .main-wrapper { margin-inline-start: 0; padding: 15px; }
      .overlay {
        position: fixed; inset: 0; background: rgba(0,0,0,0.6); z-index: 999;
        display: none; backdrop-filter: blur(4px);
      }
      .overlay.show { display: block; }
      .datetime-box .date-part { display: none; }
      .stat-val { font-size: 1.4rem; }
    }
  </style>
</head>
<body class="<?= $initialTheme === 'light' ? 'light' : '' ?>">

<div class="overlay" id="overlay"></div>

<!-- Sidebar -->
<aside class="sidebar" id="sidebar">
  <div class="logo-area">
    <div class="logo-icon">TA</div>
    <span class="logo-text">Top Accessories</span>
  </div>
  
  <nav class="nav-links">
    <span class="nav-section-label"><?= $lang === 'ar' ? 'الرئيسي' : 'Main' ?></span>
    
    <a href="sales_create.php" class="nav-item active">
      <i class="fa-solid fa-cart-plus"></i> <?= $t['sale_inv'] ?>
    </a>
    <a href="sales_list.php" class="nav-item">
      <i class="fa-solid fa-list-ul"></i> <?= $t['sale_list'] ?>
    </a>
    <a href="products.php" class="nav-item">
      <i class="fa-solid fa-boxes-stacked"></i> <?= $t['prod_list'] ?>
      <?php if($outOfStock > 0): ?>
      <span class="nav-badge"><?= $outOfStock ?></span>
      <?php endif; ?>
    </a>
    <a href="customers.php" class="nav-item">
      <i class="fa-solid fa-users"></i> <?= $t['cust_add'] ?>
    </a>
    <a href="debts.php" class="nav-item">
      <i class="fa-solid fa-hand-holding-dollar"></i> <?= $t['cust_debt'] ?>
    </a>
    <a href="inventory.php" class="nav-item">
      <i class="fa-solid fa-warehouse"></i> <?= $t['stock_audit'] ?>
    </a>
    
    <div style="height:1px; background:var(--border); margin:12px 14px;"></div>
    <span class="nav-section-label"><?= $lang === 'ar' ? 'النظام' : 'System' ?></span>
    
    <a href="suppliers.php" class="nav-item">
      <i class="fa-solid fa-truck"></i> <?= $t['suppliers'] ?>
    </a>
    <a href="purchase_invoice.php" class="nav-item">
      <i class="fa-solid fa-truck-ramp-box"></i> <?= $t['purch_inv'] ?>
    </a>
    <a href="cash_report.php" class="nav-item">
      <i class="fa-solid fa-chart-pie"></i> <?= $t['cash_rep'] ?>
    </a>
    <a href="users.php" class="nav-item">
      <i class="fa-solid fa-user-gear"></i> <?= $t['users'] ?>
    </a>
    <a href="admin/create_backup.php" class="nav-item">
      <i class="fa-solid fa-database"></i> <?= $t['backup'] ?>
    </a>
    <a href="logout.php" class="nav-item" style="color:var(--danger); margin-top:10px;">
      <i class="fa-solid fa-right-from-bracket"></i> <?= $t['logout'] ?>
    </a>
  </nav>
</aside>

<main class="main-wrapper">
  
  <!-- Topbar -->
  <header class="topbar">
    <div class="d-flex align-items-center gap-3">
      <button class="btn-icon d-lg-none" id="menuBtn"><i class="fa-solid fa-bars"></i></button>
      <h5 class="m-0 fw-bold"><?= $t['title'] ?></h5>
    </div>

    <div class="d-flex align-items-center gap-2">
      <!-- Date & Time -->
      <div class="datetime-box d-none d-md-flex">
        <i class="fa-regular fa-calendar" style="color:var(--text-muted); font-size:0.9rem;"></i>
        <div>
          <div class="date-part" id="currentDate"></div>
          <div class="time-part">
            <span id="clockHours">00</span><span class="time-separator">:</span><span id="clockMinutes">00</span><span class="time-separator">:</span><span id="clockSeconds" style="font-size:0.75rem; opacity:0.6;">00</span>
            <span id="clockAmPm" style="font-size:0.7rem; margin-inline-start:4px; opacity:0.7;">AM</span>
          </div>
        </div>
      </div>
      
      <button class="btn-icon" id="themeBtn" title="Toggle Theme">
        <i class="fa-solid <?= $initialTheme === 'light' ? 'fa-sun' : 'fa-moon' ?>"></i>
      </button>

      <div class="dropdown">
        <button class="btn-icon fw-bold" data-bs-toggle="dropdown" style="font-size:0.85rem">
          <?= strtoupper($lang) ?>
        </button>
        <ul class="dropdown-menu dropdown-menu-end">
          <li><a class="dropdown-item" href="?lang=en">🇺🇸 English</a></li>
          <li><a class="dropdown-item" href="?lang=ar">🇸🇦 العربية</a></li>
        </ul>
      </div>

      <div class="dropdown">
        <div class="user-profile" data-bs-toggle="dropdown">
          <img src="<?= esc($avatar) ?>?v=<?= time() ?>" alt="User">
          <span class="d-none d-sm-block fw-bold" style="font-size:0.85rem"><?= esc($username) ?></span>
          <i class="fa-solid fa-chevron-down" style="font-size:0.65rem; color:var(--text-muted);"></i>
        </div>
        <ul class="dropdown-menu dropdown-menu-end mt-2">
          <li class="px-3 py-2 fw-bold border-bottom border-secondary border-opacity-10 mb-1"><?= esc($username) ?></li>
          <li><a class="dropdown-item" href="profile.php"><i class="fa-regular fa-id-card me-2"></i> <?= $t['profile'] ?></a></li>
          <li><a class="dropdown-item" href="settings.php"><i class="fa-solid fa-sliders me-2"></i> <?= $t['settings'] ?></a></li>
          <li><hr class="dropdown-divider bg-secondary opacity-10"></li>
          <li><a class="dropdown-item text-danger" href="logout.php"><i class="fa-solid fa-power-off me-2"></i> <?= $t['logout'] ?></a></li>
        </ul>
      </div>
    </div>
  </header>
  
  <?php if(isset($db_error)): ?>
    <div class="alert alert-danger shadow-sm border-0 rounded-4 mb-4"><i class="fa-solid fa-triangle-exclamation me-2"></i> <?= esc($db_error) ?></div>
  <?php endif; ?>

  <!-- Stats Grid -->
  <div class="row g-3 mb-4">
    <div class="col-xl-3 col-md-6">
      <div class="stat-card st-blue">
        <div class="d-flex justify-content-between align-items-start">
            <div>
                <div class="stat-title"><?= $t['stats_sales'] ?></div>
                <div class="stat-val animate-number" id="todaySales"><?= number_format($todaySales) ?></div>
                <div class="stat-sub">
                  <span class="stat-badge badge-success"><i class="fa-solid fa-receipt"></i> <?= $todayInvoices ?> <?= $t['stats_invoices'] ?></span>
                </div>
            </div>
            <div class="icon-box"><i class="fa-solid fa-file-invoice-dollar"></i></div>
        </div>
      </div>
    </div>
    
    <div class="col-xl-3 col-md-6">
      <div class="stat-card st-orange clickable" onclick="location.href='products.php?filter=low_stock'">
        <div class="d-flex justify-content-between align-items-start">
            <div>
                <div class="stat-title"><?= $t['stats_products'] ?></div>
                <div class="stat-val animate-number" id="totalProducts"><?= number_format($totalProducts) ?></div>
                <div class="stat-sub">
                  <?php if($outOfStock > 0): ?>
                  <span class="stat-badge badge-danger"><i class="fa-solid fa-circle-xmark"></i> <?= $outOfStock ?> <?= $t['out_of_stock'] ?></span>
                  <?php else: ?>
                  <span class="stat-badge badge-warning"><i class="fa-solid fa-circle-exclamation"></i> <?= $lowStockCount ?> <?= $t['low_stock'] ?></span>
                  <?php endif; ?>
                </div>
            </div>
            <div class="icon-box"><i class="fa-solid fa-box-open"></i></div>
        </div>
        <a href="products.php?filter=low_stock" class="stat-link"><?= $t['view_report'] ?> →</a>
      </div>
    </div>

    <div class="col-xl-3 col-md-6">
      <div class="stat-card st-green">
        <div class="d-flex justify-content-between align-items-start">
            <div>
                <div class="stat-title"><?= $t['stats_customers'] ?></div>
                <div class="stat-val animate-number" id="totalCustomers"><?= number_format($totalCustomers) ?></div>
                <div class="stat-sub">
                  <span class="stat-badge badge-primary"><i class="fa-solid fa-hand-holding-dollar"></i> <?= number_format($debtsTotal, 0) ?> <?= $t['stats_debts'] ?></span>
                </div>
            </div>
            <div class="icon-box"><i class="fa-solid fa-users"></i></div>
        </div>
      </div>
    </div>

    <div class="col-xl-3 col-md-6">
      <div class="stat-card st-red clickable" onclick="location.href='cash_report.php'">
        <div class="d-flex justify-content-between align-items-start">
            <div>
                <div class="stat-title"><?= $t['stats_cash'] ?></div>
                <div class="stat-val animate-number" id="cashBalance" style="color: <?= $cashBalance < 0 ? 'var(--danger)' : 'var(--primary)' ?>"><?= number_format($cashBalance, 2) ?></div>
                <div class="stat-sub" style="border:none; padding-top:0; margin-top:0;">
                  <span class="text-muted" style="font-size:0.7rem;" id="lastUpdate">
                    <i class="fa-regular fa-clock"></i> <?= $t['updated'] ?>: <?= date('h:i A') ?>
                  </span>
                </div>
            </div>
            <div class="icon-box"><i class="fa-solid fa-wallet"></i></div>
        </div>
        <a href="cash_report.php" class="stat-link"><?= $t['view_report'] ?> →</a>
      </div>
    </div>
  </div>

  <h6 class="fw-bold mb-3 ps-2" style="font-size:0.85rem; color:var(--text-muted);">
    <i class="fa-solid fa-grid-2 me-2"></i><?= $t['sections'] ?>
  </h6>
  
  <div class="row g-3">
    <div class="col-xl-3 col-md-6 col-sm-6">
      <a href="sales_create.php" class="tile g-orange">
        <div class="tile-icon"><i class="fa-solid fa-cart-shopping"></i></div>
        <h5><?= $t['sale_inv'] ?></h5>
        <small><?= $lang=='ar' ? 'إنشاء فاتورة' : 'Create invoice' ?></small>
      </a>
    </div>
    <div class="col-xl-3 col-md-6 col-sm-6">
      <a href="sales_list.php" class="tile g-blue">
        <div class="tile-icon"><i class="fa-solid fa-magnifying-glass-dollar"></i></div>
        <h5><?= $t['sale_list'] ?></h5>
        <small><?= $lang=='ar' ? 'سجل الفواتير' : 'Invoices log' ?></small>
      </a>
    </div>
    <div class="col-xl-3 col-md-6 col-sm-6">
      <a href="purchase_invoice.php" class="tile g-violet">
        <div class="tile-icon"><i class="fa-solid fa-truck-ramp-box"></i></div>
        <h5><?= $t['purch_inv'] ?></h5>
        <small><?= $lang=='ar' ? 'إدخال بضاعة' : 'Add stock' ?></small>
      </a>
    </div>
    <div class="col-xl-3 col-md-6 col-sm-6">
      <a href="suppliers.php" class="tile g-teal">
        <div class="tile-icon"><i class="fa-solid fa-truck-field"></i></div>
        <h5><?= $t['suppliers'] ?></h5>
        <small><?= $lang=='ar' ? 'إدارة الموردين' : 'Manage suppliers' ?></small>
      </a>
    </div>

    <div class="col-xl-3 col-md-6 col-sm-6">
      <a href="add_product.php" class="tile g-purple">
        <div class="tile-icon"><i class="fa-solid fa-plus-circle"></i></div>
        <h5><?= $t['add_prod'] ?></h5>
        <small><?= $lang=='ar' ? 'منتج جديد' : 'New product' ?></small>
      </a>
    </div>
    <div class="col-xl-3 col-md-6 col-sm-6">
      <a href="products.php" class="tile g-cyan">
        <div class="tile-icon"><i class="fa-solid fa-list-check"></i></div>
        <h5><?= $t['prod_list'] ?></h5>
        <small><?= $lang=='ar' ? 'الأسعار والكميات' : 'Prices & stock' ?></small>
      </a>
    </div>
    <div class="col-xl-3 col-md-6 col-sm-6">
      <a href="stock_audit.php" class="tile g-red">
        <div class="tile-icon"><i class="fa-solid fa-clipboard-check"></i></div>
        <h5><?= $t['stock_audit'] ?></h5>
        <small><?= $lang=='ar' ? 'نواقص وتالف' : 'Damaged items' ?></small>
      </a>
    </div>
    <div class="col-xl-3 col-md-6 col-sm-6">
      <a href="customers.php" class="tile g-indigo">
        <div class="tile-icon"><i class="fa-solid fa-address-book"></i></div>
        <h5><?= $t['cust_add'] ?></h5>
        <small><?= $lang=='ar' ? 'بيانات العملاء' : 'Customer data' ?></small>
      </a>
    </div>

    <div class="col-xl-3 col-md-6 col-sm-6">
      <a href="debts.php" class="tile g-coral">
        <div class="tile-icon"><i class="fa-solid fa-book-open"></i></div>
        <h5><?= $t['cust_debt'] ?></h5>
        <small><?= $lang=='ar' ? 'متابعة الديون' : 'Track debts' ?></small>
      </a>
    </div>
    <div class="col-xl-3 col-md-6 col-sm-6">
      <a href="add_balance.php" class="tile g-emerald">
        <div class="tile-icon"><i class="fa-solid fa-money-bill-wave"></i></div>
        <h5><?= $t['add_bal'] ?></h5>
        <small><?= $lang=='ar' ? 'إيداع بالصندوق' : 'Deposit cash' ?></small>
      </a>
    </div>
    <div class="col-xl-3 col-md-6 col-sm-6">
      <a href="withdraw.php" class="tile g-pink">
        <div class="tile-icon"><i class="fa-solid fa-money-bill-transfer"></i></div>
        <h5><?= $t['withdraw'] ?></h5>
        <small><?= $lang=='ar' ? 'سحب مصاريف' : 'Withdraw' ?></small>
      </a>
    </div>
    <div class="col-xl-3 col-md-6 col-sm-6">
      <a href="cash_report.php" class="tile g-dark">
        <div class="tile-icon"><i class="fa-solid fa-chart-pie"></i></div>
        <h5><?= $t['cash_rep'] ?></h5>
        <small><?= $lang=='ar' ? 'التقرير المالي' : 'Financial report' ?></small>
      </a>
    </div>
  </div> 

  <footer class="mt-4 mb-2 text-center small" style="color:var(--text-muted); opacity:0.4;">
    &copy; <?= date('Y') ?> Top Accessories POS &bull; v2.0
  </footer>

</main>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    
    const isAr = <?= $lang === 'ar' ? 'true' : 'false' ?>;
    
    // --- Live Clock (محسّن) ---
    function updateClock(){
        const now = new Date();
        
        const hours = now.getHours();
        const minutes = now.getMinutes();
        const seconds = now.getSeconds();
        const ampm = hours >= 12 ? 'PM' : 'AM';
        const h12 = hours % 12 || 12;
        
        document.getElementById('clockHours').textContent = String(h12).padStart(2, '0');
        document.getElementById('clockMinutes').textContent = String(minutes).padStart(2, '0');
        document.getElementById('clockSeconds').textContent = String(seconds).padStart(2, '0');
        document.getElementById('clockAmPm').textContent = isAr ? (ampm === 'AM' ? 'ص' : 'م') : ampm;
        
        // التاريخ
        const dateStr = now.toLocaleDateString(isAr ? 'ar-EG' : 'en-US', {
            weekday: 'long',
            year: 'numeric',
            month: 'long',
            day: 'numeric'
        });
        const dateEl = document.getElementById('currentDate');
        if(dateEl) dateEl.textContent = dateStr;
    }
    setInterval(updateClock, 1000);
    updateClock();

    // --- Sidebar Toggle ---
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('overlay');
    const menuBtn = document.getElementById('menuBtn');
    
    function closeSidebar() {
        sidebar.classList.remove('open');
        overlay.classList.remove('show');
    }
    
    if(menuBtn) menuBtn.addEventListener('click', () => {
        sidebar.classList.add('open');
        overlay.classList.add('show');
    });
    if(overlay) overlay.addEventListener('click', closeSidebar);

    // --- Theme Toggle ---
    const themeBtn = document.getElementById('themeBtn');
    const body = document.body;
    const themeIcon = themeBtn.querySelector('i');
    
    themeBtn.addEventListener('click', () => {
        const isLight = body.classList.toggle('light');
        themeIcon.className = isLight ? 'fa-solid fa-sun' : 'fa-solid fa-moon';
        document.cookie = "bo_theme=" + (isLight ? 'light' : 'dark') + "; path=/; max-age=" + (86400*365);
    });

    // --- Number Animation ---
    function animateNumber(el, newValue) {
        const current = parseFloat(el.textContent.replace(/,/g, '')) || 0;
        if (Math.abs(current - newValue) < 0.01) return;
        
        el.classList.add('updating');
        
        setTimeout(() => {
            const duration = 400;
            const startTime = performance.now();
            const diff = newValue - current;
            
            function step(timestamp) {
                const progress = Math.min((timestamp - startTime) / duration, 1);
                const eased = 1 - Math.pow(1 - progress, 3);
                const value = current + diff * eased;
                
                el.textContent = value.toLocaleString(undefined, {
                    minimumFractionDigits: el.dataset.decimals ? parseInt(el.dataset.decimals) : 0,
                    maximumFractionDigits: el.dataset.decimals ? parseInt(el.dataset.decimals) : 0
                });
                
                if (progress < 1) requestAnimationFrame(step);
                else el.classList.remove('updating');
            }
            requestAnimationFrame(step);
        }, 150);
    }

    // --- AJAX Live Stats ---
    const ajaxUrl = 'dashboard.php?ajax_stats=1&lang=<?= $lang ?>';
    
    async function fetchStats() {
        try {
            const res = await fetch(ajaxUrl);
            const data = await res.json();
            
            if(data.ok) {
                // مبيعات
                animateNumber(document.getElementById('todaySales'), data.todaySales);
                document.querySelector('#todaySales').closest('.stat-card').querySelector('.badge-success').innerHTML = 
                    '<i class="fa-solid fa-receipt"></i> ' + data.todayInvoices + ' <?= $t['stats_invoices'] ?>';
                
                // منتجات
                animateNumber(document.getElementById('totalProducts'), data.totalProducts);
                const prodSub = document.querySelector('#totalProducts').closest('.stat-card').querySelector('.stat-sub');
                if(data.outOfStock > 0) {
                    prodSub.innerHTML = '<span class="stat-badge badge-danger"><i class="fa-solid fa-circle-xmark"></i> ' + data.outOfStock + ' <?= $t['out_of_stock'] ?></span>';
                } else {
                    prodSub.innerHTML = '<span class="stat-badge badge-warning"><i class="fa-solid fa-circle-exclamation"></i> ' + data.lowStockCount + ' <?= $t['low_stock'] ?></span>';
                }
                
                // عملاء
                animateNumber(document.getElementById('totalCustomers'), data.totalCustomers);
                
                // صندوق
                const balEl = document.getElementById('cashBalance');
                balEl.dataset.decimals = '2';
                animateNumber(balEl, data.cashBalance);
                balEl.style.color = data.cashBalance < 0 ? 'var(--danger)' : 'var(--primary)';
                
                // تحديث الوقت
                document.getElementById('lastUpdate').innerHTML = 
                    '<i class="fa-regular fa-clock"></i> <?= $t['updated'] ?>: ' + data.time;
            }
        } catch(err) { 
            console.error('Stats error:', err); 
        }
    }
    
    // تحديث كل 10 ثواني
    setInterval(fetchStats, 10000);
});
</script>
</body>
</html>