<?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';
 $is_ar = ($lang === 'ar');
 $dir = $is_ar ? 'rtl' : 'ltr';

 $texts = [
    'ar' => [
        'title' => 'إدارة المشتركين | أسامة إلكتريك',
        'header' => 'سجل المشتركين الشامل',
        'sub_header' => 'إدارة سعة الأمبير، العلب، والأرصدة بدقة',
        'add_cust' => 'إضافة مشترك جديد',
        'search_placeholder' => 'اسم، اشتراك، هاتف، علبة...',
        'name' => 'اسم المشترك',
        'sub_no' => 'رقم الاشتراك',
        'box_no' => 'العلبة',
        'phone' => 'رقم الهاتف',
        'system' => 'النظام',
        'area' => 'المنطقة',
        'address' => 'العنوان',
        'old_balance' => 'رصيد سابق ($)',
        'insurance' => 'تأمين ($)',
        'fixed_fee' => 'رسم الاشتراك الثابت (L.L)',
        'amp_price' => 'سعر الأمبير ($)',
        'initial_reading' => 'قراءة البداية',
        'ampere_qty' => 'الأمبيرات (A)',
        'notes' => 'الملاحظات',
        'status' => 'الحالة',
        'active' => 'نشط',
        'inactive' => 'ملغى / معطل',
        'exempt' => 'زبون معفى (مجاني)',
        'actions' => 'العمليات',
        'save' => 'حفظ البيانات',
        'cancel' => 'إلغاء',
        'edit' => 'تعديل',
        'delete' => 'حذف',
        'statement' => 'كشف حساب',
        'success' => 'تم حفظ البيانات وتحديث السجل بنجاح',
        'meter' => 'عداد',
        'ampere' => 'أمبير',
        'home' => 'الرئيسية',
        'all' => 'الكل',
        'added_by' => 'الموظف المسؤول',
        'filter_user' => 'فلترة حسب الموظف',
        'filter_amp' => 'فلترة حسب الأمبير',
        'copied' => 'تم النسخ!',
        'no_results' => 'لا توجد نتائج تطابق معايير البحث والفلترة',
        'showing' => 'عرض',
        'of' => 'من أصل',
        'customer' => 'مشترك موجود',
        'confirm_disable' => 'هل أنت متأكد من تعطيل هذا المشترك؟',
        'confirm_enable' => 'إعادة تفعيل المشترك؟',
        'confirm_delete' => 'حذف نهائي؟ لا يمكن التراجع!'
    ]
];

try {
    $pdo->exec("ALTER TABLE `customers` ADD COLUMN IF NOT EXISTS `sub_no` VARCHAR(50) NULL AFTER `id` ");
    $pdo->exec("ALTER TABLE `customers` ADD COLUMN IF NOT EXISTS `box_no` VARCHAR(50) NULL AFTER `sub_no` ");
    $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` ");
    $pdo->exec("ALTER TABLE `customers` MODIFY COLUMN `ampere_qty` DECIMAL(10,2) DEFAULT 0");
    $pdo->exec("ALTER TABLE `customers` MODIFY COLUMN `monthly_fixed_fee` DECIMAL(12,2) DEFAULT 0");
    $pdo->exec("ALTER TABLE `customers` ADD COLUMN IF NOT EXISTS `custom_amp_price` DECIMAL(10,2) DEFAULT 0 AFTER `monthly_fixed_fee` ");
} catch (PDOException $e) {}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    $name = trim($_POST['name']);
    $sub_no = trim($_POST['sub_no']);
    $box_no = trim($_POST['box_no']);
    $phone = trim($_POST['phone']);
    $area = trim($_POST['area']);
    $address = trim($_POST['address'] ?? '');
    $system_type = $_POST['system_type'];
    $old_balance = (float)$_POST['old_balance'];
    $insurance = (float)$_POST['insurance'];
    $fixed_fee = (float)$_POST['monthly_fixed_fee'];
    $custom_amp_price = (float)$_POST['custom_amp_price'];
    $initial_reading = (float)$_POST['initial_reading'];
    $ampere_qty = (float)$_POST['ampere_qty'];
    $notes = trim($_POST['notes']);
    $status = $_POST['status'];
    $is_exempt = isset($_POST['is_exempt']) ? 1 : 0;
    $cust_id = $_POST['cust_id'] ?? null;

    $assigned_user_id = ($can_manage_all && isset($_POST['created_by'])) ? (int)$_POST['created_by'] : $logged_user_id;

    try {
        if ($action == 'add') {
            $stmt = $pdo->prepare("INSERT INTO customers (name, sub_no, box_no, created_by, phone, area, address, system_type, initial_reading, ampere_qty, monthly_fixed_fee, custom_amp_price, old_balance, insurance, notes, status, is_exempt) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$name, $sub_no, $box_no, $assigned_user_id, $phone, $area, $address, $system_type, $initial_reading, $ampere_qty, $fixed_fee, $custom_amp_price, $old_balance, $insurance, $notes, $status, $is_exempt]);
            $message = $texts['ar']['success'];
        } elseif ($action == 'edit') {
            $check_sql = $can_manage_all ? "SELECT id FROM customers WHERE id = ?" : "SELECT id FROM customers WHERE id = ? AND created_by = ?";
            $check_params = $can_manage_all ? [$cust_id] : [$cust_id, $logged_user_id];
            $can_edit = $pdo->prepare($check_sql);
            $can_edit->execute($check_params);

            if ($can_edit->rowCount() > 0) {
                $stmt = $pdo->prepare("UPDATE customers SET name=?, sub_no=?, box_no=?, phone=?, area=?, address=?, system_type=?, initial_reading=?, ampere_qty=?, monthly_fixed_fee=?, custom_amp_price=?, old_balance=?, insurance=?, notes=?, status=?, is_exempt=?, created_by=? WHERE id=?");
                $stmt->execute([$name, $sub_no, $box_no, $phone, $area, $address, $system_type, $initial_reading, $ampere_qty, $fixed_fee, $custom_amp_price, $old_balance, $insurance, $notes, $status, $is_exempt, $assigned_user_id, $cust_id]);
                $message = $texts['ar']['success'];
            } else { throw new Exception("ليس لديك صلاحية لتعديل هذا المشترك."); }
        }
    } catch (Exception $e) { 
        $message = "خطأ: " . ($e->getCode() == 23000 ? "رقم الاشتراك مكرر!" : $e->getMessage());
        $msg_type = 'error';
    }
}

if (isset($_GET['delete'])) {
    $del_id = $_GET['delete'];
    $check_sql = $can_manage_all ? "DELETE FROM customers WHERE id = ?" : "DELETE FROM customers WHERE id = ? AND created_by = ?";
    $check_params = $can_manage_all ? [$del_id] : [$del_id, $logged_user_id];
    $pdo->prepare($check_sql)->execute($check_params);
    header("Location: customers.php"); exit;
}

if (isset($_GET['toggle_status']) && isset($_GET['id'])) {
    $t_id = $_GET['id'];
    $new_status = (int)$_GET['toggle_status'];
    
    $check_sql = $can_manage_all ? "SELECT id FROM customers WHERE id = ?" : "SELECT id FROM customers WHERE id = ? AND created_by = ?";
    $check_params = $can_manage_all ? [$t_id] : [$t_id, $logged_user_id];
    
    $stmt_check = $pdo->prepare($check_sql);
    $stmt_check->execute($check_params);
    
    if ($stmt_check->rowCount() > 0) {
        $pdo->prepare("UPDATE customers SET status = ? WHERE id = ?")->execute([$new_status, $t_id]);
        
        $redirect_query = $_GET;
        unset($redirect_query['toggle_status'], $redirect_query['id']);
        header("Location: customers.php?" . http_build_query($redirect_query)); 
        exit;
    }
}

 $f_system = $_GET['f_system'] ?? '';
 $f_status = $_GET['f_status'] ?? '';
 $f_box = $_GET['f_box'] ?? '';
 $f_user = $_GET['f_user'] ?? ''; 
 $f_search = $_GET['search'] ?? '';
 $f_name_search = $_GET['name_search'] ?? '';
 $f_ampere = $_GET['f_ampere'] ?? '';

 $limit = isset($_GET['limit']) ? (($_GET['limit'] == 'all') ? 999999 : (int)$_GET['limit']) : 20;
 $page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
 $offset = ($page - 1) * $limit;

 $role_condition = $can_manage_all ? "1=1" : "c.created_by = :logged_uid";
 $where_clauses = [$role_condition];
 $params = $can_manage_all ? [] : [':logged_uid' => $logged_user_id];

if ($can_manage_all && $f_user !== '') {
    $where_clauses[] = "c.created_by = :f_uid";
    $params[':f_uid'] = $f_user;
}
if ($f_system) { $where_clauses[] = "c.system_type = :sys"; $params[':sys'] = $f_system; }
if ($f_status !== '') { $where_clauses[] = "c.status = :st"; $params[':st'] = $f_status; }
if ($f_box) { $where_clauses[] = "c.box_no = :box"; $params[':box'] = $f_box; }
if ($f_ampere !== '') { 
    $where_clauses[] = "c.ampere_qty = :amp"; 
    $params[':amp'] = (float)$f_ampere; 
}
if ($f_search) {
    $where_clauses[] = "(c.name LIKE :s1 OR c.phone LIKE :s2 OR c.sub_no LIKE :s3 OR c.box_no LIKE :s4)";
    $params[':s1'] = "%$f_search%";
    $params[':s2'] = "%$f_search%";
    $params[':s3'] = "%$f_search%";
    $params[':s4'] = "%$f_search%";
}
if ($f_name_search) {
    $where_clauses[] = "c.name LIKE :name_search";
    $params[':name_search'] = "%$f_name_search%";
}

 $where_sql = implode(" AND ", $where_clauses);

 $count_stmt = $pdo->prepare("SELECT COUNT(*) FROM customers c WHERE $where_sql");
 $count_stmt->execute($params);
 $total_records = $count_stmt->fetchColumn();
 $total_pages = ceil($total_records / $limit);

 $stats_query = "SELECT 
    COUNT(*) as total, 
    SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) as active, 
    SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END) as inactive,
    SUM(CASE WHEN is_exempt = 1 THEN 1 ELSE 0 END) as exempt,
    SUM(ampere_qty) as total_amps, 
    SUM(old_balance) as total_debt,
    SUM(insurance) as total_insurance
FROM customers c WHERE $where_sql";
 $stmt_stats = $pdo->prepare($stats_query);
 $stmt_stats->execute($params);
 $stats = $stmt_stats->fetch();

 $global_stats_query = "SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) as active,
    SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END) as inactive,
    SUM(CASE WHEN is_exempt = 1 THEN 1 ELSE 0 END) as exempt
FROM customers c WHERE $role_condition";
 $stmt_global = $pdo->prepare($global_stats_query);
 $stmt_global->execute($can_manage_all ? [] : [':logged_uid' => $logged_user_id]);
 $global_stats = $stmt_global->fetch();

 $query = "SELECT c.*, u.name as creator_name 
          FROM customers c 
          LEFT JOIN users u ON c.created_by = u.id 
          WHERE $where_sql 
          ORDER BY c.id DESC LIMIT $offset, $limit";
 $stmt = $pdo->prepare($query);
 $stmt->execute($params);
 $customers = $stmt->fetchAll();

 $box_query = "SELECT DISTINCT box_no FROM customers c WHERE box_no IS NOT NULL AND box_no != '' AND $role_condition ORDER BY box_no ASC";
 $stmt_boxes = $pdo->prepare($box_query);
if(!$can_manage_all) { $stmt_boxes->execute([':logged_uid' => $logged_user_id]); } else { $stmt_boxes->execute(); }
 $unique_boxes = $stmt_boxes->fetchAll(PDO::FETCH_COLUMN);

 $amp_query = "SELECT DISTINCT ampere_qty FROM customers c WHERE $role_condition ORDER BY ampere_qty ASC";
 $stmt_amps = $pdo->prepare($amp_query);
if(!$can_manage_all) { $stmt_amps->execute([':logged_uid' => $logged_user_id]); } else { $stmt_amps->execute(); }
 $unique_amps = $stmt_amps->fetchAll(PDO::FETCH_COLUMN);

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

function buildPageUrl($target_page, $current_get) {
    $params = $current_get;
    $params['page'] = $target_page;
    return "customers.php?" . http_build_query($params);
}

function buildFilterUrl($overrides, $current_get) {
    $params = $current_get;
    foreach ($overrides as $key => $val) {
        if ($val === null) {
            unset($params[$key]);
        } else {
            $params[$key] = $val;
        }
    }
    unset($params['page']);
    return "customers.php?" . http_build_query($params);
}
?>
<!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">
    <style>
        body { font-family: 'Cairo', sans-serif; background-color: #f1f5f9; }
        .modal-body { max-height: calc(100vh - 280px); overflow-y: auto; }
        .modal-body::-webkit-scrollbar { width: 6px; }
        .modal-body::-webkit-scrollbar-track { background: #f1f5f9; border-radius: 10px; }
        .modal-body::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 10px; }
        .modal-body::-webkit-scrollbar-thumb:hover { background: #94a3b8; }
        .toggle-checkbox:checked { right: 0; border-color: #2563eb; }
        .toggle-checkbox:checked + .toggle-label { background-color: #2563eb; }
        .stat-card { transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); }
        .stat-card:hover { transform: translateY(-5px); box-shadow: 0 20px 40px -12px rgba(0,0,0,0.15); }
        .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); }
        .copy-flash { animation: copyPulse 0.6s ease-out; }
        @keyframes copyPulse {
            0% { background-color: #2563eb; color: white; transform: scale(1.1); }
            100% { background-color: transparent; color: inherit; transform: scale(1); }
        }
        .row-inactive { opacity: 0.5; }
        .row-inactive:hover { opacity: 0.8; }
        @media (max-width: 1024px) {
            .desktop-table { display: none; }
            .mobile-cards { display: flex !important; }
        }
        @media (min-width: 1025px) {
            .mobile-cards { display: none !important; }
        }
        .mobile-card { transition: all 0.2s; border-right: 4px solid transparent; }
        .mobile-card:hover { border-right-color: #2563eb; transform: translateX(-4px); }
        .mobile-card.card-inactive { border-right-color: #fca5a5; opacity: 0.6; }
        @keyframes modalIn {
            from { opacity: 0; transform: scale(0.95) translateY(20px); }
            to { opacity: 1; transform: scale(1) translateY(0); }
        }
    </style>
</head>
<body class="pb-12 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 lg: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-users-gear"></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">
                        <?php if($can_manage_all): ?>لوحة تحكم الإدارة: إدارة الموظفين والزبائن<?php else: ?>إدارة المشتركين الشخصيين<?php endif; ?>
                    </p>
                </div>
            </div>
            <div class="flex gap-3 flex-wrap justify-center">
                <button onclick="openModal('add')" class="bg-blue-600 hover:bg-black text-white px-8 py-3 rounded-2xl font-black transition flex items-center gap-2 shadow-lg shadow-blue-100 italic">
                    <i class="fas fa-plus-circle"></i> إضافة مشترك
                </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>الرئيسية
                </a>
            </div>
        </div>

        <div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-8 gap-3 mb-8 italic">
            <div class="stat-card bg-white p-4 rounded-[1.5rem] shadow-sm border border-slate-100 text-center">
                <p class="text-[9px] font-black text-slate-400 uppercase mb-1">المعروضين</p>
                <h3 class="text-xl font-black text-slate-800 italic"><?= number_format($total_records) ?></h3>
            </div>
            <div class="stat-card bg-white p-4 rounded-[1.5rem] shadow-sm border border-slate-100 text-center border-b-4 border-emerald-500">
                <p class="text-[9px] font-black text-emerald-500 uppercase mb-1">نشط</p>
                <h3 class="text-xl font-black text-emerald-600 italic"><?= number_format($stats['active']) ?></h3>
            </div>
            <div class="stat-card bg-white p-4 rounded-[1.5rem] shadow-sm border border-slate-100 text-center border-b-4 border-rose-400">
                <p class="text-[9px] font-black text-rose-400 uppercase mb-1">معطل</p>
                <h3 class="text-xl font-black text-rose-500 italic"><?= number_format($stats['inactive']) ?></h3>
            </div>
            <div class="stat-card bg-white p-4 rounded-[1.5rem] shadow-sm border border-slate-100 text-center border-b-4 border-amber-400">
                <p class="text-[9px] font-black text-amber-500 uppercase mb-1">معفى</p>
                <h3 class="text-xl font-black text-amber-600 italic"><?= number_format($stats['exempt']) ?></h3>
            </div>
            <div class="stat-card bg-indigo-600 p-4 rounded-[1.5rem] shadow-lg text-center text-white col-span-2">
                <p class="text-[9px] font-black uppercase mb-1 opacity-70">إجمالي الأمبير</p>
                <h3 class="text-2xl font-black italic"><?= number_format(floatval($stats['total_amps']), 1) ?> <small class="text-xs opacity-70">A</small></h3>
            </div>
            <div class="stat-card bg-rose-600 p-4 rounded-[1.5rem] shadow-lg text-center text-white">
                <p class="text-[9px] font-black uppercase mb-1 opacity-70">الديون</p>
                <h3 class="text-lg font-black italic">$<?= number_format($stats['total_debt'], 0) ?></h3>
            </div>
            <div class="stat-card bg-emerald-600 p-4 rounded-[1.5rem] shadow-lg text-center text-white">
                <p class="text-[9px] font-black uppercase mb-1 opacity-70">التأمينات</p>
                <h3 class="text-lg font-black italic">$<?= number_format($stats['total_insurance'], 0) ?></h3>
            </div>
        </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-8 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="flex flex-wrap gap-2 mb-6 items-center">
            <span class="text-[10px] font-black text-slate-400 uppercase ml-2"><i class="fas fa-bolt ml-1"></i>فلترة سريعة:</span>
            
            <a href="<?= buildFilterUrl(['f_status' => null, 'f_system' => null, 'f_box' => null, 'f_user' => null, 'f_ampere' => null, 'search' => null, 'name_search' => null], $_GET) ?>" 
               class="quick-pill px-4 py-2 rounded-full text-xs font-black uppercase italic <?php if(empty($f_status) && empty($f_system) && empty($f_box) && empty($f_user) && empty($f_ampere) && empty($f_search) && empty($f_name_search)): ?>bg-blue-600 text-white active-pill<?php else: ?>bg-white text-slate-600 border border-slate-200 hover:bg-blue-50<?php endif; ?> shadow-sm transition">
                <i class="fas fa-globe ml-1"></i>الكل (<?= number_format($global_stats['total']) ?>)
            </a>
            
            <a href="<?= buildFilterUrl(['f_status' => '1', 'f_system' => null, 'f_box' => null, 'f_user' => null, 'f_ampere' => null, 'search' => null, 'name_search' => null], $_GET) ?>" 
               class="quick-pill px-4 py-2 rounded-full text-xs font-black uppercase italic <?php if($f_status === '1' && empty($f_system) && empty($f_box) && empty($f_user) && empty($f_ampere)): ?>bg-emerald-600 text-white active-pill<?php else: ?>bg-white text-emerald-600 border border-emerald-100 hover:bg-emerald-50<?php endif; ?> shadow-sm transition">
                <i class="fas fa-check-circle ml-1"></i>نشط (<?= number_format($global_stats['active']) ?>)
            </a>
            
            <a href="<?= buildFilterUrl(['f_status' => '0', 'f_system' => null, 'f_box' => null, 'f_user' => null, 'f_ampere' => null, 'search' => null, 'name_search' => null], $_GET) ?>" 
               class="quick-pill px-4 py-2 rounded-full text-xs font-black uppercase italic <?php if($f_status === '0' && empty($f_system) && empty($f_box) && empty($f_user) && empty($f_ampere)): ?>bg-rose-600 text-white active-pill<?php else: ?>bg-white text-rose-500 border border-rose-100 hover:bg-rose-50<?php endif; ?> shadow-sm transition">
                <i class="fas fa-ban ml-1"></i>معطل (<?= number_format($global_stats['inactive']) ?>)
            </a>
            
            <a href="<?= buildFilterUrl(['f_status' => null, 'f_system' => 'ampere', 'f_box' => null, 'f_user' => null, 'f_ampere' => null, 'search' => null, 'name_search' => null], $_GET) ?>" 
               class="quick-pill px-4 py-2 rounded-full text-xs font-black uppercase italic <?php if($f_system === 'ampere' && empty($f_status) && empty($f_box)): ?>bg-orange-600 text-white active-pill<?php else: ?>bg-white text-orange-600 border border-orange-100 hover:bg-orange-50<?php endif; ?> shadow-sm transition">
                <i class="fas fa-bolt ml-1"></i>أمبير فقط
            </a>
            
            <a href="<?= buildFilterUrl(['f_status' => null, 'f_system' => 'meter', 'f_box' => null, 'f_user' => null, 'f_ampere' => null, 'search' => null, 'name_search' => null], $_GET) ?>" 
               class="quick-pill px-4 py-2 rounded-full text-xs font-black uppercase italic <?php if($f_system === 'meter' && empty($f_status) && empty($f_box)): ?>bg-blue-600 text-white active-pill<?php else: ?>bg-white text-blue-600 border border-blue-100 hover:bg-blue-50<?php endif; ?> shadow-sm transition">
                <i class="fas fa-gauge-high ml-1"></i>عداد فقط
            </a>
        </div>

        <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-4 xl:grid-cols-9 gap-4 items-end italic font-bold text-sm">
                <div>
                    <label class="block text-[10px] font-black text-slate-400 mb-2 uppercase tracking-widest text-center">بحث شامل <span class="text-blue-500">(Live)</span></label>
                    <input type="text" name="search" id="liveSearchInput" value="<?= htmlspecialchars($f_search) ?>" placeholder="<?= $texts['ar']['search_placeholder'] ?>" class="w-full p-3.5 bg-slate-50 rounded-2xl border-none font-bold outline-none focus:ring-2 focus:ring-blue-600 shadow-inner text-sm">
                </div>
                
                <div>
                    <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-3.5 bg-emerald-50 text-emerald-700 rounded-2xl border-none font-bold outline-none focus:ring-2 focus:ring-emerald-500 shadow-inner text-sm">
                </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" onchange="this.form.submit()" class="w-full p-3.5 bg-blue-50/50 rounded-2xl border-none font-black text-blue-700 cursor-pointer outline-none text-sm">
                        <option value="">الكل</option>
                        <?php foreach($all_users as $u): ?>
                            <option value="<?= $u['id'] ?>" <?php if($f_user == $u['id']): ?>selected<?php endif; ?>><?= htmlspecialchars($u['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php endif; ?>

                <div>
                    <label class="block text-[10px] font-black text-slate-400 mb-2 uppercase">العلبة</label>
                    <select name="f_box" onchange="this.form.submit()" class="w-full p-3.5 bg-slate-50 rounded-2xl border-none cursor-pointer outline-none text-sm">
                        <option value="">كل العلب</option>
                        <?php foreach($unique_boxes as $box): ?>
                            <option value="<?= htmlspecialchars($box) ?>" <?php if($f_box == $box): ?>selected<?php endif; ?>><?= htmlspecialchars($box) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div>
                    <label class="block text-[10px] font-black text-indigo-600 mb-2 uppercase"><i class="fas fa-bolt ml-1"></i>الأمبير</label>
                    <select name="f_ampere" onchange="this.form.submit()" class="w-full p-3.5 bg-indigo-50/50 rounded-2xl border-none font-black text-indigo-700 cursor-pointer outline-none text-sm">
                        <option value="">كل السعات</option>
                        <?php foreach($unique_amps as $amp): ?>
                            <option value="<?= floatval($amp) ?>" <?php if($f_ampere !== '' && floatval($f_ampere) == floatval($amp)): ?>selected<?php endif; ?>><?= floatval($amp) ?> أمبير</option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div>
                    <label class="block text-[10px] font-black text-slate-400 mb-2 uppercase">النظام</label>
                    <select name="f_system" onchange="this.form.submit()" class="w-full p-3.5 bg-slate-50 rounded-2xl border-none cursor-pointer outline-none text-sm text-center">
                        <option value="">الكل</option>
                        <option value="meter" <?php if($f_system == 'meter'): ?>selected<?php endif; ?>>عداد</option>
                        <option value="ampere" <?php if($f_system == 'ampere'): ?>selected<?php endif; ?>>أمبير</option>
                    </select>
                </div>
                <div>
                    <label class="block text-[10px] font-black text-slate-400 mb-2 uppercase">الحالة</label>
                    <select name="f_status" onchange="this.form.submit()" class="w-full p-3.5 bg-slate-50 rounded-2xl border-none cursor-pointer outline-none text-sm text-center">
                        <option value="">الكل</option>
                        <option value="1" <?php if($f_status === '1'): ?>selected<?php endif; ?>>نشط</option>
                        <option value="0" <?php if($f_status === '0'): ?>selected<?php endif; ?>>معطل</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-3.5 bg-blue-50 rounded-2xl border-none text-blue-700 text-center font-black text-sm">
                        <option value="20" <?php if($limit == 20): ?>selected<?php endif; ?>>20</option>
                        <option value="50" <?php if($limit == 50): ?>selected<?php endif; ?>>50</option>
                        <option value="100" <?php if($limit == 100): ?>selected<?php endif; ?>>100</option>
                        <option value="all" <?php if($limit > 1000): ?>selected<?php endif; ?>>الكل</option>
                    </select>
                </div>
                <button type="submit" class="bg-slate-800 text-white p-3.5 rounded-2xl font-black shadow-lg hover:bg-black transition flex justify-center items-center"><i class="fas fa-search"></i></button>
            </form>
        </div>

        <div class="bg-white rounded-[2.5rem] shadow-sm border border-slate-100 overflow-hidden">
            <div class="overflow-x-auto desktop-table">
                <table class="w-full text-right font-bold italic" id="customersTable">
                    <thead class="bg-slate-50 text-slate-400 text-[10px] font-black uppercase tracking-widest border-b">
                        <tr>
                            <th class="p-5">#</th>
                            <th class="p-5">المشترك / العلبة</th>
                            <th class="p-5 text-center">الملاحظات</th>
                            <th class="p-5 text-center">الأمبيرات</th>
                            <th class="p-5 text-center">سعر الأمبير</th>
                            <?php if($can_manage_all): ?><th class="p-5 text-center">الموظف</th><?php endif; ?>
                            <th class="p-5 text-center">النظام</th>
                            <th class="p-5 text-center">الرصيد ($)</th>
                            <th class="p-5 text-center">العمليات</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-50 font-bold italic text-sm">
                        <?php foreach($customers as $c): ?>
                        <tr class="hover:bg-blue-50/20 transition group <?php if($c['status'] == 0): ?>row-inactive<?php endif; ?>">
                            <td class="p-5">
                                <span class="text-blue-600 font-mono italic cursor-pointer hover:underline" 
                                      onclick="copyToClipboard('<?php htmlspecialchars(addslashes($c['sub_no'])) ?>', this)" 
                                      title="اضغط للنسخ">
                                    <?php if($c['sub_no']): ?><?= htmlspecialchars($c['sub_no']) ?><?php else: ?>---<?php endif; ?>
                                </span>
                            </td>
                            <td class="p-5">
                                <div class="flex items-center gap-2 flex-wrap">
                                    <span class="text-slate-800 italic font-black"><?= htmlspecialchars($c['name']) ?></span>
                                    <?php if($c['is_exempt']): ?>
                                        <span class="bg-amber-100 text-amber-700 px-2 py-0.5 rounded text-[8px] font-black uppercase shadow-sm">معفى 🎁</span>
                                    <?php endif; ?>
                                    <?php if($c['status'] == 0): ?>
                                        <span class="bg-rose-100 text-rose-600 px-2 py-0.5 rounded text-[8px] font-black uppercase shadow-sm">معطل</span>
                                    <?php endif; ?>
                                </div>
                                <div class="flex flex-wrap gap-1.5 mt-1.5">
                                    <span class="text-[9px] bg-blue-50 text-blue-500 px-2 py-0.5 rounded font-black italic uppercase">علبة: <?php if($c['box_no']): ?><?= htmlspecialchars($c['box_no']) ?><?php else: ?>---<?php endif; ?></span>
                                    <?php if($c['phone']): ?>
                                        <a href="tel:<?= $c['phone'] ?>" class="text-[9px] text-slate-400 hover:text-blue-500 transition"><i class="fas fa-phone text-[7px] ml-0.5"></i><?= $c['phone'] ?></a>
                                    <?php endif; ?>
                                    <?php if($c['area']): ?>
                                        <span class="text-[9px] text-slate-300"><?= htmlspecialchars($c['area']) ?></span>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td class="p-5 text-center">
                                <div class="text-[11px] text-slate-900 font-bold max-w-[140px] truncate mx-auto leading-tight" title="<?= htmlspecialchars($c['notes']) ?>">
                                    <?php if($c['notes']): ?><?= htmlspecialchars($c['notes']) ?><?php else: ?><span class="opacity-10">---</span><?php endif; ?>
                                </div>
                            </td>
                            <td class="p-5 text-center">
                                <span class="bg-slate-900 text-white px-4 py-1.5 rounded-xl font-black text-sm italic shadow-md inline-block min-w-[60px]">
                                    <?= floatval($c['ampere_qty']) ?> A
                                </span>
                            </td>
                            <td class="p-5 text-center">
                                <?php if($c['custom_amp_price'] > 0): ?>
                                    <span class="text-orange-600 font-black">$<?= number_format($c['custom_amp_price'], 2) ?></span>
                                <?php else: ?>
                                    <span class="text-slate-300 font-bold text-xs">عام</span>
                                <?php endif; ?>
                            </td>
                            <?php if($can_manage_all): ?>
                            <td class="p-5 text-center">
                                <span class="text-[10px] font-black text-blue-500 uppercase bg-blue-50 px-3 py-1 rounded-full italic shadow-sm"><?php if($c['creator_name']): ?><?= htmlspecialchars($c['creator_name']) ?><?php else: ?>—<?php endif; ?></span>
                            </td>
                            <?php endif; ?>
                            <td class="p-5 text-center">
                                <span class="px-3 py-1 rounded-full text-[10px] font-black uppercase <?php if($c['system_type'] == 'meter'): ?>bg-blue-100 text-blue-700<?php else: ?>bg-orange-100 text-orange-700<?php endif; ?>">
                                    <?php if($c['system_type'] == 'meter'): ?>عداد<?php else: ?>أمبير<?php endif; ?>
                                </span>
                            </td>
                            <td class="p-5 text-center">
                                <span class="font-black <?php if($c['old_balance'] > 0): ?>text-rose-600<?php else: ?>text-emerald-600<?php endif; ?>"><?php if($c['old_balance'] > 0): ?>-<?php endif; ?>$<?= number_format(abs($c['old_balance']), 2) ?></span>
                            </td>
                            <td class="p-5 text-center">
                                <div class="flex justify-center gap-1.5">
                                    <a href="customer_statement.php?id=<?= $c['id'] ?>" class="w-8 h-8 bg-indigo-50 text-indigo-600 rounded-xl flex items-center justify-center hover:bg-indigo-600 hover:text-white transition shadow-sm text-xs" title="كشف حساب"><i class="fas fa-file-invoice"></i></a>
                                    <button onclick='openModal("edit", <?= json_encode($c, 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($c['status'] == 1): ?>
                                        <a href="?toggle_status=0&id=<?= $c['id'] ?>&<?= http_build_query(array_diff_key($_GET, ['toggle_status'=>'', 'id'=>''])) ?>" onclick="return confirm('<?= $texts['ar']['confirm_disable'] ?>')" class="w-8 h-8 bg-emerald-50 text-emerald-600 rounded-xl flex items-center justify-center hover:bg-rose-500 hover:text-white transition shadow-sm text-xs" title="تعطيل"><i class="fas fa-toggle-on text-base"></i></a>
                                    <?php else: ?>
                                        <a href="?toggle_status=1&id=<?= $c['id'] ?>&<?= http_build_query(array_diff_key($_GET, ['toggle_status'=>'', 'id'=>''])) ?>" onclick="return confirm('<?= $texts['ar']['confirm_enable'] ?>')" class="w-8 h-8 bg-slate-100 text-slate-400 rounded-xl flex items-center justify-center hover:bg-emerald-500 hover:text-white transition shadow-sm text-xs" title="تفعيل"><i class="fas fa-toggle-off text-base"></i></a>
                                    <?php endif; ?>
                                    <a href="?delete=<?= $c['id'] ?>" 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>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if(empty($customers)): ?>
                            <tr><td colspan="<?php if($can_manage_all): ?>9<?php else: ?>8<?php endif; ?>" class="p-20 text-center text-slate-300 italic font-black text-lg">
                                <i class="fas fa-search text-4xl mb-4 block opacity-30"></i>
                                <?= $texts['ar']['no_results'] ?>
                            </td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <div class="mobile-cards flex-col gap-3 p-4">
                <?php foreach($customers as $c): ?>
                <div class="mobile-card bg-white border border-slate-100 rounded-2xl p-4 shadow-sm <?php if($c['status'] == 0): ?>card-inactive<?php endif; ?>">
                    <div class="flex justify-between items-start mb-3">
                        <div>
                            <div class="flex items-center gap-2 flex-wrap">
                                <span class="font-black text-slate-800 italic"><?= htmlspecialchars($c['name']) ?></span>
                                <?php if($c['is_exempt']): ?><span class="bg-amber-100 text-amber-700 px-2 py-0.5 rounded text-[8px] font-black">معفى 🎁</span><?php endif; ?>
                                <?php if($c['status'] == 0): ?><span class="bg-rose-100 text-rose-600 px-2 py-0.5 rounded text-[8px] font-black">معطل</span><?php endif; ?>
                            </div>
                            <div class="flex gap-2 mt-1 text-[10px] text-slate-400">
                                <span class="cursor-pointer hover:text-blue-500" onclick="copyToClipboard('<?php htmlspecialchars(addslashes($c['sub_no'])) ?>', this)">#: <?php if($c['sub_no']): ?><?= htmlspecialchars($c['sub_no']) ?><?php else: ?>---<?php endif; ?></span>
                                <?php if($c['box_no']): ?><span>علبة: <?= htmlspecialchars($c['box_no']) ?></span><?php endif; ?>
                                <?php if($c['phone']): ?><a href="tel:<?= $c['phone'] ?>" class="text-blue-400"><?= $c['phone'] ?></a><?php endif; ?>
                            </div>
                        </div>
                        <span class="bg-slate-900 text-white px-3 py-1 rounded-lg font-black text-xs italic shadow-md"><?= floatval($c['ampere_qty']) ?>A</span>
                    </div>
                    <?php if($c['notes']): ?>
                        <p class="text-[11px] text-slate-500 mb-3 truncate"><?= htmlspecialchars($c['notes']) ?></p>
                    <?php endif; ?>
                    <div class="flex justify-between items-center border-t border-slate-50 pt-3">
                        <div class="flex gap-3 text-[11px]">
                            <span class="px-2 py-0.5 rounded-full font-black uppercase <?php if($c['system_type'] == 'meter'): ?>bg-blue-100 text-blue-700<?php else: ?>bg-orange-100 text-orange-700<?php endif; ?>"><?php if($c['system_type'] == 'meter'): ?>عداد<?php else: ?>أمبير<?php endif; ?></span>
                            <span class="font-black <?php if($c['old_balance'] > 0): ?>text-rose-600<?php else: ?>text-emerald-600<?php endif; ?>$"><?= number_format(abs($c['old_balance']), 2) ?></span>
                            <?php if($c['custom_amp_price'] > 0): ?><span class="text-orange-500 font-bold">$<?= number_format($c['custom_amp_price'], 2) ?>/A</span><?php endif; ?>
                        </div>
                        <div class="flex gap-1">
                            <a href="customer_statement.php?id=<?= $c['id'] ?>" class="w-8 h-8 bg-indigo-50 text-indigo-600 rounded-xl flex items-center justify-center text-xs"><i class="fas fa-file-invoice"></i></a>
                            <button onclick='openModal("edit", <?= json_encode($c, JSON_UNESCAPED_UNICODE) ?>)' class="w-8 h-8 bg-blue-50 text-blue-500 rounded-xl flex items-center justify-center text-xs"><i class="fas fa-edit"></i></button>
                            <?php if($c['status'] == 1): ?>
                                <a href="?toggle_status=0&id=<?= $c['id'] ?>&<?= http_build_query(array_diff_key($_GET, ['toggle_status'=>'', 'id'=>''])) ?>" class="w-8 h-8 bg-emerald-50 text-emerald-600 rounded-xl flex items-center justify-center text-xs"><i class="fas fa-toggle-on"></i></a>
                            <?php else: ?>
                                <a href="?toggle_status=1&id=<?= $c['id'] ?>&<?= http_build_query(array_diff_key($_GET, ['toggle_status'=>'', 'id'=>''])) ?>" class="w-8 h-8 bg-slate-100 text-slate-400 rounded-xl flex items-center justify-center text-xs"><i class="fas fa-toggle-off"></i></a>
                            <?php endif; ?>
                            <a href="?delete=<?= $c['id'] ?>" 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 text-xs"><i class="fas fa-trash-alt"></i></a>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
                <?php if(empty($customers)): ?>
                    <div class="p-16 text-center text-slate-300 italic font-black text-lg">
                        <i class="fas fa-search text-4xl mb-4 block opacity-30"></i>
                        <?= $texts['ar']['no_results'] ?>
                    </div>
                <?php endif; ?>
            </div>

            <?php if ($total_pages > 1): ?>
            <div class="p-6 bg-slate-50 border-t border-slate-100 flex flex-wrap justify-center items-center gap-2">
                <?php if ($page > 1): ?>
                    <a href="<?= buildPageUrl($page - 1, $_GET) ?>" 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 text-sm">
                        <i class="fas fa-chevron-right ml-1"></i>السابق
                    </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 font-black">...</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 text-sm"><?= $i ?></span>
                    <?php else: ?>
                        <a href="<?= buildPageUrl($i, $_GET) ?>" 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 text-sm"><?= $i ?></a>
                    <?php endif; ?>
                <?php endfor;
                if($end < $total_pages) echo '<span class="px-2 text-slate-300 font-black">...</span>'; ?>

                <?php if ($page < $total_pages): ?>
                    <a href="<?= buildPageUrl($page + 1, $_GET) ?>" 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 text-sm">
                        التالي<i class="fas fa-chevron-left mr-1"></i>
                    </a>
                <?php endif; ?>
            </div>
            <?php endif; ?>
        </div>
        
        <div class="mt-4 text-center text-[10px] font-black text-slate-400 uppercase italic">
            <?= $texts['ar']['showing'] ?> <?= count($customers) ?> <?= $texts['ar']['of'] ?> <?= number_format($total_records) ?> <?= $texts['ar']['customer'] ?>
        </div>
    </div>

    <div id="custModal" class="fixed inset-0 bg-slate-900/60 hidden items-center justify-center z-50 p-4 backdrop-blur-sm overflow-y-auto italic font-bold">
        <div class="bg-white rounded-[3rem] w-full max-w-3xl overflow-hidden shadow-2xl my-8 border-t-8 border-blue-600" style="animation: modalIn 0.3s ease-out">
            <div class="p-8 bg-white border-b border-slate-100 flex justify-between items-center shrink-0">
                <h3 id="modalTitle" class="text-xl font-black italic"></h3>
                <button onclick="closeModal()" class="w-10 h-10 bg-slate-100 rounded-xl hover:bg-rose-500 hover:text-white transition-all text-xl flex items-center justify-center">&times;</button>
            </div>

            <form method="POST">
                <div class="p-8 space-y-5 modal-body">
                    <input type="hidden" name="action" id="formAction">
                    <input type="hidden" name="cust_id" id="custId">

                    <div class="p-5 bg-blue-50/50 rounded-[2rem] border border-blue-100">
                        <p class="text-[10px] font-black text-blue-600 uppercase tracking-widest mb-4 text-center"><i class="fas fa-user ml-1"></i>البيانات الأساسية</p>
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 font-bold">
                            <div>
                                <label class="block text-xs font-black text-slate-500 mb-1.5">اسم المشترك *</label>
                                <input type="text" name="name" id="custName" required class="w-full p-3.5 bg-white rounded-xl border-none outline-none focus:ring-2 focus:ring-blue-600 shadow-sm">
                            </div>
                            <div>
                                <label class="block text-xs font-black text-slate-500 mb-1.5">رقم الاشتراك</label>
                                <input type="text" name="sub_no" id="custSubNo" class="w-full p-3.5 bg-white rounded-xl border-none outline-none shadow-sm">
                            </div>
                            <div>
                                <label class="block text-xs font-black text-blue-600 mb-1.5">رقم العلبة</label>
                                <input type="text" name="box_no" id="custBoxNo" placeholder="مثلاً: A1" class="w-full p-3.5 bg-white rounded-xl border-none font-black text-blue-700 outline-none shadow-sm">
                            </div>
                        </div>
                    </div>

                    <div class="p-5 bg-slate-50 rounded-[2rem] border border-slate-100">
                        <p class="text-[10px] font-black text-slate-500 uppercase tracking-widest mb-4 text-center"><i class="fas fa-map-marker-alt ml-1"></i>التواصل والموقع</p>
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div>
                                <label class="block text-xs font-black text-slate-500 mb-1.5">رقم الهاتف</label>
                                <input type="text" name="phone" id="custPhone" class="w-full p-3.5 bg-white rounded-xl border-none outline-none shadow-sm">
                            </div>
                            <div>
                                <label class="block text-xs font-black text-slate-500 mb-1.5">المنطقة</label>
                                <input type="text" name="area" id="custArea" class="w-full p-3.5 bg-white rounded-xl border-none outline-none shadow-sm">
                            </div>
                            <div>
                                <label class="block text-xs font-black text-slate-500 mb-1.5">العنوان التفصيلي</label>
                                <input type="text" name="address" id="custAddress" placeholder="شارع، مبنى، طابق..." class="w-full p-3.5 bg-white rounded-xl border-none outline-none shadow-sm">
                            </div>
                        </div>
                    </div>

                    <div class="p-5 bg-indigo-50/50 rounded-[2rem] border border-indigo-100">
                        <p class="text-[10px] font-black text-indigo-600 uppercase tracking-widest mb-4 text-center"><i class="fas fa-bolt ml-1"></i>الأمبير والأسعار</p>
                        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                            <div>
                                <label class="block text-xs font-black text-indigo-600 mb-1.5">الأمبيرات (A) *</label>
                                <input type="number" step="0.1" name="ampere_qty" id="custAmpere" required class="w-full p-3.5 bg-white rounded-xl border-none font-black text-indigo-600 shadow-sm text-center">
                            </div>
                            <div>
                                <label class="block text-xs font-black text-orange-600 mb-1.5">سعر الأمبير ($)</label>
                                <input type="number" step="0.01" name="custom_amp_price" id="custAmpPrice" placeholder="0 = عام" class="w-full p-3.5 bg-white rounded-xl border-none font-black text-orange-600 shadow-sm text-center">
                            </div>
                            <div id="fixedFeeContainer">
                                <label class="block text-xs font-black text-violet-600 mb-1.5">رسم ثابت (L.L)</label>
                                <input type="number" name="monthly_fixed_fee" id="custFixedFee" class="w-full p-3.5 bg-white rounded-xl border-none font-black text-violet-600 shadow-sm text-center" placeholder="بالليرة">
                            </div>
                            <div>
                                <label class="block text-xs font-black text-slate-500 mb-1.5">النظام</label>
                                <select name="system_type" id="custSystem" onchange="toggleSystemFields()" class="w-full p-3.5 bg-white rounded-xl border-none font-bold outline-none cursor-pointer shadow-sm text-center">
                                    <option value="meter">عداد</option>
                                    <option value="ampere">أمبير</option>
                                </select>
                            </div>
                        </div>
                        <div id="meterFields" class="mt-4">
                            <label class="block text-xs font-black text-slate-500 mb-1.5">قراءة البداية</label>
                            <input type="number" step="0.01" name="initial_reading" id="custInitial" class="w-full p-3.5 bg-white rounded-xl border-none outline-none shadow-sm">
                        </div>
                    </div>

                    <div class="p-5 bg-slate-50 rounded-[2rem] border border-slate-100">
                        <p class="text-[10px] font-black text-slate-500 uppercase tracking-widest mb-4 text-center"><i class="fas fa-wallet ml-1"></i>الأرصدة والتأمين</p>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-xs font-black text-rose-500 mb-1.5 text-center">رصيد سابق ($)</label>
                                <input type="number" step="0.01" name="old_balance" id="custBalance" class="w-full p-3.5 bg-white rounded-xl border-none font-black text-rose-500 outline-none shadow-sm text-center">
                            </div>
                            <div>
                                <label class="block text-xs font-black text-emerald-600 mb-1.5 text-center">تأمين ($)</label>
                                <input type="number" step="0.01" name="insurance" id="custInsurance" class="w-full p-3.5 bg-white rounded-xl border-none font-black text-emerald-600 outline-none shadow-sm text-center">
                            </div>
                        </div>
                    </div>

                    <div class="p-5 bg-slate-50 rounded-[2rem] border border-slate-100">
                        <p class="text-[10px] font-black text-slate-500 uppercase tracking-widest mb-4 text-center"><i class="fas fa-cog ml-1"></i>إعدادات إضافية</p>
                        
                        <div class="flex items-center justify-between p-4 bg-white rounded-xl border border-slate-100 mb-4">
                             <div>
                                <label class="block text-xs font-black text-amber-600">حالة الإعفاء (مجاني)</label>
                                <p class="text-[10px] text-slate-400 font-bold">تفعيل المجاني للمشترك</p>
                             </div>
                             <div class="relative inline-block w-12 mr-2 align-middle select-none">
                                <input type="checkbox" name="is_exempt" id="custExempt" class="toggle-checkbox absolute block w-6 h-6 rounded-full bg-white border-4 appearance-none cursor-pointer transition-all duration-300 right-6 outline-none"/>
                                <label for="custExempt" class="toggle-label block overflow-hidden h-6 rounded-full bg-gray-300 cursor-pointer transition-colors duration-300"></label>
                             </div>
                        </div>

                        <?php if($can_manage_all): ?>
                        <div class="mb-4">
                            <label class="block text-xs font-black text-blue-600 mb-1.5 text-center">تعيين الموظف المسؤول</label>
                            <select name="created_by" id="custCreatedBy" class="w-full p-3.5 bg-white rounded-xl border-none font-black text-blue-700 shadow-sm outline-none cursor-pointer">
                                <?php foreach($all_users as $u): ?>
                                    <option value="<?= $u['id'] ?>" <?php if($u['id'] == $logged_user_id): ?>selected<?php endif; ?>>
                                        <?= htmlspecialchars($u['name']) ?> (<?php if($u['id'] == $logged_user_id): ?>أنت<?php else: ?>موظف<?php endif; ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <?php endif; ?>

                        <div class="mb-4">
                            <label class="block text-xs font-black text-slate-500 mb-1.5">الملاحظات</label>
                            <textarea name="notes" id="custNotes" rows="2" class="w-full p-3.5 bg-white rounded-xl border-none font-bold outline-none focus:ring-2 focus:ring-blue-600 shadow-sm"></textarea>
                        </div>

                        <div>
                            <label class="block text-xs font-black text-slate-500 mb-1.5 text-center">حالة الاشتراك</label>
                            <select name="status" id="custStatus" class="w-full p-3.5 bg-white rounded-xl border-none font-bold cursor-pointer text-center">
                                <option value="1">نشط / يعمل ✅</option>
                                <option value="0">ملغى / معطل ❌</option>
                            </select>
                        </div>
                    </div>
                </div>

                <div class="p-8 border-t border-slate-100 flex gap-4 italic uppercase bg-white">
                    <button type="submit" class="flex-grow p-5 bg-blue-600 text-white rounded-2xl font-black shadow-xl hover:bg-black transition transform active:scale-95 italic text-lg">
                        <i class="fas fa-save ml-2"></i><?= $texts['ar']['save'] ?>
                    </button>
                    <button type="button" onclick="closeModal()" class="px-8 p-5 bg-slate-100 text-slate-500 rounded-2xl font-black hover:bg-slate-200 transition italic flex items-center justify-center gap-2">
                        <i class="fas fa-times"></i> <?= $texts['ar']['cancel'] ?>
                    </button>
                </div>
            </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">
        <i class="fas fa-chevron-up"></i>
    </button>

    <div id="copyToast" class="fixed bottom-6 right-6 bg-slate-900 text-white px-5 py-3 rounded-2xl font-bold shadow-2xl hidden z-50 text-sm italic transition-all">
        <i class="fas fa-check-circle text-emerald-400 ml-2"></i>تم النسخ!
    </div>

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

        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('liveSearchInput').value = '';
                document.getElementById('filterForm').submit(); 
            }
        });

        function copyToClipboard(text, el) {
            if (!text || text === '---') return;
            navigator.clipboard.writeText(text).then(function() {
                el.classList.add('copy-flash');
                setTimeout(function() { el.classList.remove('copy-flash'); }, 600);
                var toast = document.getElementById('copyToast');
                toast.classList.remove('hidden');
                toast.classList.add('flex');
                setTimeout(function() { toast.classList.add('hidden'); toast.classList.remove('flex'); }, 1500);
            });
        }

        function toggleSystemFields() {
            var system = document.getElementById('custSystem').value;
            document.getElementById('meterFields').style.display = (system === 'meter') ? 'block' : 'none';
            var fixedFeeCont = document.getElementById('fixedFeeContainer');
            if (system === 'meter') { fixedFeeCont.style.display = 'block'; } 
            else { fixedFeeCont.style.display = 'none'; document.getElementById('custFixedFee').value = 0; }
        }

        function openModal(mode, data) {
            var modal = document.getElementById('custModal');
            document.getElementById('formAction').value = mode;
            
            var fields = ['custId','custName','custSubNo','custBoxNo','custPhone','custArea','custAddress',
                           'custAmpere','custAmpPrice','custFixedFee','custBalance','custInsurance','custInitial','custNotes'];
            fields.forEach(function(f) { document.getElementById(f).value = ''; });
            document.getElementById('custStatus').value = '1';
            document.getElementById('custSystem').value = 'meter';
            document.getElementById('custExempt').checked = false;

            if (mode === 'add') {
                document.getElementById('modalTitle').innerText = 'إضافة مشترك جديد';
                document.getElementById('custAmpere').value = '5';
                document.getElementById('custFixedFee').value = '500000';
                var createdByEl = document.getElementById('custCreatedBy');
                if(createdByEl) createdByEl.value = '<?= $logged_user_id ?>';
            } else {
                document.getElementById('modalTitle').innerText = 'تعديل بيانات المشترك';
                document.getElementById('custId').value = data.id;
                document.getElementById('custName').value = data.name;
                document.getElementById('custSubNo').value = data.sub_no;
                document.getElementById('custBoxNo').value = data.box_no;
                document.getElementById('custPhone').value = data.phone;
                document.getElementById('custArea').value = data.area;
                document.getElementById('custAddress').value = data.address || '';
                document.getElementById('custSystem').value = data.system_type;
                document.getElementById('custAmpere').value = data.ampere_qty;
                document.getElementById('custAmpPrice').value = data.custom_amp_price;
                document.getElementById('custFixedFee').value = data.monthly_fixed_fee;
                document.getElementById('custBalance').value = data.old_balance;
                document.getElementById('custInsurance').value = data.insurance;
                document.getElementById('custInitial').value = data.initial_reading;
                document.getElementById('custNotes').value = data.notes;
                document.getElementById('custStatus').value = data.status;
                document.getElementById('custExempt').checked = (data.is_exempt == 1);
                var createdByEl = document.getElementById('custCreatedBy');
                if(createdByEl) createdByEl.value = data.created_by;
            }
            
            toggleSystemFields();
            modal.classList.replace('hidden', 'flex');
            document.body.style.overflow = 'hidden';
        }

        function closeModal() { 
            document.getElementById('custModal').classList.replace('flex', 'hidden');
            document.body.style.overflow = '';
        }

        document.getElementById('custModal').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'); }
        });

        window.onload = function() {
            var liveInput = document.getElementById('liveSearchInput');
            var nameInput = document.getElementById('nameSearchInput');
            if(liveInput.value) { liveInput.focus(); liveInput.select(); } 
            else if (nameInput.value) { nameInput.focus(); nameInput.select(); }
        };
    </script>
</body>
</html>