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

// --- صيانة تلقائية وتحديث الجداول ---
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `payments` (
        `id` INT AUTO_INCREMENT PRIMARY KEY,
        `bill_id` INT NOT NULL,
        `amount` DECIMAL(12,2) NOT NULL,
        `currency` ENUM('USD', 'LBP') DEFAULT 'USD',
        `notes` TEXT NULL,
        `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (`bill_id`) REFERENCES `bills`(`id`) ON DELETE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;");

    $pdo->exec("ALTER TABLE `payments` ADD COLUMN IF NOT EXISTS `notes` TEXT NULL AFTER `currency` ");
} catch (PDOException $e) { }

// جلب سعر الصرف الحالي من الإعدادات
try {
    $global_rate = $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'exchange_rate'")->fetchColumn() ?: 90000;
} catch (Exception $e) { $global_rate = 90000; }

$message = '';
$error = '';
$auto_print_id = null;

// 2. معالجة إضافة دفعة جديدة (دعم الدفع الجزئي)
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_payment'])) {
    try {
        $bill_id = $_POST['bill_id'];
        $paid_amount = (float)$_POST['amount'];
        $currency = $_POST['currency'];
        $notes = $_POST['notes'] ?? 'دفع نقدي';

        $pdo->beginTransaction();

        // أ. جلب بيانات الفاتورة الحالية وسعر صرفها
        $stmt_bill = $pdo->prepare("
            SELECT b.amount_usd, p.exchange_rate 
            FROM bills b 
            LEFT JOIN monthly_pricing p ON b.month = p.month AND b.year = p.year 
            WHERE b.id = ?
        ");
        $stmt_bill->execute([$bill_id]);
        $bill = $stmt_bill->fetch();

        if ($bill) {
            $current_due_usd = (float)$bill['amount_usd'];
            $bill_rate = (float)($bill['exchange_rate'] ?: $global_rate);
            
            // ب. تحويل المبلغ المدفوع إلى دولار إذا كان بالليرة للخصم من الرصيد
            $paid_in_usd = ($currency === 'LBP') ? ($paid_amount / $bill_rate) : $paid_amount;
            
            // ج. تسجيل الدفعة في جدول payments
            $stmt_ins = $pdo->prepare("INSERT INTO payments (bill_id, amount, currency, notes) VALUES (?, ?, ?, ?)");
            $stmt_ins->execute([$bill_id, $paid_amount, $currency, $notes]);
            $new_pay_id = $pdo->lastInsertId();

            // د. حساب الرصيد الجديد المتبقي
            $remaining_usd = $current_due_usd - $paid_in_usd;
            
            if ($remaining_usd <= 0.05) { // دفع كامل (تلافي الفروقات البسيطة)
                $update = $pdo->prepare("UPDATE bills SET amount_usd = 0, status = 'paid' WHERE id = ?");
                $update->execute([$bill_id]);
                $message = "تم تسديد الفاتورة بالكامل بنجاح.";
            } else {
                // دفع جزئي: تحديث المبلغ المتبقي فقط وإبقاء الحالة Unpaid
                $update = $pdo->prepare("UPDATE bills SET amount_usd = ? WHERE id = ?");
                $update->execute([$remaining_usd, $bill_id]);
                $message = "تم تسجيل الدفعة الجزئية. المتبقي على الفاتورة: $" . number_format($remaining_usd, 2);
            }

            $pdo->commit();
            $auto_print_id = $new_pay_id;
        } else {
            throw new Exception("الفاتورة غير موجودة.");
        }

    } catch (Exception $e) {
        $pdo->rollBack();
        $error = "فشل التسجيل: " . $e->getMessage();
    }
}

// 3. جلب البيانات
$today = date('Y-m-d');
$stats_usd = $pdo->query("SELECT SUM(amount) FROM payments WHERE currency = 'USD' AND DATE(created_at) = '$today'")->fetchColumn() ?: 0;
$stats_lbp = $pdo->query("SELECT SUM(amount) FROM payments WHERE currency = 'LBP' AND DATE(created_at) = '$today'")->fetchColumn() ?: 0;

$unpaid_bills = $pdo->query("
    SELECT b.id, b.bill_number, b.amount_usd, c.name, p.exchange_rate as bill_rate
    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.status = 'unpaid' 
    ORDER BY b.created_at DESC
")->fetchAll();

$payments = $pdo->query("
    SELECT p.*, b.bill_number, c.name as customer_name 
    FROM payments p 
    JOIN bills b ON p.bill_id = b.id 
    JOIN customers c ON b.customer_id = c.id 
    ORDER BY p.id DESC LIMIT 50
")->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; }
        .receipt-print { display: none; }
        @media print {
            body * { visibility: hidden; }
            .receipt-print, .receipt-print * { visibility: visible; }
            .receipt-print { display: block; position: absolute; left: 0; top: 0; width: 80mm; }
        }
    </style>
</head>
<body class="pb-12 text-slate-800">

    <div class="container mx-auto px-4 py-8 max-w-6xl no-print">
        <!-- 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-emerald-600 text-white rounded-2xl flex items-center justify-center text-3xl shadow-xl">
                    <i class="fas fa-cash-register"></i>
                </div>
                <div>
                    <h1 class="text-2xl font-black text-slate-800">إدارة المقبوضات والتحصيل</h1>
                    <p class="text-sm text-slate-400 font-bold uppercase italic">صندوق اليوم: <?= date('Y-m-d') ?></p>
                </div>
            </div>
            <div class="flex gap-3">
                <button onclick="document.getElementById('payModal').classList.replace('hidden', 'flex')" class="bg-emerald-600 hover:bg-black text-white px-8 py-3 rounded-2xl font-black transition shadow-lg flex items-center gap-2">
                    <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 transition">الرئيسية</a>
            </div>
        </div>

        <!-- Stats -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
            <div class="bg-white p-8 rounded-[2rem] border-r-8 border-emerald-500 shadow-sm flex items-center justify-between">
                <div><p class="text-xs font-black text-slate-400 uppercase mb-2">إجمالي الدولار (اليوم)</p><h3 class="text-4xl font-black text-emerald-600">$<?= number_format($stats_usd, 2) ?></h3></div>
                <div class="text-emerald-200 text-5xl"><i class="fas fa-dollar-sign"></i></div>
            </div>
            <div class="bg-white p-8 rounded-[2rem] border-r-8 border-slate-800 shadow-sm flex items-center justify-between">
                <div><p class="text-xs font-black text-slate-400 uppercase mb-2">إجمالي الليرة (اليوم)</p><h3 class="text-3xl font-black text-slate-800"><?= number_format($stats_lbp) ?> <small class="text-sm">ل.ل</small></h3></div>
                <div class="text-slate-100 text-5xl"><i class="fas fa-money-bill-wave"></i></div>
            </div>
        </div>

        <?php if($message): ?><div class="bg-emerald-500 text-white p-5 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-5 rounded-2xl mb-8 font-bold shadow-lg"><i class="fas fa-exclamation-triangle"></i> <?= $error ?></div><?php endif; ?>

        <!-- Table -->
        <div class="bg-white rounded-[2.5rem] shadow-sm border border-slate-100 overflow-hidden">
            <div class="p-6 border-b border-slate-50 bg-slate-50/50 flex justify-between items-center">
                <h3 class="font-black text-slate-700 uppercase tracking-widest text-sm italic">سجل العمليات الأخير</h3>
                <input type="text" id="paySearch" placeholder="بحث سريع..." class="p-2 px-4 bg-white rounded-xl border border-slate-200 font-bold text-xs outline-none focus:ring-2 focus:ring-emerald-500 w-64">
            </div>
            <div class="overflow-x-auto">
                <table class="w-full text-right" id="payTable">
                    <thead class="bg-slate-50 text-slate-400 text-[10px] font-black uppercase tracking-widest border-b">
                        <tr>
                            <th class="p-6">الوقت</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>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-50">
                        <?php foreach($payments as $p): ?>
                        <tr class="hover:bg-emerald-50/10 transition group font-bold">
                            <td class="p-6 text-xs text-slate-400 italic"><?= date('H:i', strtotime($p['created_at'])) ?></td>
                            <td class="p-6">
                                <div class="font-black text-slate-800"><?= htmlspecialchars($p['customer_name']) ?></div>
                                <div class="text-[9px] text-slate-400"><?= htmlspecialchars($p['notes']) ?></div>
                            </td>
                            <td class="p-6 text-center font-black <?= $p['currency'] == 'USD' ? 'text-emerald-600' : 'text-slate-700' ?>">
                                <?= $p['currency'] == 'USD' ? '$' . number_format($p['amount'], 2) : number_format($p['amount']) . ' ل.ل' ?>
                            </td>
                            <td class="p-6 text-center font-mono text-xs font-black text-blue-500 italic"><?= $p['bill_number'] ?></td>
                            <td class="p-6 text-center">
                                <button onclick="printReceipt(<?= $p['id'] ?>)" class="w-9 h-9 bg-slate-100 text-slate-400 rounded-xl hover:bg-emerald-600 hover:text-white transition shadow-sm">
                                    <i class="fas fa-print"></i>
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Modal القبض -->
    <div id="payModal" class="fixed inset-0 bg-slate-900/60 hidden items-center justify-center z-50 p-4 backdrop-blur-sm no-print">
        <div class="bg-white rounded-[3rem] w-full max-w-lg overflow-hidden shadow-2xl animate-in zoom-in duration-300">
            <div class="p-8 bg-emerald-600 text-white flex justify-between items-center italic font-black">
                <h3>تسجيل عملية قبض جديدة</h3>
                <button onclick="document.getElementById('payModal').classList.replace('flex', 'hidden')" class="text-2xl">&times;</button>
            </div>
            <form method="POST" class="p-10 space-y-6">
                <input type="hidden" name="add_payment" value="1">
                <div>
                    <label class="block text-[10px] font-black text-slate-400 mb-2 uppercase tracking-widest">اختر الفاتورة المستحقة</label>
                    <select name="bill_id" id="bill_select" onchange="autoFill()" required class="w-full p-4 bg-slate-50 rounded-2xl border-none font-bold outline-none focus:ring-2 focus:ring-emerald-500">
                        <option value="">--- اختر فاتورة المشترك ---</option>
                        <?php foreach($unpaid_bills as $ub): 
                            $rate_to_use = $ub['bill_rate'] ?: $global_rate;
                            $lbp_val = $ub['amount_usd'] * $rate_to_use;
                        ?>
                            <option value="<?= $ub['id'] ?>" data-usd="<?= $ub['amount_usd'] ?>" data-lbp="<?= $lbp_val ?>" data-rate="<?= $rate_to_use ?>">
                                <?= htmlspecialchars($ub['name']) ?> - $<?= number_format($ub['amount_usd'],2) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="grid grid-cols-2 gap-4">
                    <div class="p-4 bg-emerald-50 rounded-2xl border border-emerald-100">
                        <label class="block text-[10px] font-black text-emerald-600 mb-2 uppercase">المبلغ المقبوض</label>
                        <input type="number" step="0.01" name="amount" id="pay_amount" required class="w-full bg-white p-3 rounded-xl border-none font-black text-xl text-center outline-none">
                    </div>
                    <div>
                        <label class="block text-[10px] font-black text-slate-400 mb-2 uppercase">العملة</label>
                        <select name="currency" id="pay_currency" onchange="autoFill()" class="w-full p-4 bg-slate-50 rounded-2xl border-none font-black text-center cursor-pointer">
                            <option value="USD">USD ($)</option>
                            <option value="LBP">LBP (ل.ل)</option>
                        </select>
                    </div>
                </div>
                <div id="rateInfo" class="text-center text-[10px] font-bold text-slate-400 italic"></div>
                <div>
                    <label class="block text-[10px] font-black text-slate-400 mb-2 uppercase">ملاحظات</label>
                    <input type="text" name="notes" placeholder="دفعة جزئية، دفعة كاملة..." class="w-full p-4 bg-slate-50 rounded-2xl border-none font-bold">
                </div>
                <button type="submit" class="w-full p-6 bg-emerald-600 text-white rounded-3xl font-black shadow-xl hover:bg-black transition text-lg italic">تأكيد وتسجيل القبض</button>
            </form>
        </div>
    </div>

    <!-- سند القبض -->
    <div id="receiptDiv" class="receipt-print p-4">
        <div class="text-center">
            <h2 class="font-black text-lg">أسامة إلكتريك</h2>
            <p class="text-[10px]">سند قبض مالي (VOUCHER)</p>
            <hr style="border-top:1px dashed #000; margin: 10px 0;">
        </div>
        <div class="text-sm space-y-1">
            <p><strong>الرقم:</strong> <span id="r_id"></span></p>
            <p><strong>التاريخ:</strong> <?= date('Y-m-d H:i') ?></p>
            <p><strong>المشترك:</strong> <span id="r_cust"></span></p>
            <p><strong>المبلغ:</strong> <span id="r_amount" style="font-size:1.2rem; font-weight:900;"></span></p>
            <p><strong>عن فاتورة:</strong> <span id="r_bill"></span></p>
        </div>
        <hr style="border-top:1px dashed #000; margin: 10px 0;">
        <div class="text-center italic text-[10px]">شكراً لثقتكم - أسامة إلكتريك</div>
    </div>

    <script>
        function autoFill() {
            const sel = document.getElementById('bill_select');
            const info = document.getElementById('rateInfo');
            if(sel.selectedIndex > 0) {
                const opt = sel.options[sel.selectedIndex];
                const curr = document.getElementById('pay_currency').value;
                const rate = opt.getAttribute('data-rate');
                const usd = parseFloat(opt.getAttribute('data-usd'));
                const lbp = Math.round(usd * rate);
                document.getElementById('pay_amount').value = (curr === 'USD') ? usd : lbp;
                info.innerText = "سعر الصرف المعتمد: " + Number(rate).toLocaleString() + " ل.ل";
            } else { info.innerText = ""; }
        }
        document.getElementById('paySearch').addEventListener('input', function() {
            const val = this.value.toLowerCase();
            document.querySelectorAll('#payTable tbody tr').forEach(row => { row.style.display = row.innerText.toLowerCase().includes(val) ? '' : 'none'; });
        });
        function printReceipt(id) {
            const row = Array.from(document.querySelectorAll('#payTable tbody tr')).find(tr => tr.innerHTML.includes('printReceipt('+id+')'));
            if(row) {
                document.getElementById('r_id').innerText = id;
                document.getElementById('r_cust').innerText = row.cells[1].querySelector('.font-black').innerText;
                document.getElementById('r_amount').innerText = row.cells[2].innerText;
                document.getElementById('r_bill').innerText = row.cells[3].innerText;
                window.print();
            }
        }
        window.onload = function() { <?php if($auto_print_id): ?> printReceipt(<?= $auto_print_id ?>); <?php endif; ?> };
    </script>
</body>
</html>