<?php
session_start();

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

require_once 'db.php';

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

// جلب سعر الأمبير العام الحالي (لأغراض العرض والحساب التقديري)
$current_month = date('n');
$current_year = date('Y');
$price_stmt = $pdo->prepare("SELECT price_amp FROM monthly_pricing WHERE month = ? AND year = ?");
$price_stmt->execute([$current_month, $current_year]);
$global_amp_price = $price_stmt->fetchColumn() ?: 0;

// 2. جلب إحصائيات سريعة لنظام الأمبير
$stats = $pdo->query("SELECT 
    COUNT(*) as total_subs,
    SUM(ampere_qty) as total_amps,
    SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) as active_subs
    FROM customers WHERE system_type = 'ampere'")->fetch();

// 3. جلب قائمة مشتركين الأمبير
$query = "SELECT * FROM customers WHERE system_type = 'ampere' ORDER BY ampere_qty DESC, id DESC";
$customers = $pdo->query($query)->fetchAll();

?>

<!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: #f8fafc; }
        .stat-card { transition: all 0.3s ease; }
        .stat-card:hover { transform: translateY(-5px); }
    </style>
</head>
<body class="pb-12 text-slate-800">

    <div class="container mx-auto px-4 py-8">
        <!-- Header -->
        <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-orange-500 text-white rounded-2xl flex items-center justify-center text-3xl shadow-xl shadow-orange-100">
                    <i class="fas fa-plug"></i>
                </div>
                <div>
                    <h1 class="text-2xl font-black text-slate-800">إدارة اشتراكات الأمبير</h1>
                    <p class="text-sm text-slate-400 font-bold uppercase tracking-widest">مراقبة الأحمال والدخل المتوقع للنظام المقطوع</p>
                </div>
            </div>
            <div class="flex gap-3">
                <a href="customers.php" class="bg-slate-800 text-white px-8 py-3 rounded-2xl font-black hover:bg-black transition shadow-lg">
                    <i class="fas fa-user-plus ml-2"></i> إضافة/تعديل مشترك
                </a>
                <a href="dashboard.php" class="bg-slate-100 text-slate-600 px-8 py-3 rounded-2xl font-bold hover:bg-slate-200 transition">الرئيسية</a>
            </div>
        </div>

        <!-- Stats Grid -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
            <div class="stat-card bg-white p-6 rounded-[2rem] border border-slate-100 shadow-sm">
                <p class="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-2">إجمالي المشتركين (أمبير)</p>
                <h3 class="text-3xl font-black"><?= $stats['total_subs'] ?></h3>
                <p class="text-[10px] text-emerald-500 font-bold mt-2"><?= $stats['active_subs'] ?> مشترك نشط حالياً</p>
            </div>
            <div class="stat-card bg-white p-6 rounded-[2rem] border border-slate-100 shadow-sm">
                <p class="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-2">إجمالي الأحمال المباعة</p>
                <h3 class="text-3xl font-black text-orange-500"><?= number_format($stats['total_amps']) ?> <small class="text-sm">Ampere</small></h3>
                <p class="text-[10px] text-slate-400 font-bold mt-2">مجموع سعة المولد المستهلكة</p>
            </div>
            <div class="stat-card bg-slate-900 p-6 rounded-[2rem] text-white shadow-xl">
                <p class="text-slate-500 text-[10px] font-black uppercase tracking-widest mb-2">السعر العام المعتمد (<?= $current_month ?>/<?= $current_year ?>)</p>
                <h3 class="text-3xl font-black text-emerald-400">$<?= number_format($global_amp_price, 2) ?></h3>
                <p class="text-[10px] text-slate-400 font-bold mt-2 italic">يستخدم في حال عدم وجود سعر خاص</p>
            </div>
        </div>

        <!-- Search Bar -->
        <div class="bg-white p-6 rounded-[2rem] shadow-sm mb-8 border border-slate-100">
            <div class="relative">
                <i class="fas fa-search absolute right-5 top-5 text-slate-300"></i>
                <input type="text" id="ampSearchInput" placeholder="ابحث عن مشترك، رقم هاتف، أو سعة (مثلاً: 5A)..." 
                       class="w-full p-4 pr-12 bg-slate-50 rounded-2xl border-none focus:ring-2 focus:ring-orange-500 outline-none font-bold transition">
            </div>
        </div>

        <!-- Table -->
        <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="ampTable">
                    <thead class="bg-slate-50 text-slate-400 text-[10px] font-black uppercase tracking-[0.2em] border-b">
                        <tr>
                            <th class="p-6">المشترك</th>
                            <th class="p-6 text-center">سعة الاشتراك</th>
                            <th class="p-6 text-center">السعر المطبق</th>
                            <th class="p-6 text-center">الرسم الثابت</th>
                            <th class="p-6 text-center">التكلفة الشهرية</th>
                            <th class="p-6 text-center">الحالة</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-50">
                        <?php foreach($customers as $c): 
                            // حساب السعر المطبق
                            $price_to_show = ($c['custom_amp_price'] > 0) ? $c['custom_amp_price'] : $global_amp_price;
                            $monthly_cost = ($c['ampere_qty'] * $price_to_show) + $c['monthly_fixed_fee'];
                        ?>
                        <tr class="hover:bg-orange-50/20 transition group">
                            <td class="p-6">
                                <div class="font-black text-slate-800 italic"><?= htmlspecialchars($c['name']) ?></div>
                                <div class="text-[9px] text-slate-400 font-bold">Sub: #<?= $c['sub_no'] ?> | <?= $c['phone'] ?></div>
                            </td>
                            <td class="p-6 text-center font-black text-lg text-slate-700">
                                <?= $c['ampere_qty'] ?> <small class="text-[10px] text-slate-400">A</small>
                            </td>
                            <td class="p-6 text-center">
                                <?php if($c['custom_amp_price'] > 0): ?>
                                    <span class="bg-orange-100 text-orange-700 px-3 py-1 rounded-lg text-xs font-black" title="سعر خاص للزبون">
                                        $<?= number_format($c['custom_amp_price'], 2) ?>
                                    </span>
                                <?php else: ?>
                                    <span class="text-slate-400 text-xs font-bold">$<?= number_format($global_amp_price, 2) ?> <small>(عام)</small></span>
                                <?php endif; ?>
                            </td>
                            <td class="p-6 text-center font-bold text-indigo-500">
                                $<?= number_format($c['monthly_fixed_fee'], 2) ?>
                            </td>
                            <td class="p-6 text-center">
                                <div class="bg-slate-50 px-4 py-2 rounded-2xl inline-block border border-slate-100">
                                    <span class="font-black text-slate-800 text-md">$<?= number_format($monthly_cost, 2) ?></span>
                                </div>
                            </td>
                            <td class="p-6 text-center">
                                <span class="w-3 h-3 rounded-full inline-block <?= $c['status'] == 1 ? 'bg-emerald-500 shadow-[0_0_8px_rgba(16,185,129,0.4)]' : 'bg-slate-300' ?>"></span>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if(empty($customers)): ?>
                            <tr><td colspan="6" class="p-20 text-center text-slate-300 italic font-black text-lg">لا يوجد مشتركين بنظام الأمبير حالياً</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="mt-8 text-center text-slate-400 text-[10px] font-black uppercase tracking-[0.4em]">
            Osama Electric - Load Management System v2.5
        </div>
    </div>

    <script>
        // البحث الفوري في الجدول
        document.getElementById('ampSearchInput').addEventListener('input', function() {
            const searchValue = this.value.toLowerCase();
            const rows = document.querySelectorAll('#ampTable tbody tr');
            
            rows.forEach(row => {
                const text = row.innerText.toLowerCase();
                row.style.display = text.includes(searchValue) ? '' : 'none';
            });
        });
    </script>
</body>
</html>