<?php
session_start();

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

require_once 'db.php';

 $logged_user_id = $_SESSION['user_id'];
 $stmt_me = $pdo->prepare("SELECT role, is_primary FROM users WHERE id = ?");
 $stmt_me->execute([$logged_user_id]);
 $me = $stmt_me->fetch();

 $user_role = strtolower($me['role'] ?? 'user');
 $is_primary = (int)($me['is_primary'] ?? 0);
 $can_manage_all = ($user_role === 'admin' || $is_primary === 1);

 $lang = $_SESSION['lang'] ?? 'ar';
 $texts = [
    'ar' => [
        'title' => 'التقارير والمصاريف | أسامة إلكتريك',
        'header' => 'المركز المالي المتطور',
        'sub_header' => 'تحليل الأرباح، المصاريف، وتحصيل الديون',
        'add_expense' => 'تسجيل مصروف جديد',
        'edit_expense' => 'تعديل المصروف',
        'net_profit' => 'صافي الربح الفعلي',
        'collected' => 'إجمالي المحصل',
        'expenses' => 'إجمالي المصاريف',
        'unpaid_bills' => 'فواتير معلقة',
        'old_debts' => 'ديون قديمة',
        'insurance' => 'التأمينات المحفوظة',
        'active_cust' => 'الزبائن النشطين',
        'collection_rate' => 'نسبة التحصيل',
        'total_debt' => 'إجمالي الديون المعلقة',
        'category' => 'التصنيف',
        'amount' => 'المبلغ',
        'date' => 'التاريخ',
        'from_date' => 'من تاريخ',
        'to_date' => 'إلى تاريخ',
        'save' => 'حفظ المصروف',
        'update' => 'تحديث المصروف',
        'history_expenses' => 'سجل المصاريف',
        'top_debtors' => 'أكبر 10 مديونين',
        'home' => 'الرئيسية',
        'all_users' => 'كل الموظفين',
        'filter_btn' => 'تحديث التقرير',
        'print' => 'طباعة التقرير',
        'no_expenses' => 'لا توجد مصاريف في الفترة المحددة',
        'no_debtors' => 'لا توجد ديون معلقة',
        'confirm_delete' => 'حذف هذا المصروف نهائياً؟',
        'success_add' => 'تم تسجيل المصروف بنجاح',
        'success_edit' => 'تم تعديل المصروف بنجاح',
        'success_delete' => 'تم حذف المصروف بنجاح',
        'all_categories' => 'كل التصنيفات',
        'income_vs_expenses' => 'الإيرادات مقابل المصاريف',
        'expense_breakdown' => 'توزيع المصاريف',
        'last_6_months' => 'آخر 6 أشهر',
        'today' => 'اليوم',
        'this_week' => 'هذا الأسبوع',
        'this_month' => 'هذا الشهر',
        'this_year' => 'هذا العام',
        'all_time' => 'كل الأوقات',
        'notes' => 'ملاحظات',
        'by' => 'بواسطة',
        'operations' => 'العمليات',
        'subscriber' => 'المشترك',
        'old_balance' => 'رصيد قديم',
        'unpaid_bills_col' => 'فواتير غير مدفوعة',
        'total_due' => 'المجموع المستحق',
        'formula' => 'المعادلة: المحصل - المصاريف المصروفة',
        'period_note' => 'المصاريف محددة بالفترة • الإيرادات والديون إجمالية'
    ]
];

try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `expenses` (
        `id` INT AUTO_INCREMENT PRIMARY KEY,
        `title` VARCHAR(255) NOT NULL,
        `category` ENUM('fuel','maintenance','salaries','rent','other') DEFAULT 'other',
        `amount_usd` DECIMAL(12,2) NOT NULL,
        `expense_date` DATE NOT NULL,
        `notes` TEXT NULL,
        `created_by` INT NULL,
        `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");
    $pdo->exec("ALTER TABLE `expenses` ADD COLUMN IF NOT EXISTS `created_by` INT NULL AFTER `notes`");
} catch (PDOException $e) {}

 $message = '';
 $msg_type = 'success';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_expense'])) {
    $exp_id = $_POST['exp_id'] ?? null;
    $exp_title = trim($_POST['exp_title']);
    $exp_category = $_POST['exp_category'];
    $exp_amount = (float)$_POST['exp_amount'];
    $exp_date = $_POST['exp_date'];
    $exp_notes = trim($_POST['exp_notes']);

    try {
        if ($exp_id) {
            $check_sql = $can_manage_all ? "SELECT id FROM expenses WHERE id = ?" : "SELECT id FROM expenses WHERE id = ? AND created_by = ?";
            $check_params = $can_manage_all ? [$exp_id] : [$exp_id, $logged_user_id];
            $chk = $pdo->prepare($check_sql);
            $chk->execute($check_params);
            if ($chk->rowCount() > 0) {
                $stmt = $pdo->prepare("UPDATE expenses SET title=?, category=?, amount_usd=?, expense_date=?, notes=? WHERE id=?");
                $stmt->execute([$exp_title, $exp_category, $exp_amount, $exp_date, $exp_notes, $exp_id]);
                $message = $texts['ar']['success_edit'];
            } else {
                $message = "ليس لديك صلاحية لتعديل هذا القيد.";
                $msg_type = 'error';
            }
        } else {
            $stmt = $pdo->prepare("INSERT INTO expenses (title, category, amount_usd, expense_date, notes, created_by) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([$exp_title, $exp_category, $exp_amount, $exp_date, $exp_notes, $logged_user_id]);
            $message = $texts['ar']['success_add'];
        }
    } catch (PDOException $e) {
        $message = "خطأ: " . $e->getMessage();
        $msg_type = 'error';
    }
}

if (isset($_GET['delete_exp'])) {
    $del_id = $_GET['delete_exp'];
    $check_sql = $can_manage_all ? "DELETE FROM expenses WHERE id = ?" : "DELETE FROM expenses WHERE id = ? AND created_by = ?";
    $check_params = $can_manage_all ? [$del_id] : [$del_id, $logged_user_id];
    $pdo->prepare($check_sql)->execute($check_params);
    $message = $texts['ar']['success_delete'];
}

 $f_user = $_GET['f_user'] ?? '';
 $f_from = $_GET['f_from'] ?? '';
 $f_to = $_GET['f_to'] ?? '';
 $f_cat = $_GET['f_cat'] ?? '';

 $role_simple = $can_manage_all ? ($f_user ? "created_by = :uid" : "1=1") : "created_by = :uid";
 $role_joined = $can_manage_all ? ($f_user ? "e.created_by = :uid" : "1=1") : "e.created_by = :uid";
 $role_cust = $can_manage_all ? ($f_user ? "c.created_by = :uid" : "1=1") : "c.created_by = :uid";

// ✅ إصلاح باراميترات قاعدة البيانات (فصل باراميترات التاريخ والتصنيف عن الباراميترات الأساسية)
 $params_basic = [];
if (!$can_manage_all || $f_user !== '') {
    $params_basic[':uid'] = $can_manage_all ? (int)$f_user : $logged_user_id;
}

 $date_cond = "";
 $cat_cond = "";
 $params_exp_full = $params_basic;

if ($f_from) { $date_cond .= " AND expense_date >= :f_from"; $params_exp_full[':f_from'] = $f_from; }
if ($f_to) { $date_cond .= " AND expense_date <= :f_to"; $params_exp_full[':f_to'] = $f_to; }
if ($f_cat) { $cat_cond .= " AND category = :f_cat"; $params_exp_full[':f_cat'] = $f_cat; }

 $full_exp_where = "$role_simple $date_cond $cat_cond";

// أ. حساب الإيرادات (استخدام $params_basic فقط)
 $stmt = $pdo->prepare("SELECT COALESCE(SUM(amount_usd),0) FROM bills WHERE status='paid' AND customer_id IN (SELECT id FROM customers c WHERE $role_cust)");
 $stmt->execute($params_basic);
 $total_paid = (float)$stmt->fetchColumn();

// ب. حساب الفواتير غير المدفوعة
 $stmt = $pdo->prepare("SELECT COALESCE(SUM(amount_usd),0) FROM bills WHERE status='unpaid' AND customer_id IN (SELECT id FROM customers c WHERE $role_cust)");
 $stmt->execute($params_basic);
 $total_unpaid = (float)$stmt->fetchColumn();

// ج. حساب المصاريف (استخدام $params_exp_full ليشمل التواريخ والتصنيفات)
 $stmt = $pdo->prepare("SELECT COALESCE(SUM(amount_usd),0) FROM expenses WHERE $full_exp_where");
 $stmt->execute($params_exp_full);
 $total_expenses = (float)$stmt->fetchColumn();

// د. حساب ديون المشتركين القديمة
 $stmt = $pdo->prepare("SELECT COALESCE(SUM(old_balance),0) FROM customers c WHERE $role_cust");
 $stmt->execute($params_basic);
 $old_debts = (float)$stmt->fetchColumn();

// هـ. حساب التأمينات
 $stmt = $pdo->prepare("SELECT COALESCE(SUM(insurance),0) FROM customers c WHERE $role_cust");
 $stmt->execute($params_basic);
 $total_insurance = (float)$stmt->fetchColumn();

// و. عدد الزبائن النشطين
 $stmt = $pdo->prepare("SELECT COUNT(*) FROM customers c WHERE status=1 AND $role_cust");
 $stmt->execute($params_basic);
 $active_customers = (int)$stmt->fetchColumn();

 $total_bills = $total_paid + $total_unpaid;
 $collection_rate = $total_bills > 0 ? round(($total_paid / $total_bills) * 100, 1) : 0;
 $net_profit = $total_paid - $total_expenses;
 $total_debt = $total_unpaid + $old_debts;

// بيانات الرسم البياني الشريطي (آخر 6 أشهر)
 $chart_labels = [];
 $chart_expenses_data = [];
 $chart_income_data = [];
 $month_ar = ['01'=>'يناير','02'=>'فبراير','03'=>'مارس','04'=>'أبريل','05'=>'مايو','06'=>'يونيو','07'=>'يوليو','08'=>'أغسطس','09'=>'سبتمبر','10'=>'أكتوبر','11'=>'نوفمبر','12'=>'ديسمبر'];

for ($i = 5; $i >= 0; $i--) {
    $d = new DateTime("first day of -$i months");
    $key = $d->format('Y-m');
    $chart_labels[] = ($month_ar[$d->format('m')] ?? $d->format('m')) . ' ' . $d->format('Y');
    $chart_expenses_data[$key] = 0;
    $chart_income_data[$key] = 0;
}

 $me_q = "SELECT DATE_FORMAT(expense_date,'%Y-%m') as m, SUM(amount_usd) as t FROM expenses WHERE $role_simple AND expense_date >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH) GROUP BY m";
 $stmt_me = $pdo->prepare($me_q);
 $stmt_me->execute($params_basic);
foreach ($stmt_me->fetchAll() as $row) {
    if (isset($chart_expenses_data[$row['m']])) $chart_expenses_data[$row['m']] = (float)$row['t'];
}

try {
    $mi_q = "SELECT DATE_FORMAT(bill_date,'%Y-%m') as m, SUM(amount_usd) as t FROM bills WHERE status='paid' AND customer_id IN (SELECT id FROM customers c WHERE $role_cust) AND bill_date >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH) GROUP BY m";
    $stmt_mi = $pdo->prepare($mi_q);
    $stmt_mi->execute($params_basic);
    foreach ($stmt_mi->fetchAll() as $row) {
        if (isset($chart_income_data[$row['m']])) $chart_income_data[$row['m']] = (float)$row['t'];
    }
} catch (Exception $e) {}

 $chart_exp_final = [];
 $chart_inc_final = [];
foreach ($chart_expenses_data as $k => $v) {
    $chart_exp_final[] = $v;
    $chart_inc_final[] = $chart_income_data[$k];
}

// توزيع المصاريف للرسم الدائري
 $bd_q = "SELECT category, SUM(amount_usd) as total FROM expenses WHERE $full_exp_where GROUP BY category";
 $stmt_bd = $pdo->prepare($bd_q);
 $stmt_bd->execute($params_exp_full);
 $expense_breakdown = $stmt_bd->fetchAll();

// قائمة المصاريف الأخيرة
 $list_q = "SELECT e.*, u.name as creator_name FROM expenses e LEFT JOIN users u ON e.created_by = u.id WHERE $role_joined $date_cond $cat_cond ORDER BY e.expense_date DESC, e.id DESC LIMIT 50";
 $stmt_list = $pdo->prepare($list_q);
 $stmt_list->execute($params_exp_full);
 $recent_expenses = $stmt_list->fetchAll();

// أكبر 10 مديونين
 $debtors_q = "SELECT c.name, c.sub_no, c.old_balance, c.phone,
              (SELECT COALESCE(SUM(amount_usd),0) FROM bills WHERE customer_id=c.id AND status='unpaid') as bills_debt
              FROM customers c WHERE $role_cust
              ORDER BY (c.old_balance + (SELECT COALESCE(SUM(amount_usd),0) FROM bills WHERE customer_id=c.id AND status='unpaid')) DESC LIMIT 10";
 $stmt_debtors = $pdo->prepare($debtors_q);
 $stmt_debtors->execute($params_basic);
 $top_debtors = $stmt_debtors->fetchAll();

 $users_list = $can_manage_all ? $pdo->query("SELECT id, name FROM users ORDER BY name ASC")->fetchAll() : [];

 $cat_names = ['fuel'=>'مازوت','maintenance'=>'صيانة','salaries'=>'رواتب','rent'=>'إيجار','other'=>'أخرى'];
 $cat_colors = ['fuel'=>'#f59e0b','maintenance'=>'#3b82f6','salaries'=>'#10b981','rent'=>'#ef4444','other'=>'#8b5cf6'];
 $cat_icons = ['fuel'=>'fa-gas-pump','maintenance'=>'fa-wrench','salaries'=>'fa-users','rent'=>'fa-building','other'=>'fa-ellipsis'];
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= $texts['ar']['title'] ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body { font-family: 'Cairo', sans-serif; background-color: #f1f5f9; }
        .profit-card { background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%); }
        .stat-card { transition: all 0.3s cubic-bezier(0.4,0,0.2,1); }
        .stat-card:hover { transform: translateY(-4px); box-shadow: 0 20px 40px -12px rgba(0,0,0,0.12); }
        .quick-pill { transition: all 0.2s; }
        .quick-pill:hover { transform: scale(1.05); }
        .quick-pill.active-pill { box-shadow: 0 0 0 3px rgba(37,99,235,0.3); }
        .modal-body { max-height: calc(100vh - 200px); overflow-y: auto; }
        .modal-body::-webkit-scrollbar { width: 6px; }
        .modal-body::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 10px; }
        @keyframes modalIn { from { opacity:0; transform:scale(0.95) translateY(20px); } to { opacity:1; transform:scale(1) translateY(0); } }
        @media print {
            .no-print { display: none !important; }
            body { background: white; }
            * { box-shadow: none !important; }
            .stat-card:hover { transform: none; }
        }
        @media (max-width: 768px) {
            .kpi-grid { grid-template-columns: repeat(2, 1fr) !important; }
            .chart-grid { grid-template-columns: 1fr !important; }
            .table-grid { grid-template-columns: 1fr !important; }
        }
    </style>
</head>
<body class="pb-20 text-slate-800">

<div class="container mx-auto px-4 py-8 max-w-7xl">
    
    <div class="bg-white p-8 rounded-[2.5rem] shadow-sm mb-8 flex flex-col md:flex-row justify-between items-center gap-6 border border-slate-100">
        <div class="flex items-center gap-5">
            <div class="w-16 h-16 bg-blue-600 text-white rounded-2xl flex items-center justify-center text-3xl shadow-xl shadow-blue-100">
                <i class="fas fa-chart-pie"></i>
            </div>
            <div>
                <h1 class="text-2xl font-black text-slate-800 italic"><?= $texts['ar']['header'] ?></h1>
                <p class="text-sm text-slate-400 font-bold italic"><?= $texts['ar']['sub_header'] ?></p>
            </div>
        </div>
        <div class="flex gap-3 flex-wrap justify-center no-print">
            <button onclick="openModal()" class="bg-rose-600 hover:bg-black text-white px-8 py-3 rounded-2xl font-black transition shadow-lg shadow-rose-100 italic">
                <i class="fas fa-plus-circle ml-2"></i><?= $texts['ar']['add_expense'] ?>
            </button>
            <button onclick="window.print()" class="bg-slate-800 hover:bg-black text-white px-6 py-3 rounded-2xl font-black transition shadow-lg italic">
                <i class="fas fa-print ml-2"></i><?= $texts['ar']['print'] ?>
            </button>
            <a href="dashboard.php" class="bg-slate-100 text-slate-600 px-8 py-3 rounded-2xl font-bold hover:bg-slate-200 transition italic">
                <i class="fas fa-arrow-right ml-2"></i><?= $texts['ar']['home'] ?>
            </a>
        </div>
    </div>

    <div class="bg-white p-6 rounded-[2rem] shadow-sm mb-6 border border-slate-100 no-print">
        <form id="filterForm" method="GET" class="space-y-4">
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-4 items-end">
                <div>
                    <label class="block text-[10px] font-black text-slate-400 mb-2 uppercase tracking-widest"><?= $texts['ar']['from_date'] ?></label>
                    <input type="date" name="f_from" id="f_from" value="<?= htmlspecialchars($f_from) ?>" class="w-full p-3.5 bg-slate-50 rounded-xl border-none font-bold outline-none focus:ring-2 focus:ring-blue-600">
                </div>
                <div>
                    <label class="block text-[10px] font-black text-slate-400 mb-2 uppercase tracking-widest"><?= $texts['ar']['to_date'] ?></label>
                    <input type="date" name="f_to" id="f_to" value="<?= htmlspecialchars($f_to) ?>" class="w-full p-3.5 bg-slate-50 rounded-xl border-none font-bold outline-none focus:ring-2 focus:ring-blue-600">
                </div>
                <div>
                    <label class="block text-[10px] font-black text-slate-400 mb-2 uppercase"><?= $texts['ar']['category'] ?></label>
                    <select name="f_cat" class="w-full p-3.5 bg-slate-50 rounded-xl border-none font-bold cursor-pointer outline-none">
                        <option value=""><?= $texts['ar']['all_categories'] ?></option>
                        <?php foreach($cat_names as $k => $v): ?>
                            <option value="<?= $k ?>" <?= $f_cat == $k ? 'selected' : '' ?>><?= $v ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php if($can_manage_all): ?>
                <div>
                    <label class="block text-[10px] font-black text-blue-600 mb-2 uppercase">الموظف</label>
                    <select name="f_user" class="w-full p-3.5 bg-blue-50/50 rounded-xl border-none font-black text-blue-700 outline-none cursor-pointer">
                        <option value=""><?= $texts['ar']['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>
                </div>
                <?php endif; ?>
                <button type="submit" class="bg-slate-800 text-white p-3.5 rounded-xl font-black shadow-lg hover:bg-black transition flex justify-center items-center">
                    <i class="fas fa-sync-alt ml-2"></i><?= $texts['ar']['filter_btn'] ?>
                </button>
            </div>
            <div class="flex flex-wrap gap-2 items-center pt-2 border-t border-slate-50">
                <span class="text-[10px] font-black text-slate-400 uppercase ml-1"><i class="fas fa-clock ml-1"></i>سريع:</span>
                <button type="button" onclick="setQuickDate('today')" class="quick-pill px-4 py-1.5 rounded-full text-[11px] font-black uppercase <?php if($f_from == date('Y-m-d') && $f_to == date('Y-m-d')): ?>bg-blue-600 text-white active-pill<?php else: ?>bg-white text-slate-500 border border-slate-200 hover:bg-blue-50<?php endif; ?> shadow-sm"><?= $texts['ar']['today'] ?></button>
                <button type="button" onclick="setQuickDate('week')" class="quick-pill px-4 py-1.5 rounded-full text-[11px] font-black uppercase <?php if($f_from == date('Y-m-d', strtotime('-7 days')) && $f_to == date('Y-m-d')): ?>bg-blue-600 text-white active-pill<?php else: ?>bg-white text-slate-500 border border-slate-200 hover:bg-blue-50<?php endif; ?> shadow-sm"><?= $texts['ar']['this_week'] ?></button>
                <button type="button" onclick="setQuickDate('month')" class="quick-pill px-4 py-1.5 rounded-full text-[11px] font-black uppercase <?php if($f_from == date('Y-m-01') && $f_to == date('Y-m-d')): ?>bg-blue-600 text-white active-pill<?php else: ?>bg-white text-slate-500 border border-slate-200 hover:bg-blue-50<?php endif; ?> shadow-sm"><?= $texts['ar']['this_month'] ?></button>
                <button type="button" onclick="setQuickDate('year')" class="quick-pill px-4 py-1.5 rounded-full text-[11px] font-black uppercase <?php if($f_from == date('Y-01-01') && $f_to == date('Y-m-d')): ?>bg-blue-600 text-white active-pill<?php else: ?>bg-white text-slate-500 border border-slate-200 hover:bg-blue-50<?php endif; ?> shadow-sm"><?= $texts['ar']['this_year'] ?></button>
                <button type="button" onclick="setQuickDate('all')" class="quick-pill px-4 py-1.5 rounded-full text-[11px] font-black uppercase <?php if(empty($f_from) && empty($f_to)): ?>bg-blue-600 text-white active-pill<?php else: ?>bg-white text-slate-500 border border-slate-200 hover:bg-blue-50<?php endif; ?> shadow-sm"><?= $texts['ar']['all_time'] ?></button>
            </div>
        </form>
    </div>

    <?php if($message): ?>
        <div id="msgBanner" class="<?php if($msg_type == 'success'): ?>bg-emerald-500<?php else: ?>bg-rose-500<?php endif; ?> text-white p-5 rounded-2xl mb-6 font-bold shadow-lg flex items-center justify-between gap-3 italic">
            <span class="flex items-center gap-3">
                <i class="fas <?php if($msg_type == 'success'): ?>fa-check-circle<?php else: ?>fa-exclamation-triangle<?php endif; ?> text-xl"></i><?= $message ?>
            </span>
            <button onclick="document.getElementById('msgBanner').remove()" class="hover:rotate-90 transition-transform text-xl">&times;</button>
        </div>
    <?php endif; ?>

    <div class="kpi-grid grid grid-cols-2 md:grid-cols-4 gap-4 mb-8" style="display:grid;">
        <div class="stat-card bg-white p-5 rounded-[2rem] border border-slate-100 shadow-sm">
            <p class="text-[9px] font-black text-blue-500 uppercase mb-1"><i class="fas fa-hand-holding-dollar ml-1"></i><?= $texts['ar']['collected'] ?></p>
            <h3 class="text-2xl font-black text-blue-600 italic">$<?= number_format($total_paid, 2) ?></h3>
        </div>
        <div class="stat-card bg-white p-5 rounded-[2rem] border border-slate-100 shadow-sm">
            <p class="text-[9px] font-black text-rose-500 uppercase mb-1"><i class="fas fa-receipt ml-1"></i><?= $texts['ar']['expenses'] ?></p>
            <h3 class="text-2xl font-black text-rose-500 italic">$<?= number_format($total_expenses, 2) ?></h3>
        </div>
        <div class="stat-card bg-white p-5 rounded-[2rem] border border-slate-100 shadow-sm">
            <p class="text-[9px] font-black text-amber-500 uppercase mb-1"><i class="fas fa-file-invoice-dollar ml-1"></i><?= $texts['ar']['unpaid_bills'] ?></p>
            <h3 class="text-2xl font-black text-amber-600 italic">$<?= number_format($total_unpaid, 2) ?></h3>
        </div>
        <div class="stat-card bg-white p-5 rounded-[2rem] border border-slate-100 shadow-sm">
            <p class="text-[9px] font-black text-slate-400 uppercase mb-1"><i class="fas fa-money-bill-transfer ml-1"></i><?= $texts['ar']['old_debts'] ?></p>
            <h3 class="text-2xl font-black text-slate-500 italic">$<?= number_format($old_debts, 2) ?></h3>
        </div>
        <div class="stat-card bg-white p-5 rounded-[2rem] border border-slate-100 shadow-sm">
            <p class="text-[9px] font-black text-emerald-500 uppercase mb-1"><i class="fas fa-shield-halved ml-1"></i><?= $texts['ar']['insurance'] ?></p>
            <h3 class="text-2xl font-black text-emerald-600 italic">$<?= number_format($total_insurance, 2) ?></h3>
        </div>
        <div class="stat-card bg-white p-5 rounded-[2rem] border border-slate-100 shadow-sm">
            <p class="text-[9px] font-black text-indigo-500 uppercase mb-1"><i class="fas fa-users ml-1"></i><?= $texts['ar']['active_cust'] ?></p>
            <h3 class="text-2xl font-black text-indigo-600 italic"><?= number_format($active_customers) ?></h3>
        </div>
        <div class="stat-card bg-white p-5 rounded-[2rem] border border-slate-100 shadow-sm">
            <p class="text-[9px] font-black text-cyan-500 uppercase mb-1"><i class="fas fa-percentage ml-1"></i><?= $texts['ar']['collection_rate'] ?></p>
            <h3 class="text-2xl font-black <?php if($collection_rate >= 70): ?>text-emerald-600<?php elseif($collection_rate >= 40): ?>text-amber-600<?php else: ?>text-rose-600<?php endif; ?> italic"><?= $collection_rate ?>%</h3>
        </div>
        <div class="stat-card profit-card p-5 rounded-[2rem] text-white shadow-lg border-b-4 border-emerald-500">
            <p class="text-[9px] font-black text-emerald-400 uppercase mb-1"><i class="fas fa-coins ml-1"></i><?= $texts['ar']['net_profit'] ?></p>
            <h3 class="text-2xl font-black italic <?php if($net_profit >= 0): ?>text-emerald-400<?php else: ?>text-rose-400<?php endif; ?>"><?php if($net_profit >= 0): ?>+<?php endif; ?>$<?= number_format($net_profit, 2) ?></h3>
        </div>
    </div>

    <div class="chart-grid grid grid-cols-1 lg:grid-cols-5 gap-6 mb-8" style="display:grid;">
        <div class="lg:col-span-3 bg-white p-8 rounded-[3rem] shadow-sm border border-slate-100">
            <div class="flex justify-between items-center mb-6">
                <h4 class="font-black text-slate-800 italic"><i class="fas fa-chart-bar text-blue-500 ml-2"></i><?= $texts['ar']['income_vs_expenses'] ?></h4>
                <span class="text-[9px] font-black text-slate-300 uppercase"><?= $texts['ar']['last_6_months'] ?></span>
            </div>
            <div class="h-72">
                <canvas id="barChart"></canvas>
            </div>
        </div>
        <div class="lg:col-span-2 bg-white p-8 rounded-[3rem] shadow-sm border border-slate-100">
            <h4 class="font-black text-slate-800 mb-6 italic"><i class="fas fa-chart-pie text-orange-500 ml-2"></i><?= $texts['ar']['expense_breakdown'] ?></h4>
            <div class="h-72 flex items-center justify-center" id="doughnutContainer">
                <?php if(empty($expense_breakdown)): ?>
                    <div class="text-slate-300 text-center italic font-bold">
                        <i class="fas fa-chart-pie text-5xl mb-3 block opacity-20"></i>
                        <p><?= $texts['ar']['no_expenses'] ?></p>
                    </div>
                <?php else: ?>
                    <canvas id="doughnutChart"></canvas>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <?php if($f_from || $f_to): ?>
        <div class="bg-amber-50 border border-amber-100 p-4 rounded-2xl mb-8 text-center">
            <p class="text-[11px] font-black text-amber-600 uppercase italic">
                <i class="fas fa-info-circle ml-1"></i><?= $texts['ar']['period_note'] ?>
                <?php if($f_from): ?>من <?= $f_from ?><?php endif; ?>
                <?php if($f_to): ?>إلى <?= $f_to ?><?php endif; ?>
            </p>
        </div>
    <?php endif; ?>

    <div class="table-grid grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8" style="display:grid;">
        <div class="lg:col-span-2 bg-white rounded-[3rem] shadow-sm border border-slate-100 overflow-hidden">
            <div class="p-8 border-b border-slate-50 bg-slate-50/50 flex justify-between items-center">
                <h4 class="font-black text-slate-800 italic"><i class="fas fa-list text-slate-400 ml-2"></i><?= $texts['ar']['history_expenses'] ?></h4>
                <span class="text-[10px] font-black text-slate-300 uppercase"><?= count($recent_expenses) ?> قيد</span>
            </div>
            <?php if(empty($recent_expenses)): ?>
                <div class="p-20 text-center text-slate-300 italic font-bold">
                    <i class="fas fa-receipt text-5xl mb-4 block opacity-20"></i>
                    <p><?= $texts['ar']['no_expenses'] ?></p>
                </div>
            <?php else: ?>
            <div class="overflow-x-auto">
                <table class="w-full text-right">
                    <thead class="bg-slate-50 text-slate-400 text-[10px] font-black uppercase">
                        <tr>
                            <th class="p-5"><?= $texts['ar']['date'] ?></th>
                            <th class="p-5">البيان</th>
                            <th class="p-5 text-center"><?= $texts['ar']['amount'] ?></th>
                            <th class="p-5 text-center"><?= $texts['ar']['by'] ?></th>
                            <th class="p-5 text-center no-print"><?= $texts['ar']['operations'] ?></th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-50 font-bold italic text-sm">
                        <?php foreach($recent_expenses as $exp): ?>
                        <tr class="hover:bg-slate-50 transition group">
                            <td class="p-5 text-xs text-slate-400 whitespace-nowrap"><?= $exp['expense_date'] ?></td>
                            <td class="p-5">
                                <div class="text-slate-800 font-black"><?= htmlspecialchars($exp['title']) ?></div>
                                <div class="flex items-center gap-1.5 mt-1">
                                    <span class="w-5 h-5 rounded-lg flex items-center justify-center text-[8px] text-white" style="background:<?= $cat_colors[$exp['category']] ?? '#8b5cf6' ?>">
                                        <i class="fas <?= $cat_icons[$exp['category']] ?? 'fa-ellipsis' ?>"></i>
                                    </span>
                                    <span class="text-[9px] text-slate-400 uppercase font-black"><?= $cat_names[$exp['category']] ?? $exp['category'] ?></span>
                                    <?php if($exp['notes']): ?>
                                        <span class="text-[9px] text-slate-300 truncate max-w-[100px]" title="<?= htmlspecialchars($exp['notes']) ?>"><?= htmlspecialchars($exp['notes']) ?></span>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td class="p-5 text-center text-rose-600 font-black text-lg">$<?= number_format($exp['amount_usd'], 2) ?></td>
                            <td class="p-5 text-center">
                                <span class="text-[9px] font-black uppercase text-slate-400 bg-slate-100 px-2 py-0.5 rounded-full"><?= htmlspecialchars($exp['creator_name'] ?: '—') ?></span>
                            </td>
                            <td class="p-5 text-center no-print">
                                <div class="flex justify-center gap-1">
                                    <button onclick='editExpense(<?= json_encode($exp, JSON_UNESCAPED_UNICODE) ?>)' class="w-8 h-8 bg-blue-50 text-blue-500 rounded-xl flex items-center justify-center hover:bg-blue-500 hover:text-white transition shadow-sm text-xs"><i class="fas fa-edit"></i></button>
                                    <?php if($can_manage_all || $exp['created_by'] == $logged_user_id): ?>
                                        <a href="?delete_exp=<?= $exp['id'] ?>&<?= http_build_query(array_diff_key($_GET, ['delete_exp'=>''])) ?>" onclick="return confirm('<?= $texts['ar']['confirm_delete'] ?>')" class="w-8 h-8 bg-rose-50 text-rose-500 rounded-xl flex items-center justify-center hover:bg-rose-500 hover:text-white transition shadow-sm text-xs"><i class="fas fa-trash-alt"></i></a>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php endif; ?>
        </div>

        <div class="space-y-6">
            <div class="bg-slate-900 p-7 rounded-[3rem] text-white shadow-xl">
                <p class="text-slate-500 text-[10px] font-black uppercase mb-2"><i class="fas fa-exclamation-triangle ml-1"></i><?= $texts['ar']['total_debt'] ?></p>
                <h3 class="text-4xl font-black text-rose-400 tracking-tighter italic">$<?= number_format($total_debt, 2) ?></h3>
                <div class="flex gap-4 mt-4 text-[10px]">
                    <span class="text-amber-400 font-bold">فواتير: $<?= number_format($total_unpaid, 0) ?></span>
                    <span class="text-slate-400 font-bold">أرصدة: $<?= number_format($old_debts, 0) ?></span>
                </div>
            </div>

            <div class="bg-white rounded-[3rem] shadow-sm border border-slate-100 overflow-hidden">
                <div class="p-6 border-b border-slate-50 bg-slate-50/50">
                    <h4 class="font-black text-slate-800 uppercase italic text-xs"><i class="fas fa-arrow-down-wide-short text-rose-400 ml-1"></i><?= $texts['ar']['top_debtors'] ?></h4>
                </div>
                <?php if(empty($top_debtors)): ?>
                    <div class="p-12 text-center text-slate-300 italic font-bold text-sm">
                        <i class="fas fa-face-smile text-3xl mb-3 block opacity-20"></i>
                        <p><?= $texts['ar']['no_debtors'] ?></p>
                    </div>
                <?php else: ?>
                <div class="divide-y divide-slate-50">
                    <?php foreach($top_debtors as $idx => $d):
                        $total_d = floatval($d['old_balance']) + floatval($d['bills_debt']);
                        if($total_d <= 0.1) continue;
                    ?>
                    <div class="p-4 hover:bg-rose-50/30 transition flex items-center justify-between gap-3">
                        <div class="flex items-center gap-3 min-w-0">
                            <span class="w-7 h-7 rounded-lg bg-rose-100 text-rose-600 flex items-center justify-center text-[10px] font-black shrink-0"><?= $idx + 1 ?></span>
                            <div class="min-w-0">
                                <p class="font-black text-slate-800 text-sm truncate"><?= htmlspecialchars($d['name']) ?></p>
                                <p class="text-[9px] text-slate-400">#<?= $d['sub_no'] ?: '—' ?><?php if($d['phone']): ?> · <?= $d['phone'] ?><?php endif; ?></p>
                            </div>
                        </div>
                        <span class="bg-rose-600 text-white px-3 py-1 rounded-xl font-black text-[11px] shadow shrink-0">$<?= number_format($total_d, 0) ?></span>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<div id="expenseModal" class="fixed inset-0 bg-slate-900/60 hidden items-center justify-center z-50 p-4 backdrop-blur-sm overflow-y-auto">
    <div class="bg-white rounded-[3rem] w-full max-w-lg overflow-hidden shadow-2xl my-8 border-t-8 border-rose-500" style="animation: modalIn 0.3s ease-out">
        <div class="p-8 bg-slate-900 text-white flex justify-between items-center italic font-black shrink-0">
            <h3 id="modalTitle"><i class="fas fa-plus-circle ml-2"></i><?= $texts['ar']['add_expense'] ?></h3>
            <button onclick="closeModal()" class="w-10 h-10 bg-white/10 rounded-xl hover:bg-rose-500 transition-all text-xl flex items-center justify-center">&times;</button>
        </div>
        <form method="POST" class="p-8 space-y-5 font-bold italic modal-body">
            <input type="hidden" name="save_expense" value="1">
            <input type="hidden" name="exp_id" id="exp_id" value="">
            <div>
                <label class="block text-[10px] font-black text-slate-400 mb-2 uppercase tracking-widest">البيان *</label>
                <input type="text" name="exp_title" id="exp_title" required class="w-full p-4 bg-slate-50 rounded-2xl border-none outline-none focus:ring-2 focus:ring-blue-600 shadow-inner">
            </div>
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-[10px] font-black text-slate-400 mb-2 uppercase italic"><?= $texts['ar']['category'] ?></label>
                    <select name="exp_category" id="exp_category" class="w-full p-4 bg-slate-50 rounded-2xl border-none font-bold outline-none cursor-pointer shadow-inner">
                        <?php foreach($cat_names as $k => $v): ?>
                            <option value="<?= $k ?>"><?= $v ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-[10px] font-black text-slate-400 mb-2 uppercase italic"><?= $texts['ar']['date'] ?></label>
                    <input type="date" name="exp_date" id="exp_date" value="<?= date('Y-m-d') ?>" required class="w-full p-4 bg-slate-50 rounded-2xl border-none font-bold shadow-inner">
                </div>
            </div>
            <div>
                <label class="block text-[10px] font-black text-rose-600 mb-2 uppercase italic tracking-widest">المبلغ ($) *</label>
                <input type="number" step="0.01" min="0.01" name="exp_amount" id="exp_amount" required class="w-full p-4 bg-rose-50 rounded-2xl border-none font-black text-2xl text-center text-rose-700 outline-none shadow-inner">
            </div>
            <div>
                <label class="block text-[10px] font-black text-slate-400 mb-2 uppercase italic"><?= $texts['ar']['notes'] ?></label>
                <input type="text" name="exp_notes" id="exp_notes" class="w-full p-4 bg-slate-50 rounded-2xl border-none outline-none shadow-inner">
            </div>
            <button type="submit" id="submitBtn" class="w-full p-5 bg-slate-900 text-white rounded-3xl font-black shadow-xl hover:bg-black transition text-lg italic uppercase">
                <i class="fas fa-save ml-2"></i><?= $texts['ar']['save'] ?>
            </button>
        </form>
    </div>
</div>

<button id="backToTop" onclick="window.scrollTo({top:0,behavior:'smooth'})" class="fixed bottom-6 left-6 w-12 h-12 bg-blue-600 text-white rounded-2xl shadow-xl hidden items-center justify-center hover:bg-black transition z-40 text-lg no-print">
    <i class="fas fa-chevron-up"></i>
</button>

<script>
function setQuickDate(range) {
    var from = document.getElementById('f_from');
    var to = document.getElementById('f_to');
    var today = new Date().toISOString().split('T')[0];
    to.value = today;
    switch(range) {
        case 'today': from.value = today; break;
        case 'week':
            var w = new Date(); w.setDate(w.getDate() - 7);
            from.value = w.toISOString().split('T')[0]; break;
        case 'month':
            from.value = new Date(new Date().getFullYear(), new Date().getMonth(), 1).toISOString().split('T')[0]; break;
        case 'year':
            from.value = new Date().getFullYear() + '-01-01'; break;
        case 'all':
            from.value = ''; to.value = ''; break;
    }
    document.getElementById('filterForm').submit();
}

function openModal() {
    document.getElementById('exp_id').value = '';
    document.getElementById('exp_title').value = '';
    document.getElementById('exp_category').value = 'other';
    document.getElementById('exp_date').value = new Date().toISOString().split('T')[0];
    document.getElementById('exp_amount').value = '';
    document.getElementById('exp_notes').value = '';
    document.getElementById('modalTitle').innerHTML = '<i class="fas fa-plus-circle ml-2"></i><?= $texts['ar']['add_expense'] ?>';
    document.getElementById('submitBtn').innerHTML = '<i class="fas fa-save ml-2"></i><?= $texts['ar']['save'] ?>';
    var m = document.getElementById('expenseModal');
    m.classList.remove('hidden');
    m.classList.add('flex');
    document.body.style.overflow = 'hidden';
}

function editExpense(data) {
    document.getElementById('exp_id').value = data.id;
    document.getElementById('exp_title').value = data.title;
    document.getElementById('exp_category').value = data.category;
    document.getElementById('exp_date').value = data.expense_date;
    document.getElementById('exp_amount').value = data.amount_usd;
    document.getElementById('exp_notes').value = data.notes || '';
    document.getElementById('modalTitle').innerHTML = '<i class="fas fa-edit ml-2"></i><?= $texts['ar']['edit_expense'] ?>';
    document.getElementById('submitBtn').innerHTML = '<i class="fas fa-sync-alt ml-2"></i><?= $texts['ar']['update'] ?>';
    var m = document.getElementById('expenseModal');
    m.classList.remove('hidden');
    m.classList.add('flex');
    document.body.style.overflow = 'hidden';
}

function closeModal() {
    var m = document.getElementById('expenseModal');
    m.classList.add('hidden');
    m.classList.remove('flex');
    document.body.style.overflow = '';
}

document.getElementById('expenseModal').addEventListener('click', function(e) {
    if (e.target === this) closeModal();
});
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') closeModal();
});

window.addEventListener('scroll', function() {
    var btn = document.getElementById('backToTop');
    if (window.scrollY > 400) { btn.classList.remove('hidden'); btn.classList.add('flex'); }
    else { btn.classList.add('hidden'); btn.classList.remove('flex'); }
});

var barCtx = document.getElementById('barChart').getContext('2d');
new Chart(barCtx, {
    type: 'bar',
    data: {
        labels: <?= json_encode($chart_labels, JSON_UNESCAPED_UNICODE) ?>,
        datasets: [
            {
                label: 'الإيرادات (محصل)',
                data: <?= json_encode($chart_inc_final) ?>,
                backgroundColor: 'rgba(59,130,246,0.8)',
                borderRadius: 8,
                borderSkipped: false
            },
            {
                label: 'المصاريف',
                data: <?= json_encode($chart_exp_final) ?>,
                backgroundColor: 'rgba(239,68,68,0.8)',
                borderRadius: 8,
                borderSkipped: false
            }
        ]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: { position: 'top', labels: { font: { family: 'Cairo', weight: 'bold', size: 11 }, padding: 20 } }
        },
        scales: {
            y: { beginAtZero: true, ticks: { font: { family: 'Cairo' }, callback: function(v) { return '$' + v; } }, grid: { color: '#f1f5f9' } },
            x: { ticks: { font: { family: 'Cairo', weight: 'bold', size: 10 } }, grid: { display: false } }
        }
    }
});

<?php if(!empty($expense_breakdown)): ?>
var dCtx = document.getElementById('doughnutChart').getContext('2d');
new Chart(dCtx, {
    type: 'doughnut',
    data: {
        labels: <?= json_encode(array_map(function($e) use ($cat_names) { return $cat_names[$e['category']] ?? $e['category']; }, $expense_breakdown), JSON_UNESCAPED_UNICODE) ?>,
        datasets: [{
            data: <?= json_encode(array_column($expense_breakdown, 'total')) ?>,
            backgroundColor: <?= json_encode(array_map(function($e) use ($cat_colors) { return $cat_colors[$e['category']] ?? '#8b5cf6'; }, $expense_breakdown)) ?>,
            borderWidth: 0,
            hoverOffset: 12
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        cutout: '70%',
        plugins: {
            legend: { position: 'bottom', labels: { font: { family: 'Cairo', weight: 'bold', size: 11 }, padding: 15 } },
            tooltip: {
                callbacks: {
                    label: function(ctx) {
                        var total = ctx.dataset.data.reduce(function(a,b){ return a+b; }, 0);
                        var pct = total > 0 ? ((ctx.parsed / total) * 100).toFixed(1) : 0;
                        return ctx.label + ': $' + ctx.parsed.toFixed(2) + ' (' + pct + '%)';
                    }
                }
            }
        }
    }
});
<?php endif; ?>
</script>
</body>
</html>