<?php
// 1. تفعيل الجلسات والتحقق من تسجيل الدخول
session_start();
require_once 'db.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit;
}

// جلب بيانات الجلسة
$logged_user_id = $_SESSION['user_id'];
$user_role = strtolower($_SESSION['role'] ?? 'user');

// 2. وظيفة التحقق من الصلاحيات
function hasPerm($p) {
    if ($_SESSION['role'] === 'admin') return true; 
    return isset($_SESSION['permissions']) && in_array($p, $_SESSION['permissions']);
}

// جلب بيانات المدير الأساسي للتحقق
$stmt_me = $pdo->prepare("SELECT is_primary FROM users WHERE id = ?");
$stmt_me->execute([$logged_user_id]);
$is_primary = $stmt_me->fetchColumn();

// 3. إدارة اللغة
if (isset($_GET['lang'])) { $_SESSION['lang'] = $_GET['lang']; }
$lang = $_SESSION['lang'] ?? 'ar';
$is_ar = ($lang === 'ar');

// 4. منطق الفلترة (للأدمن فقط)
$f_user = $_GET['f_user'] ?? ''; // الموظف المختار للفلترة

// بناء شرط الاستعلام (المدير يرى الكل أو يفلتر، الموظف يرى نفسه)
// نستخدم "c.created_by" لأننا سنقوم بعمل JOIN مع جدول الزبائن في الاستعلامات اللاحقة
$role_condition = ($user_role === 'admin') ? ($f_user !== '' ? "c.created_by = :uid" : "1=1") : "c.created_by = :uid";
$params = [];
if ($user_role !== 'admin' || $f_user !== '') {
    $params[':uid'] = ($user_role === 'admin') ? $f_user : $logged_user_id;
}

// --- تعريف المتغيرات بقيم افتراضية لمنع أخطاء Undefined ---
$users_list = [];
$customers_count = 0;
$meters_count = 0;
$ampere_subscribers_count = 0;
$total_amperes = 0;
$total_collected = 0;
$total_expenses = 0;
$net_profit = 0;
$total_debt = 0;
$latest_unpaid = [];

// 5. جلب القوائم والبيانات
try {
    // جلب قائمة الموظفين
    if ($user_role === 'admin') {
        $stmt_users = $pdo->query("SELECT id, name FROM users ORDER BY name ASC");
        $users_list = $stmt_users->fetchAll();
    }

    // --- الإحصائيات ---
    
    // عدد المشتركين الكلي
    $st = $pdo->prepare("SELECT COUNT(*) FROM customers c WHERE $role_condition");
    $st->execute($params);
    $customers_count = $st->fetchColumn();

    // عدد العدادات
    $st = $pdo->prepare("SELECT COUNT(*) FROM customers c WHERE c.system_type = 'meter' AND $role_condition");
    $st->execute($params);
    $meters_count = $st->fetchColumn();

    // عدد مشتركي الأمبير
    $st = $pdo->prepare("SELECT COUNT(*) FROM customers c WHERE c.system_type = 'ampere' AND $role_condition");
    $st->execute($params);
    $ampere_subscribers_count = $st->fetchColumn();

    // مجموع الأمبيرات المباعة
    $st = $pdo->prepare("SELECT SUM(c.ampere_qty) FROM customers c WHERE $role_condition");
    $st->execute($params);
    $total_amperes = $st->fetchColumn() ?: 0;

    // إجمالي المقبوضات فعلياً (JOIN مع customers لأن created_by هناك)
    $st_paid = $pdo->prepare("SELECT SUM(b.amount_usd) FROM bills b JOIN customers c ON b.customer_id = c.id WHERE b.status = 'paid' AND $role_condition");
    $st_paid->execute($params);
    $total_collected = (float)$st_paid->fetchColumn() ?: 0;

    // إجمالي المصاريف (جدول expenses لا يحتوي على created_by لذا نجلب الإجمالي العام)
    $st_exp = $pdo->query("SELECT SUM(amount_usd) FROM expenses");
    $total_expenses = (float)$st_exp->fetchColumn() ?: 0;

    // صافي الربح
    $net_profit = $total_collected - $total_expenses;

    // إجمالي الديون المعلقة
    $st_debt = $pdo->prepare("SELECT SUM(b.amount_usd) FROM bills b JOIN customers c ON b.customer_id = c.id WHERE b.status = 'unpaid' AND $role_condition");
    $st_debt->execute($params);
    $total_debt = (float)$st_debt->fetchColumn() ?: 0;
     
    // آخر 10 فواتير غير مدفوعة
    $latest_unpaid_query = "
        SELECT b.*, c.name as customer_name, c.box_no 
        FROM bills b 
        JOIN customers c ON b.customer_id = c.id 
        WHERE b.status = 'unpaid' AND $role_condition
        ORDER BY b.id DESC LIMIT 10";
    $st = $pdo->prepare($latest_unpaid_query);
    $st->execute($params);
    $latest_unpaid = $st->fetchAll() ?: [];

} catch (PDOException $e) {
    // يمكن تفعيل السطر التالي في حال كنت تطور الكود لترى الخطأ
    // die("Error: " . $e->getMessage());
}

$text = [
    'ar' => [
        'title' => 'أسامة إلكتريك',
        'dashboard' => 'لوحة التحكم',
        'customers' => 'المشتركين',
        'meters' => 'العدادات',
        'amperes' => 'الأمبيرات',
        'amp_clients' => 'مشتركي الأمبير', // تمت الإضافة
        'total_amps' => 'مجموع الأمبيرات',
        'readings' => 'القراءات',
        'pricing' => 'التسعير',
        'exchange' => 'سعر الصرف',
        'bills' => 'الفواتير',
        'payments' => 'المقبوضات',
        'reminders' => 'تذكير الواتساب',
        'reports' => 'التقارير والمصاريف',
        'closed_months' => 'الأشهر المغلقة',
        'audit_log' => 'سجل العمليات',
        'backup' => 'النسخ الاحتياطي',
        'users_mgmt' => 'إدارة الموظفين',
        'logout' => 'خروج',
        'debt_title' => 'الديون المعلقة',
        'net_profit_title' => 'صافي الربح الفعلي',
        'quick_actions' => 'إجراءات سريعة',
        'new_customer' => 'مشترك جديد',
        'add_reading' => 'إدخال قراءة',
        'revenue_overview' => 'نظرة عامة على الإداء',
        'unpaid_alert' => 'تنبيه: فواتير بانتظار التحصيل',
        'filter_user' => 'فلترة حسب الموظف',
        'all_users' => 'كل الشبكة',
        'admin_label' => 'مدير نظام',
        'user_label' => 'موظف ميداني',
        'primary_label' => 'مدير أساسي 👑',
        'expenses' => 'المصاريف'
    ],
    'en' => [
        'title' => 'Osama Electric',
        'dashboard' => 'Dashboard',
        'customers' => 'Customers',
        'meters' => 'Meters',
        'amperes' => 'Amperes',
        'amp_clients' => 'Ampere Clients', // Added
        'total_amps' => 'Total Amps',
        'readings' => 'Readings',
        'pricing' => 'Pricing',
        'exchange' => 'Exchange Rate',
        'bills' => 'Bills',
        'payments' => 'Collections',
        'reminders' => 'WhatsApp Alerts',
        'reports' => 'Reports & Expenses',
        'closed_months' => 'Closed Months',
        'audit_log' => 'Audit Log',
        'backup' => 'Backup Vault',
        'users_mgmt' => 'User Management',
        'logout' => 'Logout',
        'debt_title' => 'Outstanding Debt',
        'net_profit_title' => 'Net Profit',
        'quick_actions' => 'Quick Actions',
        'new_customer' => 'New Customer',
        'add_reading' => 'Add Reading',
        'revenue_overview' => 'Performance Overview',
        'unpaid_alert' => 'Alert: Pending Collection',
        'filter_user' => 'Filter by Employee',
        'all_users' => 'Whole Network',
        'admin_label' => 'Administrator',
        'user_label' => 'Field Staff',
        'primary_label' => 'Primary Admin 👑',
        'expenses' => 'Expenses'
    ]
];
?>

<!DOCTYPE html>
<html lang="<?= $lang ?>" dir="<?= $is_ar ? 'rtl' : 'ltr' ?>">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= $text[$lang]['title'] ?> - <?= $text[$lang]['dashboard'] ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;900&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body { font-family: 'Cairo', sans-serif; background-color: #f8fafc; }
        .nav-link { color: #94a3b8; transition: 0.2s; border-radius: 12px; font-size: 0.85rem; font-weight: 600; }
        .nav-link:hover, .nav-link.active { background: #2563eb; color: white; }
        .sidebar::-webkit-scrollbar { width: 4px; }
        .sidebar::-webkit-scrollbar-thumb { background: #1e293b; border-radius: 10px; }
        .stat-card { transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); }
        .stat-card:hover { transform: translateY(-5px); }
        .sidebar { transition: transform 0.3s ease-in-out; }
    </style>
</head>
<body class="text-slate-700">

<div id="sidebarOverlay" class="fixed inset-0 bg-black/50 z-40 hidden md:hidden transition-opacity opacity-0" onclick="toggleSidebar()"></div>

<div class="flex min-h-screen">
    <aside id="sidebar" class="sidebar fixed inset-y-0 start-0 z-50 w-72 bg-[#0f172a] transform <?= $is_ar ? 'translate-x-full' : '-translate-x-full' ?> md:translate-x-0 overflow-y-auto h-full shadow-2xl md:shadow-none">
        <div class="p-8 flex justify-between items-center">
            <h4 class="text-white text-2xl font-black flex items-center gap-3 italic">
                <i class="fas fa-bolt text-blue-500"></i> <?= $text[$lang]['title'] ?>
            </h4>
            <button onclick="toggleSidebar()" class="md:hidden text-slate-400 hover:text-white">
                <i class="fas fa-times text-xl"></i>
            </button>
        </div>
        
        <nav class="mt-2 px-6 pb-20 space-y-1">
            <a href="dashboard.php" class="nav-link active flex items-center p-3.5 gap-3 italic">
                <i class="fas fa-th-large"></i> <span><?= $text[$lang]['dashboard'] ?></span>
            </a>
            
            <div class="text-slate-600 text-[10px] font-black px-3 pt-6 pb-2 tracking-[0.2em] italic uppercase">العمليات والزبائن</div>
            
            <?php if(hasPerm('customers')): ?>
            <a href="customers.php" class="nav-link flex items-center p-3 gap-3">
                <i class="fas fa-users"></i> <span><?= $text[$lang]['customers'] ?></span>
            </a>
            <?php endif; ?>

            <?php if(hasPerm('meters')): ?>
            <a href="meters.php" class="nav-link flex items-center p-3 gap-3">
                <i class="fas fa-microchip"></i> <span><?= $text[$lang]['meters'] ?></span>
            </a>
            <a href="amperes.php" class="nav-link flex items-center p-3 gap-3">
                <i class="fas fa-plug"></i> <span><?= $text[$lang]['amperes'] ?></span>
            </a>
            <?php endif; ?>

            <?php if(hasPerm('readings')): ?>
            <a href="readings.php" class="nav-link flex items-center p-3 gap-3">
                <i class="fas fa-file-signature"></i> <span><?= $text[$lang]['readings'] ?></span>
            </a>
            <?php endif; ?>

            <div class="text-slate-600 text-[10px] font-black px-3 pt-6 pb-2 tracking-[0.2em] italic uppercase">الحسابات والتحصيل</div>
            
            <?php if(hasPerm('pricing')): ?>
            <a href="pricing.php" class="nav-link flex items-center p-3 gap-3">
                <i class="fas fa-tags"></i> <span><?= $text[$lang]['pricing'] ?></span>
            </a>
            <a href="exchange_rate.php" class="nav-link flex items-center p-3 gap-3">
                <i class="fas fa-sync-alt"></i> <span><?= $text[$lang]['exchange'] ?></span>
            </a>
            <?php endif; ?>

            <?php if(hasPerm('bills_gen')): ?>
            <a href="bills.php" class="nav-link flex items-center p-3 gap-3">
                <i class="fas fa-file-invoice-dollar"></i> <span><?= $text[$lang]['bills'] ?></span>
            </a>
            <?php endif; ?>

            <?php if(hasPerm('bills_pay')): ?>
            <a href="payments.php" class="nav-link flex items-center p-3 gap-3">
                <i class="fas fa-wallet"></i> <span><?= $text[$lang]['payments'] ?></span>
            </a>
            <a href="bulk_reminders.php" class="nav-link flex items-center p-3 gap-3">
                <i class="fab fa-whatsapp"></i> <span><?= $text[$lang]['reminders'] ?></span>
            </a>
            <?php endif; ?>

            <div class="text-slate-600 text-[10px] font-black px-3 pt-6 pb-2 tracking-[0.2em] italic uppercase">التقارير والنظام</div>
            
            <?php if(hasPerm('reports')): ?>
            <a href="reports.php" class="nav-link flex items-center p-3 gap-3">
                <i class="fas fa-chart-line"></i> <span><?= $text[$lang]['reports'] ?></span>
            </a>
            <?php endif; ?>

            <?php if(hasPerm('system')): ?>
            <a href="closed_months.php" class="nav-link flex items-center p-3 gap-3">
                <i class="fas fa-calendar-check"></i> <span><?= $text[$lang]['closed_months'] ?></span>
            </a>
            <a href="audit_log.php" class="nav-link flex items-center p-3 gap-3">
                <i class="fas fa-history"></i> <span><?= $text[$lang]['audit_log'] ?></span>
            </a>
            <a href="backup.php" class="nav-link flex items-center p-3 gap-3">
                <i class="fas fa-vault"></i> <span><?= $text[$lang]['backup'] ?></span>
            </a>
            <?php endif; ?>

            <?php if($user_role === 'admin'): ?>
            <a href="users.php" class="nav-link flex items-center p-3 gap-3 border-t border-slate-800 mt-4 pt-4">
                <i class="fas fa-user-shield"></i> <span><?= $text[$lang]['users_mgmt'] ?></span>
            </a>
            <?php endif; ?>

            <div class="pt-10">
                <a href="logout.php" class="nav-link flex items-center p-3 gap-3 text-rose-400 hover:bg-rose-500/10 transition">
                    <i class="fas fa-power-off"></i> <span><?= $text[$lang]['logout'] ?></span>
                </a>
            </div>
        </nav>
    </aside>

    <main class="<?= $is_ar ? 'md:mr-72' : 'md:ml-72' ?> w-full p-4 md:p-8 transition-all duration-300">
        
        <header class="bg-white rounded-[2rem] p-4 md:p-5 shadow-sm mb-8 flex flex-col lg:flex-row justify-between items-center gap-4 border border-slate-100 relative">
            <div class="flex items-center gap-4 w-full lg:w-auto">
                <button onclick="toggleSidebar()" class="md:hidden p-2 text-slate-600 hover:bg-slate-100 rounded-lg">
                    <i class="fas fa-bars text-xl"></i>
                </button>
                <div class="w-12 h-12 bg-blue-600 text-white rounded-2xl flex items-center justify-center text-xl shadow-lg shadow-blue-100 italic font-black shrink-0">
                    <?= strtoupper(substr($_SESSION['name'] ?? 'U', 0, 1)) ?>
                </div>
                <div>
                    <h2 class="text-base md:text-lg font-black text-slate-800 italic"><?= $is_ar ? 'مرحباً،' : 'Welcome,' ?> <?= htmlspecialchars($_SESSION['name'] ?? 'User') ?></h2>
                    <p class="text-[9px] font-bold text-blue-500 uppercase tracking-widest">
                        <?= $is_primary ? $text[$lang]['primary_label'] : ($user_role == 'admin' ? $text[$lang]['admin_label'] : $text[$lang]['user_label']) ?>
                    </p>
                </div>
            </div>

            <div class="flex flex-wrap items-center justify-center gap-4 w-full lg:w-auto">
                <?php if($user_role === 'admin'): ?>
                <form method="GET" class="flex items-center gap-3 bg-slate-50 p-2 rounded-2xl border border-slate-100 w-full md:w-auto">
                    <i class="fas fa-filter text-slate-300 ms-2"></i>
                    <select name="f_user" onchange="this.form.submit()" class="bg-transparent border-none font-black text-xs text-slate-600 outline-none cursor-pointer italic w-full">
                        <option value=""><?= $text[$lang]['all_users'] ?></option>
                        <?php foreach($users_list as $u): ?>
                            <option value="<?= $u['id'] ?>" <?= $f_user == $u['id'] ? 'selected' : '' ?>><?= htmlspecialchars($u['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </form>
                <?php endif; ?>

                <div class="bg-slate-50 p-1.5 rounded-2xl flex border border-slate-100">
                    <a href="?lang=ar&f_user=<?= $f_user ?>" class="px-5 py-1.5 rounded-xl text-xs font-black transition <?= $is_ar ? 'bg-white shadow-sm text-blue-600' : 'text-slate-400' ?>">عربي</a>
                    <a href="?lang=en&f_user=<?= $f_user ?>" class="px-5 py-1.5 rounded-xl text-xs font-black transition <?= !$is_ar ? 'bg-white shadow-sm text-blue-600' : 'text-slate-400' ?>">EN</a>
                </div>
            </div>
        </header>

        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 2xl:grid-cols-7 gap-6 mb-8">
            <div class="stat-card bg-white p-7 rounded-[2.5rem] shadow-sm border border-slate-100 group">
                <div class="w-14 h-14 bg-blue-50 text-blue-600 rounded-2xl flex items-center justify-center mb-5 text-2xl shadow-inner">
                    <i class="fas fa-users"></i>
                </div>
                <p class="text-slate-400 text-[10px] font-black uppercase tracking-widest"><?= $text[$lang]['customers'] ?></p>
                <h3 class="text-3xl font-black mt-2 italic"><?= number_format($customers_count) ?></h3>
            </div>

            <div class="stat-card bg-white p-7 rounded-[2.5rem] shadow-sm border border-slate-100 group border-b-4 border-emerald-500">
                <div class="w-14 h-14 bg-emerald-50 text-emerald-600 rounded-2xl flex items-center justify-center mb-5 text-2xl shadow-inner">
                    <i class="fas fa-tachometer-alt"></i>
                </div>
                <p class="text-slate-400 text-[10px] font-black uppercase tracking-widest"><?= $text[$lang]['meters'] ?></p>
                <h3 class="text-3xl font-black mt-2 italic"><?= number_format($meters_count) ?></h3>
            </div>
            
            <div class="stat-card bg-white p-7 rounded-[2.5rem] shadow-sm border border-slate-100 group border-b-4 border-blue-400">
                <div class="w-14 h-14 bg-blue-50 text-blue-400 rounded-2xl flex items-center justify-center mb-5 text-2xl shadow-inner">
                    <i class="fas fa-user-tag"></i>
                </div>
                <p class="text-slate-400 text-[10px] font-black uppercase tracking-widest"><?= $text[$lang]['amp_clients'] ?></p>
                <h3 class="text-3xl font-black mt-2 italic"><?= number_format($ampere_subscribers_count) ?></h3>
            </div>

            <div class="stat-card bg-white p-7 rounded-[2.5rem] shadow-sm border border-slate-100 group border-b-4 border-yellow-500">
                <div class="w-14 h-14 bg-yellow-50 text-yellow-600 rounded-2xl flex items-center justify-center mb-5 text-2xl shadow-inner">
                    <i class="fas fa-bolt"></i>
                </div>
                <div class="flex justify-between items-end">
                    <div>
                        <p class="text-slate-400 text-[10px] font-black uppercase tracking-widest"><?= $text[$lang]['amperes'] ?></p>
                    </div>
                    <div class="text-end">
                         <p class="text-slate-400 text-[9px] font-bold"><?= $text[$lang]['total_amps'] ?></p>
                         <span class="text-yellow-600 font-black text-xl" dir="ltr"><?= number_format($total_amperes, 0) ?> A</span>
                    </div>
                </div>
            </div>

            <div class="stat-card bg-white p-7 rounded-[2.5rem] shadow-sm border border-slate-100 group">
                <div class="w-14 h-14 bg-rose-50 text-rose-600 rounded-2xl flex items-center justify-center mb-5 text-2xl shadow-inner">
                    <i class="fas fa-file-invoice-dollar"></i>
                </div>
                <p class="text-slate-400 text-[10px] font-black uppercase tracking-widest"><?= $text[$lang]['debt_title'] ?></p>
                <h3 class="text-3xl font-black mt-2 text-rose-600 italic">$<?= number_format($total_debt, 0) ?></h3>
            </div>

            <div class="stat-card bg-slate-900 p-7 rounded-[2.5rem] shadow-xl text-white group relative overflow-hidden">
                <i class="fas fa-coins absolute right-[-10px] bottom-[-10px] text-7xl opacity-5"></i>
                <div class="w-14 h-14 bg-emerald-500 text-white rounded-2xl flex items-center justify-center mb-5 text-2xl shadow-inner">
                    <i class="fas fa-wallet"></i>
                </div>
                <p class="text-slate-400 text-[10px] font-black uppercase tracking-widest"><?= $text[$lang]['net_profit_title'] ?></p>
                <h3 class="text-3xl font-black mt-2 text-emerald-400 italic">$<?= number_format($net_profit, 0) ?></h3>
            </div>

            <div class="stat-card bg-white p-7 rounded-[2.5rem] shadow-sm border border-slate-100 group">
                <div class="w-14 h-14 bg-orange-50 text-orange-600 rounded-2xl flex items-center justify-center mb-5 text-2xl shadow-inner">
                    <i class="fas fa-shopping-cart"></i>
                </div>
                <p class="text-slate-400 text-[10px] font-black uppercase tracking-widest"><?= $text[$lang]['expenses'] ?></p>
                <h3 class="text-3xl font-black mt-2 text-orange-600 italic">$<?= number_format($total_expenses, 0) ?></h3>
            </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <div class="lg:col-span-2 bg-white p-10 rounded-[3rem] shadow-sm border border-slate-100">
                <div class="flex justify-between items-center mb-8">
                    <h5 class="font-black text-slate-800 text-lg flex items-center gap-3 italic">
                        <i class="fas fa-chart-line text-blue-600"></i> <?= $text[$lang]['revenue_overview'] ?>
                    </h5>
                </div>
                <div class="h-[320px]">
                    <canvas id="revenueChart"></canvas>
                </div>
            </div>

            <div class="bg-white p-10 rounded-[3rem] shadow-sm border border-slate-100">
                <h5 class="font-black text-slate-800 mb-8 italic"><?= $text[$lang]['quick_actions'] ?></h5>
                <div class="space-y-4">
                    <?php if(hasPerm('customers')): ?>
                    <a href="customers.php" class="flex items-center justify-between p-5 bg-blue-600 text-white rounded-3xl hover:bg-black transition group font-black shadow-lg shadow-blue-100 italic">
                        <span><?= $text[$lang]['new_customer'] ?></span>
                        <i class="fas fa-user-plus group-hover:rotate-12 transition opacity-50"></i>
                    </a>
                    <?php endif; ?>
                    
                    <?php if(hasPerm('readings')): ?>
                    <a href="readings.php" class="flex items-center justify-between p-5 bg-slate-50 text-slate-700 rounded-3xl hover:bg-slate-100 transition font-black border border-slate-100 italic">
                        <span><?= $text[$lang]['add_reading'] ?></span>
                        <i class="fas fa-pen-nib text-slate-300"></i>
                    </a>
                    <?php endif; ?>

                    <?php if(hasPerm('reports')): ?>
                    <a href="reports.php" class="flex items-center justify-between p-5 bg-emerald-50 text-emerald-700 rounded-3xl hover:bg-emerald-100 transition font-black border border-emerald-100 italic">
                        <span><?= $text[$lang]['reports'] ?></span>
                        <i class="fas fa-file-chart-pie text-emerald-200"></i>
                    </a>
                    <?php endif; ?>
                </div>
                
                <div class="mt-8 p-6 bg-slate-900 rounded-3xl text-white">
                    <p class="text-[10px] font-black text-blue-400 uppercase mb-2"><?= $is_ar ? 'النطاق الحالي' : 'Current Scope' ?></p>
                    <p class="text-[11px] font-bold leading-relaxed opacity-60 italic">
                        <?= $f_user ? ($is_ar ? "عرض بيانات موظف محدد" : "Displaying specific employee") : ($is_ar ? "عرض بيانات كامل الشبكة" : "Displaying whole network") ?>
                    </p>
                </div>
            </div>
        </div>

        <div class="mt-8 bg-white rounded-[3rem] shadow-sm border border-slate-100 overflow-hidden">
            <div class="p-8 border-b border-slate-50 flex justify-between items-center bg-slate-50/50">
                <h5 class="font-black text-slate-800 italic"><?= $text[$lang]['unpaid_alert'] ?></h5>
                <a href="bills.php?f_status=unpaid" class="text-blue-600 text-[10px] font-black uppercase tracking-widest hover:underline italic"><?= $is_ar ? 'عرض كافة الديون' : 'View All Debts' ?></a>
            </div>
            <div class="overflow-x-auto">
                <table class="w-full text-<?= $is_ar ? 'right' : 'left' ?>">
                    <thead class="bg-slate-50 text-slate-400 text-[10px] font-black uppercase tracking-widest border-b">
                        <tr>
                            <th class="p-6">المشترك</th>
                            <th class="p-6 text-center">العلبة</th>
                            <th class="p-6 text-center">رقم الفاتورة</th>
                            <th class="p-6 text-center">المبلغ المستحق</th>
                            <th class="p-6 text-center">العمليات</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-50">
                        <?php if(empty($latest_unpaid)): ?>
                            <tr><td colspan="5" class="p-16 text-center text-slate-300 italic font-black">لا توجد ديون معلقة حالياً</td></tr>
                        <?php else: ?>
                            <?php foreach($latest_unpaid as $lb): ?>
                            <tr class="hover:bg-blue-50/10 transition group italic font-bold text-sm">
                                <td class="p-6">
                                    <span class="font-black text-slate-800"><?= htmlspecialchars($lb['customer_name']) ?></span>
                                </td>
                                <td class="p-6 text-center">
                                    <span class="bg-slate-100 text-slate-500 px-3 py-1 rounded-lg text-[10px] font-black">Box: <?= htmlspecialchars($lb['box_no'] ?: '---') ?></span>
                                </td>
                                <td class="p-6 text-center font-mono text-blue-600 text-xs">#<?= htmlspecialchars($lb['bill_number']) ?></td>
                                <td class="p-6 text-center font-black text-rose-500 text-lg">$<?= number_format($lb['amount_usd'], 2) ?></td>
                                <td class="p-6 text-center">
                                    <a href="bills.php?pay_id=<?= $lb['id'] ?>" class="bg-emerald-50 text-emerald-600 px-6 py-2 rounded-xl text-[10px] font-black hover:bg-emerald-600 hover:text-white transition shadow-sm"><?= $is_ar ? 'تحصيل' : 'Collect' ?></a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="text-center text-slate-300 text-[10px] font-black uppercase tracking-[0.5em] mt-12 mb-8 italic">
            Osama Electric Security Center
        </div>

    </main>
</div>

<script>
    const ctx = document.getElementById('revenueChart').getContext('2d');
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: ['Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov'],
            datasets: [{
                label: 'Financial Performance',
                data: [450, 590, 800, 810, 950, 1300],
                borderColor: '#2563eb',
                borderWidth: 4,
                pointBackgroundColor: '#fff',
                pointBorderColor: '#2563eb',
                tension: 0.4,
                fill: true,
                backgroundColor: 'rgba(37, 99, 235, 0.05)'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: { legend: { display: false } },
            scales: {
                y: { grid: { display: true, color: '#f8fafc' }, ticks: { font: { family: 'Cairo', weight: 'bold' } } },
                x: { grid: { display: false }, ticks: { font: { family: 'Cairo', weight: 'bold' } } }
            }
        }
    });

    function toggleSidebar() {
        const sidebar = document.getElementById('sidebar');
        const overlay = document.getElementById('sidebarOverlay');
        const isAr = document.documentElement.dir === 'rtl';

        if (sidebar.classList.contains('translate-x-full') || sidebar.classList.contains('-translate-x-full')) {
            sidebar.classList.remove('translate-x-full', '-translate-x-full');
            overlay.classList.remove('hidden');
            setTimeout(() => { overlay.classList.remove('opacity-0'); }, 10);
        } else {
            if (isAr) sidebar.classList.add('translate-x-full');
            else sidebar.classList.add('-translate-x-full');
            overlay.classList.add('opacity-0');
            setTimeout(() => { overlay.classList.add('hidden'); }, 300);
        }
    }
</script>

</body>
</html>