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

$texts = [
    'ar' => [
        'title' => 'إدارة العدادات | أسامة إلكتريك',
        'header' => 'ربط وإدارة العدادات',
        'sub_header' => 'تخصيص أجهزة العدادات للمشتركين ومتابعة حالتها',
        'add_btn' => 'تسجيل عداد جديد',
        'edit_btn' => 'تعديل بيانات العداد',
        'customer' => 'المشترك',
        'meter_no' => 'رقم العداد (S/N)',
        'last_reading' => 'آخر قراءة',
        'date' => 'تاريخ التركيب',
        'status' => 'الحالة',
        'save' => 'حفظ البيانات',
        'cancel' => 'إلغاء التعديل',
        'success' => 'تمت العملية بنجاح',
        'error_dup' => 'خطأ: رقم العداد هذا مسجل مسبقاً لمشترك آخر!',
        'no_meters' => 'لا يوجد عدادات مسجلة حالياً.',
        'select_cust' => '--- اختر مشتركاً ---',
        'actions' => 'العمليات'
    ],
    'en' => [
        'title' => 'Meter Management | Osama Electric',
        'header' => 'Meter Linking & Management',
        'sub_header' => 'Assign meter devices to customers and track status',
        'add_btn' => 'Register New Meter',
        'edit_btn' => 'Edit Meter Data',
        'customer' => 'Customer',
        'meter_no' => 'Meter Serial (S/N)',
        'last_reading' => 'Last Reading',
        'date' => 'Install Date',
        'status' => 'Status',
        'save' => 'Save Data',
        'cancel' => 'Cancel Edit',
        'success' => 'Operation successful',
        'error_dup' => 'Error: This meter serial is already registered!',
        'no_meters' => 'No meters registered yet.',
        'select_cust' => '--- Select customer ---',
        'actions' => 'Actions'
    ]
];

$message = '';
$error = '';

// 2. معالجة الإضافة والتعديل
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_meter'])) {
    $cust_id = $_POST['customer_id'];
    $m_serial = $_POST['meter_number'];
    $edit_id = $_POST['edit_id'] ?? null;

    try {
        // التحقق من عدم تكرار الرقم لعداد آخر غير الحالي
        $check_sql = "SELECT id FROM meters WHERE meter_number = ? " . ($edit_id ? " AND id != ?" : "");
        $check = $pdo->prepare($check_sql);
        if ($edit_id) {
            $check->execute([$m_serial, $edit_id]);
        } else {
            $check->execute([$m_serial]);
        }
        
        if ($check->rowCount() > 0) {
            $error = $texts[$lang]['error_dup'];
        } else {
            if ($edit_id) {
                // جلب الرقم التسلسلي القديم لتحديثه في جدول المشتركين
                $old_sn = $pdo->query("SELECT meter_number FROM meters WHERE id = $edit_id")->fetchColumn();
                
                // تحديث جدول العدادات
                $stmt = $pdo->prepare("UPDATE meters SET customer_id = ?, meter_number = ? WHERE id = ?");
                $stmt->execute([$cust_id, $m_serial, $edit_id]);
                
                // تحديث جدول المشتركين (الربط)
                $upd = $pdo->prepare("UPDATE customers SET meter_id = ? WHERE meter_id = ?");
                $upd->execute([$m_serial, $old_sn]);
                
                $action_name = "Updated Meter $m_serial (ID: $edit_id)";
            } else {
                // جلب القراءة الأولية للمشترك
                $cust_data = $pdo->prepare("SELECT initial_reading FROM customers WHERE id = ?");
                $cust_data->execute([$cust_id]);
                $initial = $cust_data->fetchColumn() ?: 0;

                $stmt = $pdo->prepare("INSERT INTO meters (customer_id, meter_number, last_reading) VALUES (?, ?, ?)");
                $stmt->execute([$cust_id, $m_serial, $initial]);

                $upd = $pdo->prepare("UPDATE customers SET meter_id = ? WHERE id = ?");
                $upd->execute([$m_serial, $cust_id]);
                
                $action_name = "Linked New Meter $m_serial to Customer $cust_id";
            }

            $message = $texts[$lang]['success'];
            $pdo->prepare("INSERT INTO audit_log (user_id, action) VALUES (?, ?)")
                ->execute([$_SESSION['user_id'], $action_name]);
        }
    } catch (PDOException $e) {
        $error = "Database Error: " . $e->getMessage();
    }
}

// 3. معالجة الحذف
if (isset($_GET['delete'])) {
    $del_id = $_GET['delete'];
    try {
        // فك الارتباط من جدول المشتركين أولاً
        $sn = $pdo->query("SELECT meter_number FROM meters WHERE id = $del_id")->fetchColumn();
        $pdo->prepare("UPDATE customers SET meter_id = NULL WHERE meter_id = ?")->execute([$sn]);
        
        // حذف العداد
        $pdo->prepare("DELETE FROM meters WHERE id = ?")->execute([$del_id]);
        header("Location: meters.php?success=1");
        exit;
    } catch (PDOException $e) { $error = $e->getMessage(); }
}

// 4. جلب البيانات
$customers_to_assign = $pdo->query("
    SELECT c.id, c.name 
    FROM customers c 
    LEFT JOIN meters m ON c.id = m.customer_id 
    WHERE c.system_type = 'meter' AND (m.id IS NULL OR c.meter_id IS NULL)
")->fetchAll();

$all_meters = $pdo->query("
    SELECT m.*, c.name as customer_name 
    FROM meters m 
    JOIN customers c ON m.customer_id = c.id 
    ORDER BY m.id DESC
")->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: #f8fafc; }</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 md: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-microchip"></i>
                </div>
                <div>
                    <h1 class="text-2xl font-black text-slate-800"><?= $texts[$lang]['header'] ?></h1>
                    <p class="text-sm text-slate-400 font-bold"><?= $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">الرئيسية</a>
        </div>

        <?php if($message || isset($_GET['success'])): ?>
            <div class="bg-emerald-500 text-white p-5 rounded-2xl mb-8 font-bold flex items-center gap-3 shadow-lg shadow-emerald-100 animate-bounce">
                <i class="fas fa-check-circle text-xl"></i> <?= $texts[$lang]['success'] ?>
            </div>
        <?php endif; ?>

        <?php if($error): ?>
            <div class="bg-rose-500 text-white p-5 rounded-2xl mb-8 font-bold flex items-center gap-3 shadow-lg shadow-rose-100">
                <i class="fas fa-exclamation-triangle text-xl"></i> <?= $error ?>
            </div>
        <?php endif; ?>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <!-- Form Section -->
            <div class="lg:col-span-1">
                <div class="bg-white p-8 rounded-[2.5rem] shadow-sm border border-slate-100 sticky top-8">
                    <h3 id="formTitle" class="text-xl font-black mb-6 text-slate-800 flex items-center gap-2">
                        <i class="fas fa-plus-circle text-blue-600"></i> <?= $texts[$lang]['add_btn'] ?>
                    </h3>
                    
                    <form method="POST" id="meterForm" class="space-y-6">
                        <input type="hidden" name="save_meter" value="1">
                        <input type="hidden" name="edit_id" id="edit_id" value="">
                        
                        <div>
                            <label class="block text-xs font-black text-slate-400 mb-2 uppercase tracking-widest"><?= $texts[$lang]['customer'] ?></label>
                            <select name="customer_id" id="customer_id" required class="w-full p-4 bg-slate-50 rounded-2xl border-none font-bold focus:ring-2 focus:ring-blue-600 outline-none">
                                <option value=""><?= $texts[$lang]['select_cust'] ?></option>
                                <?php 
                                // دمج المشتركين المتاحين مع المشترك الذي يتم تعديله حالياً لكي يظهر في القائمة
                                foreach($customers_to_assign as $cta): ?>
                                    <option value="<?= $cta['id'] ?>"><?= htmlspecialchars($cta['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                            <p id="editNote" class="hidden text-[10px] text-blue-500 font-bold mt-2 italic">ملاحظة: عند التعديل، تأكد من اختيار المشترك الصحيح.</p>
                        </div>

                        <div>
                            <label class="block text-xs font-black text-slate-400 mb-2 uppercase tracking-widest"><?= $texts[$lang]['meter_no'] ?></label>
                            <input type="text" name="meter_number" id="meter_number" required placeholder="S/N: 00000000" 
                                   class="w-full p-4 bg-slate-50 rounded-2xl border-none font-bold focus:ring-2 focus:ring-blue-600 outline-none uppercase">
                        </div>

                        <div class="space-y-3">
                            <button type="submit" class="w-full p-5 bg-blue-600 hover:bg-black text-white rounded-3xl font-black shadow-xl shadow-blue-100 transition transform active:scale-95">
                                <?= $texts[$lang]['save'] ?>
                            </button>
                            <button type="button" id="cancelBtn" onclick="resetForm()" class="hidden w-full p-4 bg-slate-100 text-slate-500 rounded-3xl font-bold hover:bg-slate-200 transition">
                                <?= $texts[$lang]['cancel'] ?>
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Table Section -->
            <div class="lg:col-span-2">
                <div class="bg-white rounded-[2.5rem] shadow-sm border border-slate-100 overflow-hidden">
                    <div class="p-8 bg-slate-50 border-b border-slate-100 flex justify-between items-center">
                        <h3 class="font-black text-slate-800"><?= $texts[$lang]['header'] ?></h3>
                        <span class="bg-blue-600 text-white px-4 py-1 rounded-full text-[10px] font-black"><?= count($all_meters) ?> العدادات</span>
                    </div>
                    <div class="overflow-x-auto">
                        <table class="w-full text-<?= $is_ar ? 'right' : 'left' ?>">
                            <thead class="bg-slate-50 text-slate-400 text-[10px] font-black uppercase tracking-[0.2em]">
                                <tr>
                                    <th class="p-6"><?= $texts[$lang]['customer'] ?></th>
                                    <th class="p-6 text-center"><?= $texts[$lang]['meter_no'] ?></th>
                                    <th class="p-6 text-center"><?= $texts[$lang]['last_reading'] ?></th>
                                    <th class="p-6 text-center"><?= $texts[$lang]['actions'] ?></th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-50">
                                <?php foreach($all_meters as $m): ?>
                                <tr class="hover:bg-blue-50/20 transition group">
                                    <td class="p-6">
                                        <div class="font-black text-slate-800 italic"><?= htmlspecialchars($m['customer_name']) ?></div>
                                        <div class="text-[9px] text-slate-400 uppercase font-bold tracking-widest">Connected Device</div>
                                    </td>
                                    <td class="p-6 text-center">
                                        <span class="bg-blue-50 text-blue-600 px-4 py-2 rounded-xl font-black text-sm">
                                            #<?= htmlspecialchars($m['meter_number']) ?>
                                        </span>
                                    </td>
                                    <td class="p-6 text-center font-black text-slate-400"><?= number_format($m['last_reading'], 2) ?></td>
                                    <td class="p-6 text-center flex justify-center gap-2">
                                        <button onclick='editMeter(<?= json_encode($m) ?>)' class="p-3 text-blue-500 hover:bg-blue-100 rounded-xl transition shadow-sm" title="<?= $texts[$lang]['edit'] ?>">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <a href="?delete=<?= $m['id'] ?>" onclick="return confirm('تأكيد فك ارتباط وحذف العداد؟')" class="p-3 text-rose-500 hover:bg-rose-100 rounded-xl transition shadow-sm" title="حذف">
                                            <i class="fas fa-trash-alt"></i>
                                        </a>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                <?php if(empty($all_meters)): ?>
                                    <tr><td colspan="4" class="p-20 text-center text-slate-300 font-bold italic"><?= $texts[$lang]['no_meters'] ?></td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        function editMeter(data) {
            // تحديث عنوان النموذج
            document.getElementById('formTitle').innerHTML = '<i class="fas fa-edit text-blue-600"></i> <?= $texts[$lang]['edit_btn'] ?>';
            
            // تعبئة الحقول
            document.getElementById('edit_id').value = data.id;
            document.getElementById('meter_number').value = data.meter_number;
            
            // إضافة خيار المشترك الحالي للقائمة إذا لم يكن موجوداً
            const select = document.getElementById('customer_id');
            let exists = false;
            for(let i=0; i<select.options.length; i++) {
                if(select.options[i].value == data.customer_id) {
                    exists = true;
                    break;
                }
            }
            if(!exists) {
                const opt = document.createElement('option');
                opt.value = data.customer_id;
                opt.text = data.customer_name;
                select.add(opt);
            }
            select.value = data.customer_id;

            // إظهار زر الإلغاء والملاحظة
            document.getElementById('cancelBtn').classList.remove('hidden');
            document.getElementById('editNote').classList.remove('hidden');
            
            // الانتقال للنموذج (في حال كانت الشاشة صغيرة)
            window.scrollTo({ top: document.getElementById('meterForm').offsetTop - 100, behavior: 'smooth' });
        }

        function resetForm() {
            document.getElementById('formTitle').innerHTML = '<i class="fas fa-plus-circle text-blue-600"></i> <?= $texts[$lang]['add_btn'] ?>';
            document.getElementById('edit_id').value = "";
            document.getElementById('meter_number').value = "";
            document.getElementById('customer_id').value = "";
            document.getElementById('cancelBtn').classList.add('hidden');
            document.getElementById('editNote').classList.add('hidden');
        }
    </script>
</body>
</html>