<?php
session_start();

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

require_once 'db.php';

// جلب بيانات المستخدم الحالي وصلاحياته
$logged_user_id = $_SESSION['user_id'];
$user_role = strtolower($_SESSION['role'] ?? 'user');

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

// نصوص الترجمة - تم إضافة 'actions' لحل مشكلة التحذير
$texts = [
    'ar' => [
        'title' => 'تذكير الديون | كهرباء أسامة',
        'header' => 'مركز تذكير الديون (WhatsApp)',
        'sub_header' => 'مراسلة المديونين وتحصيل المستحقات بسرعة',
        'home' => 'الرئيسية',
        'filter_box' => 'العلبة',
        'filter_user' => 'الموظف المسؤول',
        'all_users' => 'الشبكة بالكامل',
        'total_pending' => 'إجمالي المطلوب تحصيله',
        'send_wa' => 'إرسال تذكير',
        'customer' => 'المشترك',
        'box' => 'العلبة',
        'amount' => 'المبلغ المستحق',
        'status' => 'الحالة',
        'actions' => 'العمليات',
        'no_debts' => 'لا توجد ديون معلقة لهذا النطاق حالياً.',
        'bill_cycle' => 'دورة'
    ],
    'en' => [
        'title' => 'Debt Reminders | Osama Electric',
        'header' => 'Debt Reminders (WhatsApp)',
        'sub_header' => 'Message debtors and collect payments quickly',
        'home' => 'Home',
        'filter_box' => 'Box',
        'filter_user' => 'Assigned Staff',
        'all_users' => 'Whole Network',
        'total_pending' => 'Total Outstanding',
        'send_wa' => 'Send Reminder',
        'customer' => 'Customer',
        'box' => 'Box',
        'amount' => 'Due Amount',
        'status' => 'Status',
        'actions' => 'Actions',
        'no_debts' => 'No outstanding debts found for this scope.',
        'bill_cycle' => 'Cycle'
    ]
];

// 2. بناء فلاتر الصلاحيات
$f_box = $_GET['f_box'] ?? '';
$f_user = $_GET['f_user'] ?? '';

// الموظف يرى زبائنه فقط، المدير يرى الكل أو يفلتر
$role_condition = ($user_role === 'admin') ? ($f_user !== '' ? "c.created_by = :uid" : "1=1") : "c.created_by = :uid";
$params = [];
if ($user_role !== 'admin' || $f_user !== '') {
    $params[':uid'] = ($user_role === 'admin') ? $f_user : $logged_user_id;
}

// إضافة فلتر العلبة
$box_condition = "1=1";
if ($f_box !== '') {
    $box_condition = "c.box_no = :box";
    $params[':box'] = $f_box;
}

// 3. جلب الديون المفتوحة (فواتير غير مدفوعة)
$query = "SELECT b.*, c.name as customer_name, c.box_no, c.phone, c.sub_no, p.exchange_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' AND $role_condition AND $box_condition
          ORDER BY c.box_no ASC, c.name ASC";

$stmt = $pdo->prepare($query);
$stmt->execute($params);
$debts = $stmt->fetchAll();

// حساب الإجمالي المستحق للنطاق المختار
$grand_total_usd = 0;
foreach($debts as $d) { $grand_total_usd += $d['amount_usd']; }

// جلب العلب المتاحة للمستخدم للفلترة
$box_q = "SELECT DISTINCT box_no FROM customers c WHERE box_no IS NOT NULL AND $role_condition ORDER BY box_no ASC";
$stmt_bx = $pdo->prepare($box_q);
if($user_role !== 'admin') { $stmt_bx->execute([':uid' => $logged_user_id]); } else { $stmt_bx->execute(); }
$unique_boxes = $stmt_bx->fetchAll(PDO::FETCH_COLUMN);

// جلب قائمة الموظفين (للأدمن)
$users_list = ($user_role === 'admin') ? $pdo->query("SELECT id, name FROM users ORDER BY name ASC")->fetchAll() : [];

?>

<!DOCTYPE html>
<html lang="<?= $lang ?>" dir="<?= $dir ?>">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= $texts[$lang]['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; }
        .wa-btn { background-color: #25D366; }
        .wa-btn:hover { background-color: #128C7E; }
    </style>
</head>
<body class="pb-20 text-slate-800">

    <div class="container mx-auto px-4 py-8 max-w-6xl">
        
        <!-- 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-500 text-white rounded-2xl flex items-center justify-center text-3xl shadow-xl shadow-emerald-100">
                    <i class="fab fa-whatsapp"></i>
                </div>
                <div>
                    <h1 class="text-2xl font-black text-slate-800 italic"><?= $texts[$lang]['header'] ?></h1>
                    <p class="text-sm text-slate-400 font-bold uppercase italic"><?= $texts[$lang]['sub_header'] ?></p>
                </div>
            </div>
            <a href="dashboard.php" class="bg-slate-100 text-slate-600 px-8 py-3 rounded-2xl font-bold hover:bg-slate-200 transition"><?= $texts[$lang]['home'] ?></a>
        </div>

        <!-- Summary & Filters -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
            
            <!-- Total Debt Card -->
            <div class="bg-slate-900 p-8 rounded-[2.5rem] text-white shadow-xl flex flex-col justify-center relative overflow-hidden border-b-8 border-rose-500">
                <i class="fas fa-hand-holding-usd absolute right-[-10px] bottom-[-10px] text-8xl opacity-10"></i>
                <p class="text-rose-400 text-[10px] font-black uppercase tracking-widest mb-1"><?= $texts[$lang]['total_pending'] ?></p>
                <h2 class="text-4xl font-black italic">$<?= number_format($grand_total_usd, 2) ?></h2>
            </div>

            <!-- Filters Area -->
            <div class="lg:col-span-2 bg-white p-6 rounded-[2.5rem] shadow-sm border border-slate-100 flex items-center">
                <form method="GET" class="grid grid-cols-1 md:grid-cols-3 gap-4 w-full items-end font-bold italic">
                    
                    <?php if($user_role === 'admin'): ?>
                    <div>
                        <label class="block text-[10px] text-slate-400 mb-2 uppercase"><?= $texts[$lang]['filter_user'] ?></label>
                        <select name="f_user" onchange="this.form.submit()" class="w-full p-4 bg-slate-50 rounded-2xl border-none font-black text-blue-600 outline-none cursor-pointer">
                            <option value=""><?= $texts[$lang]['all_users'] ?></option>
                            <?php foreach($users_list as $u): ?>
                                <option value="<?= $u['id'] ?>" <?= $f_user == $u['id'] ? 'selected' : '' ?>><?= htmlspecialchars($u['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <?php endif; ?>

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

                    <button type="submit" class="p-4 bg-blue-600 text-white rounded-2xl font-black hover:bg-black transition shadow-lg italic">
                        <?= $is_ar ? 'تحديث' : 'Refresh' ?>
                    </button>

                </form>
            </div>
        </div>

        <!-- Debtors Table -->
        <div class="bg-white rounded-[3rem] shadow-sm border border-slate-100 overflow-hidden">
            <div class="overflow-x-auto">
                <table class="w-full text-right font-bold italic">
                    <thead class="bg-slate-50 text-slate-400 text-[10px] font-black uppercase tracking-widest border-b">
                        <tr>
                            <th class="p-6"><?= $texts[$lang]['customer'] ?></th>
                            <th class="p-6 text-center"><?= $texts[$lang]['box'] ?></th>
                            <th class="p-6 text-center"><?= $texts[$lang]['amount'] ?></th>
                            <th class="p-6 text-center"><?= $texts[$lang]['actions'] ?></th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-50">
                        <?php if(empty($debts)): ?>
                            <tr><td colspan="4" class="p-20 text-center text-slate-300 font-black italic"><?= $texts[$lang]['no_debts'] ?></td></tr>
                        <?php endif; ?>

                        <?php foreach($debts as $d): 
                            $lbp_val = $d['amount_usd'] * ($d['exchange_rate'] ?: 0);
                            $clean_phone = preg_replace('/[^0-9]/', '', $d['phone']);
                            
                            // تجهيز رسالة تذكير احترافية
                            $wa_msg = "تحية من كهرباء أسامة  ⚡\n" .
                                      "عزيزي " . $d['customer_name'] . " (علبة: " . ($d['box_no'] ?: '---') . ")\n" .
                                      "نود تذكيركم بفاتورة الكهرباء المستحقة لشهر " . $d['month'] . "/" . $d['year'] . ".\n" .
                                      "المبلغ المطلوب: $" . number_format($d['amount_usd'], 2) . "\n" .
                                      "تقريباً بالليرة: " . number_format($lbp_val) . " ل.ل\n" .
                                      "يرجى تسوية الرصيد في أقرب وقت. شكراً لتعاونكم.";
                            
                            $wa_url = "https://wa.me/" . $clean_phone . "?text=" . urlencode($wa_msg);
                        ?>
                        <tr class="hover:bg-emerald-50/10 transition group">
                            <td class="p-6">
                                <div class="text-slate-800 font-black"><?= htmlspecialchars($d['customer_name']) ?></div>
                                <div class="text-[9px] text-slate-400">#<?= htmlspecialchars($d['sub_no']) ?> | Cycle: <?= $d['month'] ?>/<?= $d['year'] ?></div>
                            </td>
                            <td class="p-6 text-center">
                                <span class="bg-blue-50 text-blue-600 px-3 py-1 rounded-xl text-[10px] font-black">
                                    Box: <?= htmlspecialchars($d['box_no'] ?: '---') ?>
                                </span>
                            </td>
                            <td class="p-6 text-center">
                                <div class="text-rose-600 font-black text-lg">$<?= number_format($d['amount_usd'], 2) ?></div>
                                <div class="text-[9px] text-slate-400"><?= number_format($lbp_val) ?> L.L</div>
                            </td>
                            <td class="p-6 text-center">
                                <a href="<?= $wa_url ?>" target="_blank" class="wa-btn text-white px-6 py-2.5 rounded-2xl font-black text-xs inline-flex items-center gap-2 shadow-lg shadow-emerald-100 transform active:scale-95 transition-all">
                                    <i class="fab fa-whatsapp text-lg"></i> <?= $texts[$lang]['send_wa'] ?>
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="text-center text-slate-300 text-[10px] font-black uppercase tracking-[0.5em] mt-12 mb-8 italic">
            Osama Electric WhatsApp Billing v1.0
        </div>

    </div>

</body>
</html>