<?php
session_start();

// 1. التحقق من الدخول
if (!isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit;
}

require_once 'db.php';

// جلب بيانات المستخدم الحالي وصلاحياته
$logged_user_id = $_SESSION['user_id'];
$stmt_user = $pdo->prepare("SELECT role, is_primary FROM users WHERE id = ?");
$stmt_user->execute([$logged_user_id]);
$user_data = $stmt_user->fetch();

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

// إدارة اللغة
$lang = $_SESSION['lang'] ?? 'ar';
$is_ar = ($lang === 'ar');
$dir = $is_ar ? 'rtl' : 'ltr';

// --- (تحسين: يفضل تشغيل هذا الجزء مرة واحدة فقط، لكن أبقيته لضمان عدم نقص أي خاصية) ---
try {
    $pdo->exec("ALTER TABLE `customers` ADD COLUMN IF NOT EXISTS `created_by` INT NULL AFTER `box_no` ");
    $pdo->exec("ALTER TABLE `customers` ADD COLUMN IF NOT EXISTS `is_exempt` TINYINT(1) DEFAULT 0 AFTER `status` ");
} catch (PDOException $e) {}

// =================================================================================
// [إضافة]: دالة حساب الاستهلاك الذكية لحل مشكلة القراءات (مثل 10655 -> 10821)
// =================================================================================
function calculateConsumption($curr, $prev) {
    $curr = (float)$curr; $prev = (float)$prev;
    if ($curr >= $prev) return $curr - $prev;
    
    // معالجة قلبة العداد أو إغفال الخانات الكبيرة (مثل 10655 ثم إدخال 0821 بدلاً من 10821)
    $offsets = [10000, 100000, 1000];
    foreach ($offsets as $offset) {
        $adjusted = ($curr + $offset) - $prev;
        if ($adjusted > 0 && $adjusted < 3000) return $adjusted; 
    }
    return 0; 
}

// =================================================================================
// إعداد الفلاتر (Persistence Logic)
// =================================================================================
$filter_keys = ['f_month', 'f_year', 'f_status', 'f_type', 'f_box', 'f_cust_status', 'f_user'];
foreach ($filter_keys as $key) {
    if (isset($_GET[$key])) { $_SESSION['sess_bills_' . $key] = $_GET[$key]; }
}
function getVal($key, $default) { return $_GET[$key] ?? $_SESSION['sess_bills_' . $key] ?? $default; }

$f_month = getVal('f_month', date('n'));
$f_year  = getVal('f_year', date('Y'));
$f_status = getVal('f_status', '');
$f_type   = getVal('f_type', '');
$f_box    = getVal('f_box', '');
$f_cust_status = getVal('f_cust_status', '');
$f_user   = getVal('f_user', ''); 
$f_search = $_GET['search'] ?? ''; 
$f_name_search = $_GET['name_search'] ?? '';

// =================================================================================
// [تحسين جوهري]: بناء استعلام "موحد" يستخدم للعرض وللتصدير (منع التكرار)
// =================================================================================
$conditions = [];
$query_params = [];

// 1. الشروط الأساسية
$conditions[] = "b.month = ?"; $query_params[] = $f_month;
$conditions[] = "b.year = ?";  $query_params[] = $f_year;

// 2. شرط الصلاحية
if (!$can_see_all) {
    $conditions[] = "c.created_by = ?";
    $query_params[] = $logged_user_id;
}

// 3. الفلاتر
if ($f_status) { $conditions[] = "b.status = ?"; $query_params[] = $f_status; }
if ($f_cust_status !== '') { $conditions[] = "c.status = ?"; $query_params[] = $f_cust_status; }
if ($f_box) { $conditions[] = "c.box_no = ?"; $query_params[] = $f_box; }

// فلتر الموظف
if ($f_user && $can_see_all) {
    $conditions[] = "c.created_by = ?";
    $query_params[] = $f_user;
}

// فلتر نوع النظام
if ($f_type == 'meter') {
    $conditions[] = "c.system_type = 'meter'";
} elseif ($f_type == 'amp_normal') {
    $conditions[] = "c.system_type = 'ampere' AND (c.custom_amp_price = 0 OR c.custom_amp_price IS NULL)";
} elseif ($f_type == 'amp_special') {
    $conditions[] = "c.system_type = 'ampere' AND c.custom_amp_price > 0";
}

// البحث الشامل
if ($f_search) {
    $conditions[] = "(c.name LIKE ? OR b.bill_number LIKE ? OR c.sub_no LIKE ? OR c.phone LIKE ?)";
    $term = "%$f_search%";
    $query_params[] = $term; $query_params[] = $term; $query_params[] = $term; $query_params[] = $term;
}

// البحث بالاسم
if ($f_name_search) {
    $conditions[] = "c.name LIKE ?";
    $query_params[] = "%$f_name_search%";
}

// تجميع جملة WHERE النهائية
$where_clause = "WHERE " . implode(' AND ', $conditions);
// =================================================================================

// معالجة تصدير الإكسل (Excel Export) - يستخدم نفس الاستعلام الموحد
if (isset($_GET['action']) && $_GET['action'] == 'export') {
    $sql_e = "SELECT b.bill_number, c.name, c.sub_no, c.box_no, c.system_type, b.amount_usd, b.status as bill_status, 
                     (b.amount_usd * IFNULL(p.exchange_rate, 0)) as amount_lbp,
                     CASE WHEN c.status = 1 THEN 'نشط' ELSE 'ملغى' END as cust_status
              FROM bills b JOIN customers c ON b.customer_id = c.id 
              LEFT JOIN monthly_pricing p ON b.month = p.month AND b.year = p.year
              $where_clause"; // استخدام الشرط الموحد

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=Bills_Report_'.$f_month.'_'.$f_year.'.csv');
    $output = fopen('php://output', 'w');
    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF)); 
    fputcsv($output, ['رقم الفاتورة', 'المشترك', 'رقم الاشتراك', 'العلبة', 'النظام', 'المبلغ ($)', 'المبلغ (ل.ل)', 'حالة الفاتورة', 'حالة المشترك']);
    
    $stmt_e = $pdo->prepare($sql_e);
    $stmt_e->execute($query_params); // استخدام البارامترات الموحدة
    while ($row = $stmt_e->fetch(PDO::FETCH_ASSOC)) { fputcsv($output, $row); }
    fclose($output);
    exit;
}

$message = '';
$error = '';
$print_id = null;
$role_check_action = $can_see_all ? "" : " AND customer_id IN (SELECT id FROM customers WHERE created_by = $logged_user_id)";

// 2. معالجة العمليات (حذف، تسديد، إعادة حساب)
if (isset($_GET['delete_id'])) {
    try {
        $bid = $_GET['delete_id'];
        $stmt_check = $pdo->prepare("SELECT customer_id, amount_usd FROM bills WHERE id = ? $role_check_action");
        $stmt_check->execute([$bid]);
        $bill_data = $stmt_check->fetch();
        if ($bill_data) {
            $pdo->prepare("DELETE FROM bills WHERE id = ?")->execute([$bid]);
            $pdo->prepare("UPDATE customers SET old_balance = old_balance + ? WHERE id = ?")->execute([$bill_data['amount_usd'], $bill_data['customer_id']]);
            $message = "تم حذف الفاتورة وإعادة المبلغ للرصيد بنجاح";
        } else { $error = "ليس لديك صلاحية لحذف هذه الفاتورة"; }
    } catch (PDOException $e) { $error = $e->getMessage(); }
}

if (isset($_GET['pay_id'])) {
    try {
        $check = $pdo->prepare("SELECT id FROM bills WHERE id = ? $role_check_action");
        $check->execute([$_GET['pay_id']]);
        if ($check->rowCount() > 0) {
            $pdo->prepare("UPDATE bills SET status = 'paid' WHERE id = ?")->execute([$_GET['pay_id']]);
            $message = "تم التسديد بنجاح (سيتم فتح الطباعة)";
            $print_id = $_GET['pay_id'];
        }
    } catch (PDOException $e) { $error = $e->getMessage(); }
}

if (isset($_GET['unpay_id'])) {
    try {
        $check = $pdo->prepare("SELECT id FROM bills WHERE id = ? $role_check_action");
        $check->execute([$_GET['unpay_id']]);
        if ($check->rowCount() > 0) {
            $pdo->prepare("UPDATE bills SET status = 'unpaid' WHERE id = ?")->execute([$_GET['unpay_id']]);
            $message = "تم إلغاء التسديد بنجاح";
        }
    } catch (PDOException $e) { $error = $e->getMessage(); }
}

if (isset($_GET['recalc_id'])) {
    try {
        $bid = $_GET['recalc_id'];
        $stmt = $pdo->prepare("SELECT b.*, c.system_type, c.custom_amp_price, c.ampere_qty, c.monthly_fixed_fee, c.old_balance as cust_balance, p.price_kwh, p.price_amp, p.exchange_rate, p.fee_per_rated_amp 
                                FROM bills b JOIN customers c ON b.customer_id = c.id 
                                LEFT JOIN monthly_pricing p ON b.month = p.month AND b.year = p.year WHERE b.id = ? $role_check_action");
        $stmt->execute([$bid]);
        $d = $stmt->fetch();
        if ($d && $d['exchange_rate'] > 0) {
            $final_usd = 0;
            if ($d['system_type'] === 'meter') {
                $r = $pdo->prepare("SELECT current_reading, previous_reading FROM meter_readings WHERE meter_id=? AND month=? AND year=?");
                $r->execute([$d['customer_id'], $d['month'], $d['year']]);
                $read = $r->fetch();
                if ($read) {
                    $consumption = calculateConsumption($read['current_reading'], $read['previous_reading']);
                    // العداد: (استهلاك * سعر ليرة) + رسم ثابت ليرة / سعر الصرف + الرصيد السابق دولار
                    $total_lbp = ($consumption * $d['price_kwh']) + ($d['monthly_fixed_fee'] ?? 0);
                    $final_usd = ($total_lbp / $d['exchange_rate']) + ($d['cust_balance'] ?? 0);
                }
            } else {
                $rate = ($d['custom_amp_price'] > 0) ? $d['custom_amp_price'] : $d['price_amp'];
                $cons_usd = ($d['ampere_qty'] ?? 0) * $rate;
                $rated_fee_usd = ($d['ampere_qty'] ?? 0) * ($d['fee_per_rated_amp'] ?? 0);
                $fixed_fee_usd = ($d['monthly_fixed_fee'] ?? 0) / $d['exchange_rate'];
                $final_usd = $cons_usd + $rated_fee_usd + $fixed_fee_usd + ($d['cust_balance'] ?? 0);
            }
            $pdo->prepare("UPDATE bills SET amount_usd = ? WHERE id = ?")->execute([$final_usd, $bid]);
            $message = "تم تحديث الحساب بنجاح";
        }
    } catch (PDOException $e) { $error = "خطأ في التحديث: " . $e->getMessage(); }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['generate_action'])) {
    if (!$can_see_all) {
        $error = "عذراً، إصدار الفواتير متاح فقط للإدارة.";
    } else {
        $m = $_POST['month']; $y = $_POST['year'];
        $target_sys = $_POST['target_system'] ?? 'all';
        $price_stmt = $pdo->prepare("SELECT * FROM monthly_pricing WHERE month = ? AND year = ?");
        $price_stmt->execute([$m, $y]);
        $pricing = $price_stmt->fetch();

        if (!$pricing || $pricing['exchange_rate'] <= 0) {
            $error = "خطأ: لم يتم ضبط الأسعار لهذا الشهر ($m / $y)!";
        } else {
            $query_cust = "SELECT * FROM customers WHERE status = 1 AND is_exempt = 0";
            if ($target_sys !== 'all') { $query_cust .= " AND system_type = " . $pdo->quote($target_sys); }
            $customers = $pdo->query($query_cust)->fetchAll();
            $generated = 0;
            foreach ($customers as $cust) {
                $check = $pdo->prepare("SELECT id FROM bills WHERE customer_id = ? AND month = ? AND year = ?");
                $check->execute([$cust['id'], $m, $y]);
                if ($check->rowCount() > 0) continue; 

                $total_usd = 0;
                if ($cust['system_type'] === 'meter') {
                    $r_stmt = $pdo->prepare("SELECT current_reading, previous_reading FROM meter_readings WHERE meter_id = ? AND month = ? AND year = ?");
                    $r_stmt->execute([$cust['id'], $m, $y]);
                    $read = $r_stmt->fetch();
                    if ($read) {
                        $consumption = calculateConsumption($read['current_reading'], $read['previous_reading']);
                        $total_lbp = ($consumption * $pricing['price_kwh']) + ($cust['monthly_fixed_fee'] ?? 0);
                        $total_usd = ($total_lbp / $pricing['exchange_rate']) + ($cust['old_balance'] ?? 0);
                    } else { continue; }
                } else {
                    $rate = ($cust['custom_amp_price'] > 0) ? $cust['custom_amp_price'] : $pricing['price_amp'];
                    $cons_usd = ($cust['ampere_qty'] ?? 0) * $rate;
                    $rated_fee_usd = ($cust['ampere_qty'] ?? 0) * ($pricing['fee_per_rated_amp'] ?? 0);
                    $fixed_fee_usd = ($cust['monthly_fixed_fee'] ?? 0) / $pricing['exchange_rate'];
                    $total_usd = $cons_usd + $rated_fee_usd + $fixed_fee_usd + ($cust['old_balance'] ?? 0);
                }

                if ($total_usd > 0) {
                    $bill_no = "B-" . $y . sprintf("%02d", $m) . "-" . ($cust['sub_no'] ?: $cust['id']);
                    $pdo->prepare("INSERT INTO bills (bill_number, customer_id, month, year, amount_usd, status) VALUES (?, ?, ?, ?, ?, 'unpaid')")->execute([$bill_no, $cust['id'], $m, $y, $total_usd]);
                    $pdo->prepare("UPDATE customers SET old_balance = 0 WHERE id = ?")->execute([$cust['id']]);
                    $generated++;
                }
            }
            $message = "تم إصدار $generated فاتورة بنجاح.";
        }
    }
}

// 3. جلب البيانات للعرض (Pagination)
$limit = isset($_GET['limit']) ? (($_GET['limit'] == 'all') ? 999999 : (int)$_GET['limit']) : 20;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

// حساب المجموع الكلي (نستخدم نفس الشرط الموحد)
$count_sql = "SELECT COUNT(*) FROM bills b JOIN customers c ON b.customer_id = c.id 
              LEFT JOIN monthly_pricing p ON b.month = p.month AND b.year = p.year $where_clause";
$count_stmt = $pdo->prepare($count_sql);
$count_stmt->execute($query_params);
$total_records = $count_stmt->fetchColumn();
$total_pages = ceil($total_records / $limit);

// جلب البيانات النهائية (نستخدم نفس الشرط الموحد) مع جلب القراءات للتعقب
$main_sql = "SELECT b.*, c.id as cid, c.name as customer_name, c.sub_no, c.box_no, c.phone, c.system_type, c.custom_amp_price, c.ampere_qty, c.monthly_fixed_fee, c.status as customer_status, 
             p.exchange_rate, p.price_kwh, p.price_amp, p.fee_per_rated_amp, mr.current_reading, mr.previous_reading
             FROM bills b JOIN customers c ON b.customer_id = c.id 
             LEFT JOIN monthly_pricing p ON b.month = p.month AND b.year = p.year
             LEFT JOIN meter_readings mr ON b.customer_id = mr.meter_id AND b.month = mr.month AND b.year = mr.year
             $where_clause 
             ORDER BY b.id DESC LIMIT $offset, $limit";
$stmt = $pdo->prepare($main_sql);
$stmt->execute($query_params);
$all_bills = $stmt->fetchAll();

// جلب العلب المتاحة
$box_cond = $can_see_all ? "" : "WHERE created_by = $logged_user_id";
$box_q = "SELECT DISTINCT box_no FROM customers $box_cond ORDER BY box_no ASC";
$unique_boxes = $pdo->query($box_q)->fetchAll(PDO::FETCH_COLUMN);
// تنظيف المصفوفة من القيم الفارغة
$unique_boxes = array_filter($unique_boxes, function($v) { return !empty($v); });

// جلب قائمة الموظفين (للمدير فقط)
$users_list = [];
if ($can_see_all) {
    try {
        $users_list = $pdo->query("SELECT id, username FROM users ORDER BY username ASC")->fetchAll();
    } catch (PDOException $e) {}
}

$query_params_url = $_GET;
unset($query_params_url['page']);
$query_string = http_build_query($query_params_url);
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <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">
    <style>body { font-family: 'Cairo', sans-serif; background-color: #f4f7fa; }</style>
</head>
<body class="pb-20 text-slate-800">

    <div class="container mx-auto px-4 py-8">
        <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-file-invoice-dollar"></i>
                </div>
                <div>
                    <h1 class="text-2xl font-black text-slate-800 italic">الفواتير والتحصيل</h1>
                    <p class="text-sm text-slate-400 font-bold uppercase italic">
                        <?= $can_see_all ? 'نطاق الإدارة (عرض كافة فواتير الشبكة)' : 'نطاق موظف (زبائنك المباشرين فقط)' ?>
                    </p>
                </div>
            </div>
            <div class="flex gap-3">
                <a href="?action=export&search=<?= urlencode($f_search) ?>&name_search=<?= urlencode($f_name_search) ?>" 
                   class="bg-emerald-600 hover:bg-black text-white px-6 py-3 rounded-2xl font-black transition shadow-lg flex items-center gap-2">
                    <i class="fas fa-file-excel"></i> Excel
                </a>
                
                <?php if($can_see_all): ?>
                <button onclick="document.getElementById('genModal').classList.remove('hidden')" class="bg-blue-600 hover:bg-black text-white px-8 py-3 rounded-2xl font-black transition shadow-lg">
                    إصدار فواتير جديدة
                </button>
                <?php endif; ?>

                <a href="dashboard.php" class="bg-slate-100 text-slate-600 px-6 py-3 rounded-2xl font-bold hover:bg-slate-200 transition">الرئيسية</a>
            </div>
        </div>

        <?php if($message): ?><div class="bg-emerald-500 text-white p-4 rounded-2xl mb-8 font-bold shadow-lg animate-bounce italic"><i class="fas fa-check-circle"></i> <?= $message ?></div><?php endif; ?>
        <?php if($error): ?><div class="bg-rose-500 text-white p-4 rounded-2xl mb-8 font-bold shadow-lg italic"><i class="fas fa-exclamation-triangle"></i> <?= $error ?></div><?php endif; ?>

        <div class="bg-white p-6 rounded-[2rem] shadow-sm mb-8 border border-slate-100">
            <form id="filterForm" method="GET" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-8 gap-4 items-end italic font-bold text-sm">
                <div class="lg:col-span-1">
                    <label class="block text-[10px] font-black text-slate-400 mb-2 uppercase tracking-widest text-center">بحث شامل (Live)</label>
                    <input type="text" name="search" id="liveSearchInput" value="<?= htmlspecialchars($f_search) ?>" placeholder="شامل..." class="w-full p-4 bg-slate-50 rounded-2xl border-none font-bold outline-none focus:ring-2 focus:ring-blue-500 shadow-inner">
                </div>
                <div class="lg:col-span-1">
                    <label class="block text-[10px] font-black text-emerald-600 mb-2 uppercase tracking-widest text-center">بحث بالاسم (عادي)</label>
                    <input type="text" name="name_search" id="nameSearchInput" value="<?= htmlspecialchars($f_name_search) ?>" placeholder="الاسم..." class="w-full p-4 bg-emerald-50 text-emerald-700 rounded-2xl border-none font-bold outline-none focus:ring-2 focus:ring-emerald-500 shadow-inner">
                </div>
                
                <?php if($can_see_all): ?>
                <div>
                    <label class="block text-[10px] font-black text-slate-400 mb-2 uppercase text-center">الموظف المسؤول</label>
                    <select name="f_user" onchange="this.form.submit()" class="w-full p-4 bg-slate-50 rounded-2xl border-none text-center">
                        <option value="">الكل</option>
                        <?php foreach($users_list as $u): ?>
                            <option value="<?= $u['id'] ?>" <?= $f_user == $u['id'] ? 'selected' : '' ?>><?= htmlspecialchars($u['username']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php else: ?>
                <div class="hidden lg:block"></div>
                <?php endif; ?>

                <div>
                    <label class="block text-[10px] font-black text-slate-400 mb-2 uppercase text-center">العلبة</label>
                    <select name="f_box" onchange="this.form.submit()" class="w-full p-4 bg-slate-50 rounded-2xl border-none outline-none cursor-pointer text-center">
                        <option value="">كل العلب</option>
                        <?php foreach($unique_boxes as $box): ?>
                            <option value="<?= htmlspecialchars($box) ?>" <?= $f_box == $box ? 'selected' : '' ?>><?= htmlspecialchars($box) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-[10px] font-black text-slate-400 mb-2 uppercase text-center">دورة الدفع</label>
                    <div class="flex gap-1">
                        <select name="f_month" onchange="this.form.submit()" class="w-1/2 p-4 bg-slate-50 rounded-2xl border-none text-center">
                            <?php for($m=1;$m<=12;$m++) echo "<option value='$m' ".($f_month==$m?'selected':'').">$m</option>"; ?>
                        </select>
                        <select name="f_year" onchange="this.form.submit()" class="w-1/2 p-4 bg-slate-50 rounded-2xl border-none text-center">
                            <?php for($y=2024;$y<=2027;$y++) echo "<option value='$y' ".($f_year==$y?'selected':'').">$y</option>"; ?>
                        </select>
                    </div>
                </div>
                <div>
                    <label class="block text-[10px] font-black text-slate-400 mb-2 uppercase text-center">النظام</label>
                    <select name="f_type" onchange="this.form.submit()" class="w-full p-4 bg-slate-50 rounded-2xl border-none text-center">
                        <option value="">الكل</option>
                        <option value="meter" <?= $f_type == 'meter' ? 'selected' : '' ?>>عدادات</option>
                        <option value="amp_normal" <?= $f_type == 'amp_normal' ? 'selected' : '' ?>>أمبير (عام)</option>
                        <option value="amp_special" <?= $f_type == 'amp_special' ? 'selected' : '' ?>>أمبير (خاص)</option>
                    </select>
                </div>
                <div>
                    <label class="block text-[10px] font-black text-slate-400 mb-2 uppercase text-center">حالة الدفع</label>
                    <select name="f_status" onchange="this.form.submit()" class="w-full p-4 bg-slate-50 rounded-2xl border-none text-center">
                        <option value="">الكل</option>
                        <option value="paid" <?= $f_status == 'paid' ? 'selected' : '' ?>>مدفوعة</option>
                        <option value="unpaid" <?= $f_status == 'unpaid' ? 'selected' : '' ?>>غير مدفوعة</option>
                    </select>
                </div>
                <div>
                    <label class="block text-[10px] font-black text-slate-400 mb-2 uppercase text-center">حالة المشترك</label>
                    <select name="f_cust_status" onchange="this.form.submit()" class="w-full p-4 bg-slate-50 rounded-2xl border-none font-bold text-rose-600 text-center">
                        <option value="">الكل</option>
                        <option value="1" <?= $f_cust_status === '1' ? 'selected' : '' ?>>نشط</option>
                        <option value="0" <?= $f_cust_status === '0' ? 'selected' : '' ?>>واقف 🛑</option>
                    </select>
                </div>
                <div>
                    <label class="block text-[10px] font-black text-blue-600 mb-2 uppercase text-center">العرض بالصفحة</label>
                    <select name="limit" onchange="this.form.submit()" class="w-full p-4 bg-blue-50 rounded-2xl border-none text-blue-700 text-center">
                        <option value="20" <?= $limit == 20 ? 'selected' : '' ?>>20 فاتورة</option>
                        <option value="50" <?= $limit == 50 ? 'selected' : '' ?>>50 فاتورة</option>
                        <option value="100" <?= $limit == 100 ? 'selected' : '' ?>>100 فاتورة</option>
                        <option value="all" <?= $limit > 1000 ? 'selected' : '' ?>>الكل (بطيء)</option>
                    </select>
                </div>
                <a href="?search=&name_search=" class="p-4 bg-slate-800 text-white rounded-2xl font-black shadow-lg text-center flex items-center justify-center"><i class="fas fa-sync-alt"></i></a>
            </form>
        </div>

        <div class="bg-white rounded-[2.5rem] shadow-sm border border-slate-100 overflow-hidden">
            <div class="overflow-x-auto">
                <table class="w-full text-right" id="billsTable">
                    <thead class="bg-slate-50 text-slate-400 text-[10px] font-black uppercase tracking-widest border-b">
                        <tr>
                            <th class="p-6 text-center">الفاتورة</th>
                            <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 font-bold italic">
                        <?php foreach($all_bills as $b): 
                            $lbp_val = round($b['amount_usd'] * ($b['exchange_rate'] ?: 0));
                            $is_meter = ($b['system_type'] == 'meter');
                            
                            // تعقب الحساب المطور (Trace)
                            $trace = "";
                            if($is_meter) {
                                $cons = calculateConsumption($b['current_reading'], $b['previous_reading']);
                                $month_cost_lbp = ($cons * $b['price_kwh']) + ($b['monthly_fixed_fee'] ?? 0);
                                $month_cost_usd = $month_cost_lbp / ($b['exchange_rate'] ?: 1);
                                $old_debt = $b['amount_usd'] - $month_cost_usd;
                                
                                $trace = "تحليل الاستهلاك (عداد):\n" .
                                         "- القراءة الحالية: " . number_format($b['current_reading'], 2) . "\n" .
                                         "- القراءة السابقة: " . number_format($b['previous_reading'], 2) . "\n" .
                                         "- الاستهلاك الحقيقي: $cons كيلوواط\n" .
                                         "- كلفة الشهر: " . number_format($month_cost_lbp) . " ل.ل\n" .
                                         "- رصيد/دين سابق مضاف: $" . number_format($old_debt, 2) . "\n" .
                                         "- المجموع الكلي بالفاتورة: $" . number_format($b['amount_usd'], 2);
                            } else {
                                $rate = ($b['custom_amp_price'] > 0) ? $b['custom_amp_price'] : $b['price_amp'];
                                $trace = "تحليل (أمبير):\n- (" . ($b['ampere_qty']??0) . " أمبير × $rate $) + (" . ($b['ampere_qty']??0) * ($b['fee_per_rated_amp']??0) . " رسوم) + (" . number_format(($b['monthly_fixed_fee']??0) / ($b['exchange_rate']?:1), 2) . " ثابت محول)";
                            }

                            $wa_msg = "تحية من أسامة إلكتريك ⚡\nعزيزي " . $b['customer_name'] . " (علبة: " . ($b['box_no'] ?: '---') . ")\nفاتورة " . ($is_meter ? 'العداد' : 'الأمبير') . " لشهر " . $b['month'] . "/" . $b['year'] . " جاهزة.\n";
                            $wa_msg .= $is_meter ? "المبلغ: " . number_format($lbp_val) . " ل.ل" : "المبلغ: $" . number_format($b['amount_usd'], 2);
                            $wa_msg .= "\nيرجى التسديد وشكراً.";
                            $wa_url = "https://wa.me/" . preg_replace('/[^0-9]/', '', $b['phone']) . "?text=" . urlencode($wa_msg);
                        ?>
                        <tr class="hover:bg-indigo-50/10 transition group">
                            <td class="p-6 text-center font-mono text-xs font-black text-indigo-500"><?= $b['bill_number'] ?></td>
                            <td class="p-6">
                                <div class="flex items-center gap-2">
                                    <span class="font-black text-slate-800"><?= htmlspecialchars($b['customer_name']) ?></span>
                                    <?php if($b['customer_status'] == 0): ?>
                                        <span class="bg-rose-100 text-rose-600 px-2 py-0.5 rounded text-[8px] font-black uppercase">واقف 🛑</span>
                                    <?php endif; ?>
                                </div>
                                <div class="text-[9px] text-slate-400 uppercase">
                                    العلبة: <?= $b['box_no'] ?: '---' ?> | #<?= $b['sub_no'] ?>
                                    <?php if($b['phone']): ?> | <i class="fas fa-phone"></i> <?= $b['phone'] ?><?php endif; ?>
                                </div>
                            </td>
                            <td class="p-6 text-center">
                                <span class="px-3 py-1 rounded-xl text-[10px] font-black <?= $is_meter ? 'bg-blue-50 text-blue-600' : 'bg-amber-50 text-amber-600' ?>">
                                    <?= $is_meter ? 'عداد (LBP)' : 'أمبير (USD)' ?>
                                </span>
                            </td>
                            <td class="p-6 text-center cursor-help" title="<?= $trace ?>">
                                <?php if($is_meter): ?>
                                    <div class="text-lg font-black text-slate-800"><?= number_format($lbp_val) ?> <small>ل.ل</small></div>
                                    <div class="text-[10px] text-slate-400 italic">$<?= number_format($b['amount_usd'], 2) ?></div>
                                <?php else: ?>
                                    <div class="text-lg font-black text-slate-800">$<?= number_format($b['amount_usd'], 2) ?></div>
                                    <div class="text-[10px] text-slate-400 italic"><?= number_format($lbp_val) ?> ل.ل</div>
                                <?php endif; ?>
                            </td>
                            <td class="p-6 text-center">
                                <span class="px-3 py-1 rounded-full text-[10px] font-black uppercase <?= $b['status'] == 'paid' ? 'bg-emerald-100 text-emerald-700' : 'bg-rose-100 text-rose-700' ?>">
                                    <?= $b['status'] == 'paid' ? 'مدفوعة' : 'غير مدفوعة' ?>
                                </span>
                            </td>
                            <td class="p-6 text-center">
                                <div class="flex justify-center gap-2">
                                    <a href="<?= $wa_url ?>" target="_blank" class="w-9 h-9 bg-emerald-50 text-emerald-600 rounded-xl flex items-center justify-center hover:bg-emerald-500 hover:text-white transition shadow-sm" title="إرسال عبر واتساب"><i class="fab fa-whatsapp"></i></a>

                                    <a href="?recalc_id=<?= $b['id'] ?>&search=<?= urlencode($f_search) ?>&name_search=<?= urlencode($f_name_search) ?>&page=<?= $page ?>" class="w-9 h-9 bg-amber-50 text-amber-600 rounded-xl flex items-center justify-center hover:bg-amber-600 hover:text-white transition shadow-sm" title="إعادة الحساب"><i class="fas fa-sync-alt"></i></a>
                                    
                                    <?php if($b['status'] == 'unpaid'): ?>
                                        <a href="?pay_id=<?= $b['id'] ?>&search=<?= urlencode($f_search) ?>&name_search=<?= urlencode($f_name_search) ?>&page=<?= $page ?>" onclick="return confirm('تأكيد القبض؟')" class="w-9 h-9 bg-indigo-50 text-indigo-600 rounded-xl flex items-center justify-center hover:bg-indigo-600 hover:text-white transition shadow-sm" title="تسديد"><i class="fas fa-check"></i></a>
                                    <?php else: ?>
                                        <a href="?unpay_id=<?= $b['id'] ?>&search=<?= urlencode($f_search) ?>&name_search=<?= urlencode($f_name_search) ?>&page=<?= $page ?>" onclick="return confirm('تراجع عن التسديد؟')" class="w-9 h-9 bg-slate-100 text-slate-400 rounded-xl flex items-center justify-center hover:bg-orange-500 hover:text-white transition shadow-sm" title="تراجع"><i class="fas fa-undo"></i></a>
                                    <?php endif; ?>

                                    <a href="print_bill.php?id=<?= $b['id'] ?>" target="_blank" class="w-9 h-9 bg-slate-100 text-slate-400 rounded-xl flex items-center justify-center hover:bg-blue-600 hover:text-white transition shadow-sm"><i class="fas fa-print text-sm"></i></a>
                                    
                                    <?php if($can_see_all): ?>
                                    <a href="?delete_id=<?= $b['id'] ?>&search=<?= urlencode($f_search) ?>&name_search=<?= urlencode($f_name_search) ?>&page=<?= $page ?>" onclick="return confirm('حذف الفاتورة؟')" class="w-9 h-9 bg-rose-50 text-rose-500 rounded-xl flex items-center justify-center hover:bg-rose-500 hover:text-white transition shadow-sm"><i class="fas fa-trash-alt"></i></a>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if(empty($all_bills)): ?>
                            <tr><td colspan="6" class="p-20 text-center text-slate-300 italic font-black text-lg">لا توجد فواتير تطابق معايير البحث والفلترة.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <?php if ($total_pages > 1): ?>
            <div class="p-8 bg-slate-50 border-t border-slate-100 flex flex-wrap justify-center items-center gap-2">
                <?php if ($page > 1): ?>
                    <a href="?<?= $query_string ?>&page=<?= $page - 1 ?>" class="px-4 py-2 bg-white rounded-xl font-black text-slate-600 border border-slate-200 hover:bg-blue-600 hover:text-white transition shadow-sm">السابق</a>
                <?php endif; ?>

                <?php 
                $start = max(1, $page - 2);
                $end = min($total_pages, $page + 2);
                if($start > 1) echo "<span class='px-2 text-slate-300'>...</span>";
                for ($i = $start; $i <= $end; $i++): ?>
                    <?php if ($i == $page): ?>
                        <span class="px-4 py-2 bg-blue-600 text-white rounded-xl font-black shadow-lg"><?= $i ?></span>
                    <?php else: ?>
                        <a href="?<?= $query_string ?>&page=<?= $i ?>" class="px-4 py-2 bg-white rounded-xl font-black text-slate-600 border border-slate-200 hover:bg-blue-50 transition shadow-sm"><?= $i ?></a>
                    <?php endif; ?>
                <?php endfor;
                if($end < $total_pages) echo "<span class='px-2 text-slate-300'>...</span>"; ?>

                <?php if ($page < $total_pages): ?>
                    <a href="?<?= $query_string ?>&page=<?= $page + 1 ?>" class="px-4 py-2 bg-white rounded-xl font-black text-slate-600 border border-slate-200 hover:bg-blue-600 hover:text-white transition shadow-sm">التالي</a>
                <?php endif; ?>
            </div>
            <?php endif; ?>
        </div>
        
        <div class="mt-4 text-center text-[10px] font-black text-slate-400 uppercase italic">
            عرض <?= count($all_bills) ?> من أصل <?= $total_records ?> فاتورة موجودة
        </div>
    </div>

    <?php if($can_see_all): ?>
    <div id="genModal" class="fixed inset-0 bg-slate-900/60 hidden items-center justify-center z-50 p-6 backdrop-blur-sm font-black italic">
        <div class="bg-white rounded-[3rem] w-full max-w-md shadow-2xl animate-in zoom-in duration-300">
            <div class="p-8 bg-blue-600 text-white flex justify-between items-center italic font-black">
                <h3>إصدار فواتير دورة جديدة</h3>
                <button onclick="document.getElementById('genModal').classList.add('hidden')" class="text-3xl">&times;</button>
            </div>
            <form method="POST" class="p-10 space-y-6">
                <input type="hidden" name="generate_action" value="1">
                <div class="grid grid-cols-2 gap-4">
                    <select name="month" class="p-4 bg-slate-50 rounded-2xl border-none outline-none font-bold"><?php for($m=1;$m<=12;$m++) echo "<option value='$m' ".(date('n')==$m?'selected':'').">$m</option>"; ?></select>
                    <select name="year" class="p-4 bg-slate-50 rounded-2xl border-none outline-none font-bold">
                        <?php for($y=2024;$y<=2027;$y++) echo "<option value='$y' ".(date('Y')==$y?'selected':'').">$y</option>"; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-[10px] font-black text-blue-600 mb-2 uppercase tracking-widest text-center">إصدار لـ:</label>
                    <select name="target_system" class="w-full p-4 bg-blue-50 text-blue-700 rounded-2xl border-none font-black outline-none cursor-pointer">
                        <option value="all">الكل (عدادات + أمبير)</option>
                        <option value="meter">العدادات فقط (استهلاك)</option>
                        <option value="ampere">الأمبير فقط (سلف مقدماً)</option>
                    </select>
                </div>
                <button type="submit" class="w-full p-6 bg-blue-600 text-white rounded-3xl font-black shadow-xl hover:bg-black transition italic uppercase">بدء الإصدار الآن</button>
            </form>
        </div>
    </div>
    <?php endif; ?>

    <script>
        let searchTimer;
        document.getElementById('liveSearchInput').addEventListener('input', function() {
            clearTimeout(searchTimer);
            searchTimer = setTimeout(() => {
                document.getElementById('filterForm').submit();
            }, 500);
        });

        document.getElementById('liveSearchInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                document.getElementById('filterForm').submit();
            }
        });

        document.getElementById('nameSearchInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                document.getElementById('filterForm').submit();
            }
        });

        window.onload = function() {
            <?php if($print_id): ?> window.open('print_bill.php?id=<?= $print_id ?>', '_blank'); <?php endif; ?>
            const liveInput = document.getElementById('liveSearchInput');
            const nameInput = document.getElementById('nameSearchInput');
            
            if(liveInput.value) {
                liveInput.focus();
                const val = liveInput.value;
                liveInput.value = '';
                liveInput.value = val;
            } else if (nameInput.value) {
                nameInput.focus();
                const val = nameInput.value;
                nameInput.value = '';
                nameInput.value = val;
            }
        };
    </script>
</body>
</html>