<?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';

$customer_id = $_GET['id'] ?? null;
$customer = null;
$history = [];

if ($customer_id) {
    // جلب بيانات المشترك
    $stmt = $pdo->prepare("SELECT * FROM customers WHERE id = ?");
    $stmt->execute([$customer_id]);
    $customer = $stmt->fetch();

    if ($customer) {
        // جلب الفواتير (كعمليات مدينة +)
        $bills = $pdo->prepare("SELECT 'bill' as type, bill_number as ref, amount_usd as amount, created_at as date, month, year 
                                FROM bills WHERE customer_id = ?");
        $bills->execute([$customer_id]);
        $all_bills = $bills->fetchAll();

        // جلب المدفوعات (كعمليات دائنة -)
        $payments = $pdo->prepare("SELECT 'payment' as type, p.id as ref, p.amount, p.created_at as date, p.currency, p.notes
                                   FROM payments p 
                                   JOIN bills b ON p.bill_id = b.id 
                                   WHERE b.customer_id = ?");
        $payments->execute([$customer_id]);
        $all_payments = $payments->fetchAll();

        // دمج العمليات وترتيبها حسب التاريخ
        $history = array_merge($all_bills, $all_payments);
        usort($history, function($a, $b) {
            return strtotime($a['date']) - strtotime($b['date']);
        });
    }
}

// جلب قائمة المشتركين للبحث
$all_customers = $pdo->query("SELECT id, name, sub_no FROM customers ORDER BY name ASC")->fetchAll();
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <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; }
        @media print {
            .no-print { display: none !important; }
            body { background: white; }
            .print-box { border: 1px solid #000 !important; border-radius: 0 !important; box-shadow: none !important; }
        }
    </style>
</head>
<body class="pb-12 text-slate-800">

    <div class="container mx-auto px-4 py-8 max-w-5xl">
        
        <!-- Header & Selection (Hidden on Print) -->
        <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 no-print">
            <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"></i>
                </div>
                <div>
                    <h1 class="text-2xl font-black text-slate-800">كشف حساب مشترك</h1>
                    <p class="text-sm text-slate-400 font-bold uppercase italic">عرض السجل المالي التاريخي</p>
                </div>
            </div>
            <div class="flex gap-3">
                <button onclick="window.print()" class="bg-slate-100 text-slate-600 px-6 py-3 rounded-2xl font-bold hover:bg-slate-200 transition">
                    <i class="fas fa-print ml-2"></i> طباعة
                </button>
                <a href="dashboard.php" class="bg-blue-600 text-white px-8 py-3 rounded-2xl font-black hover:bg-black transition shadow-lg">الرئيسية</a>
            </div>
        </div>

        <!-- Selection Form (No Print) -->
        <div class="bg-white p-6 rounded-[2rem] shadow-sm mb-8 border border-slate-100 no-print">
            <form method="GET" class="flex flex-col md:flex-row gap-4 items-end">
                <div class="flex-grow">
                    <label class="block text-[10px] font-black text-slate-400 mb-2 uppercase tracking-widest">اختر المشترك لعرض كشف الحساب</label>
                    <select name="id" required class="w-full p-4 bg-slate-50 rounded-2xl border-none font-bold outline-none focus:ring-2 focus:ring-blue-600">
                        <option value="">--- ابحث عن المشترك ---</option>
                        <?php foreach($all_customers as $ac): ?>
                            <option value="<?= $ac['id'] ?>" <?= $customer_id == $ac['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($ac['name']) ?> (<?= $ac['sub_no'] ?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <button type="submit" class="bg-slate-900 text-white px-10 py-4 rounded-2xl font-black shadow-lg hover:bg-blue-600 transition">عرض الكشف</button>
            </form>
        </div>

        <?php if($customer): ?>
            <!-- Statement View -->
            <div class="bg-white p-10 rounded-[3rem] shadow-xl border border-slate-100 print-box">
                <!-- Statement Header (Visible on Print) -->
                <div class="flex justify-between items-start border-b-2 border-slate-100 pb-8 mb-8">
                    <div>
                        <h2 class="text-3xl font-black text-slate-800 italic">أسامة إلكتريك</h2>
                        <p class="text-sm font-bold text-slate-400">لخدمات الكهرباء وإدارة المولدات</p>
                    </div>
                    <div class="text-left font-bold text-sm">
                        <p>تاريخ الكشف: <?= date('Y-m-d') ?></p>
                        <p>رقم المشترك: #<?= $customer['sub_no'] ?></p>
                    </div>
                </div>

                <!-- Customer Summary Box -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-8 mb-10">
                    <div>
                        <p class="text-[10px] font-black text-slate-400 uppercase mb-1">بيانات المشترك</p>
                        <h3 class="text-2xl font-black text-blue-600"><?= htmlspecialchars($customer['name']) ?></h3>
                        <p class="text-sm font-bold text-slate-500"><?= $customer['phone'] ?> | <?= $customer['area'] ?></p>
                    </div>
                    <div class="bg-slate-50 p-6 rounded-[2rem] flex justify-between items-center">
                        <div>
                            <p class="text-[10px] font-black text-slate-400 uppercase">الرصيد الحالي المستحق</p>
                            <h3 class="text-3xl font-black text-rose-600 italic">$<?= number_format($customer['old_balance'], 2) ?></h3>
                        </div>
                        <i class="fas fa-exclamation-triangle text-rose-100 text-4xl"></i>
                    </div>
                </div>

                <!-- Ledger Table -->
                <div class="overflow-x-auto">
                    <table class="w-full text-right">
                        <thead class="bg-slate-800 text-white text-[10px] font-black uppercase tracking-widest">
                            <tr>
                                <th class="p-4 rounded-tr-2xl">التاريخ</th>
                                <th class="p-4">البيان (نوع العملية)</th>
                                <th class="p-4">المرجع</th>
                                <th class="p-4 text-center">مدين (+)</th>
                                <th class="p-4 text-center">دائن (-)</th>
                                <th class="p-4 text-center rounded-tl-2xl">العملة</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-100">
                            <!-- الرصيد الافتتاحي -->
                            <tr class="bg-blue-50/50">
                                <td class="p-4 text-xs font-bold text-slate-400 italic">البداية</td>
                                <td class="p-4 font-black text-blue-700">رصيد افتتاحي / تأمينات</td>
                                <td class="p-4 text-xs font-bold">---</td>
                                <td class="p-4 text-center font-black text-slate-800">$<?= number_format($customer['insurance'], 2) ?></td>
                                <td class="p-4 text-center">---</td>
                                <td class="p-4 text-center text-[10px] font-black uppercase">USD</td>
                            </tr>
                            
                            <?php foreach($history as $item): ?>
                            <tr class="hover:bg-slate-50 transition">
                                <td class="p-4 text-xs font-bold text-slate-400 italic"><?= date('Y-m-d', strtotime($item['date'])) ?></td>
                                <td class="p-4">
                                    <div class="font-black text-slate-800">
                                        <?= $item['type'] == 'bill' ? "فاتورة شهر " . $item['month'] . "/" . $item['year'] : "دفعة نقدية " ?>
                                    </div>
                                    <div class="text-[9px] text-slate-400 font-bold"><?= $item['notes'] ?? '' ?></div>
                                </td>
                                <td class="p-4 font-mono text-xs font-bold text-blue-500 italic"><?= $item['ref'] ?></td>
                                <td class="p-4 text-center font-black text-rose-500">
                                    <?= $item['type'] == 'bill' ? '$' . number_format($item['amount'], 2) : '---' ?>
                                </td>
                                <td class="p-4 text-center font-black text-emerald-600">
                                    <?= $item['type'] == 'payment' ? ($item['currency'] == 'USD' ? '$' : '') . number_format($item['amount'], 2) . ($item['currency'] == 'LBP' ? ' ل.ل' : '') : '---' ?>
                                </td>
                                <td class="p-4 text-center">
                                    <span class="px-2 py-1 bg-slate-100 rounded text-[9px] font-black uppercase"><?= $item['currency'] ?? 'USD' ?></span>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Footer Signatures (Print Only) -->
                <div class="hidden print:flex justify-between items-center mt-20 pt-10 border-t border-dashed border-slate-300">
                    <div class="text-center w-48">
                        <p class="font-black text-xs uppercase mb-10">توقيع المشترك</p>
                        <div class="border-b border-slate-400"></div>
                    </div>
                    <div class="text-center w-48">
                        <p class="font-black text-xs uppercase mb-10">ختم المؤسسة</p>
                        <div class="border-b border-slate-400"></div>
                    </div>
                </div>
            </div>
        <?php elseif($customer_id): ?>
            <div class="bg-rose-500 text-white p-8 rounded-[2rem] text-center font-black shadow-lg">لم يتم العثور على هذا المشترك</div>
        <?php endif; ?>

        <div class="text-center text-slate-400 text-[10px] font-black uppercase tracking-[0.4em] mt-12 mb-8 no-print italic">
            Osama Electric Management System v3.2
        </div>

    </div>

</body>
</html>