<?php
session_start();

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

require_once 'db.php';

// إعداد المنطقة الزمنية
date_default_timezone_set('Asia/Riyadh'); 

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

// --- التعامل مع السنة والشهر من الرابط ---
$current_year = date('Y');
$f_month = isset($_GET['f_month']) ? (int)$_GET['f_month'] : (int)date('n');
$f_year  = isset($_GET['f_year'])  ? (int)$_GET['f_year']  : (int)$current_year;

// --- [ميزة الحماية]: التحقق مما إذا كان الشهر مغلقاً ---
$check_closed = $pdo->prepare("SELECT id FROM closed_months WHERE month = ? AND year = ?");
$check_closed->execute([$f_month, $f_year]);
$is_month_closed = (bool)$check_closed->fetch();

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

// 2. معالجة الحفظ السريع
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['save_reading'])) {
    if ($is_month_closed) {
        $error = "عذراً، هذا الشهر مغلق مالياً ولا يمكن التعديل عليه.";
    } else {
        $customer_id = $_POST['customer_id'];
        $curr = $_POST['current_reading'];
        
        try {
            // [تحسين]: جلب القراءة السابقة الصحيحة برمجياً قبل الحفظ لضمان عدم ضياعها
            $last_stmt = $pdo->prepare("SELECT current_reading FROM meter_readings 
                                        WHERE meter_id = :cid 
                                        AND (year < :y1 OR (year = :y2 AND month < :m)) 
                                        ORDER BY year DESC, month DESC LIMIT 1");
            $last_stmt->execute([':cid' => $customer_id, ':y1' => $f_year, ':y2' => $f_year, ':m' => $f_month]);
            $db_prev = $last_stmt->fetchColumn();

            if ($db_prev === false) {
                // إذا لم توجد قراءات سابقة، نجلب القراءة الابتدائية من جدول المشتركين
                $init_stmt = $pdo->prepare("SELECT initial_reading FROM customers WHERE id = ?");
                $init_stmt->execute([$customer_id]);
                $db_prev = $init_stmt->fetchColumn() ?: 0;
            }

            $stmt = $pdo->prepare("INSERT INTO meter_readings (meter_id, previous_reading, current_reading, month, year) 
                                   VALUES (?, ?, ?, ?, ?) 
                                   ON DUPLICATE KEY UPDATE 
                                   current_reading = VALUES(current_reading), 
                                   previous_reading = VALUES(previous_reading)");
            $stmt->execute([$customer_id, $db_prev, $curr, $f_month, $f_year]);
            
            // تحديث جدول العدادات العام (إذا كان الجدول موجوداً)
            try {
                $pdo->prepare("UPDATE meters SET last_reading = ? WHERE customer_id = ?")->execute([$curr, $customer_id]);
            } catch (Exception $e) {}
            
            $message = "تم حفظ القراءة بنجاح ✓";
        } catch (PDOException $e) {
            $error = "حدث خطأ أثناء الحفظ: " . $e->getMessage();
        }
    }
}

// 3. جلب المشتركين
$query = "SELECT c.id, c.name, c.sub_no, c.phone, c.initial_reading,
                 r.current_reading, r.previous_reading
          FROM customers c
          LEFT JOIN meter_readings r ON c.id = r.meter_id AND r.month = :m AND r.year = :y
          WHERE c.system_type = 'meter' AND c.status = 1
          ORDER BY (r.current_reading IS NOT NULL) DESC, c.name ASC";

$stmt = $pdo->prepare($query);
$stmt->execute([':m' => $f_month, ':y' => $f_year]);
$customers = $stmt->fetchAll();

// حساب الإحصائيات
$total_count = count($customers);
$completed_count = 0;
foreach($customers as $c) { if($c['current_reading'] !== null) $completed_count++; }
$pending_count = $total_count - $completed_count;
$percent = $total_count > 0 ? round(($completed_count / $total_count) * 100) : 0;

// [تصحيح جوهري]: جلب القراءات السابقة وعرضها بدقة
$prev_map = [];
foreach ($customers as $cust) {
    if ($cust['previous_reading'] !== null && $cust['previous_reading'] !== '') {
        $prev_map[$cust['id']] = $cust['previous_reading'];
    } else {
        $last_stmt = $pdo->prepare("SELECT current_reading FROM meter_readings 
                                    WHERE meter_id = :cid 
                                    AND (year < :y1 OR (year = :y2 AND month < :m)) 
                                    ORDER BY year DESC, month DESC LIMIT 1");
        $last_stmt->execute([':cid' => $cust['id'], ':y1' => $f_year, ':y2' => $f_year, ':m' => $f_month]);
        $val = $last_stmt->fetchColumn();
        $prev_map[$cust['id']] = ($val !== false) ? $val : ($cust['initial_reading'] ?: 0);
    }
}
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl" class="scroll-smooth">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>إدارة العدادات | Smart Meter</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;600;700;800;900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/tesseract.js@4/dist/tesseract.min.js"></script>
    <script>
        tailwind.config = {
            darkMode: 'class',
            theme: {
                extend: {
                    fontFamily: { sans: ['Cairo', 'sans-serif'] },
                    colors: {
                        dark: {
                            bg: '#0f172a',
                            card: '#1e293b',
                            input: '#334155',
                            text: '#f1f5f9'
                        }
                    }
                }
            }
        }
    </script>
    <style>
        ::-webkit-scrollbar { width: 6px; }
        ::-webkit-scrollbar-track { background: transparent; }
        ::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 20px; }
        .dark ::-webkit-scrollbar-thumb { background: #475569; }

        .glass-header {
            background: rgba(255, 255, 255, 0.85);
            backdrop-filter: blur(12px);
            border-bottom: 1px solid rgba(255, 255, 255, 0.3);
        }
        .dark .glass-header {
            background: rgba(15, 23, 42, 0.85);
            border-bottom: 1px solid rgba(255, 255, 255, 0.05);
        }

        .card-anim { animation: fadeUp 0.6s cubic-bezier(0.16, 1, 0.3, 1) forwards; opacity: 0; transform: translateY(20px); }
        @keyframes fadeUp { to { opacity: 1; transform: translateY(0); } }

        .scanner-view { position: relative; overflow: hidden; border-radius: 1.5rem; }
        .scan-line { width: 100%; height: 2px; background: #3b82f6; box-shadow: 0 0 10px #3b82f6; animation: scan 2s linear infinite; }
        @keyframes scan { 0% { transform: translateY(0); opacity: 0; } 10% { opacity: 1; } 90% { opacity: 1; } 100% { transform: translateY(300px); opacity: 0; } }
    </style>
</head>
<body class="bg-slate-50 text-slate-800 dark:bg-dark-bg dark:text-dark-text transition-colors duration-300 pb-24">

    <!-- Header -->
    <header class="fixed top-0 w-full z-50 glass-header transition-all duration-300">
        <div class="container mx-auto px-4 py-3 flex justify-between items-center">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-gradient-to-tr from-blue-600 to-indigo-600 flex items-center justify-center text-white shadow-lg">
                    <i class="fas fa-bolt text-lg"></i>
                </div>
                <div>
                    <h1 class="font-black text-base leading-none dark:text-white">القراءات</h1>
                    <p class="text-[10px] text-slate-500 dark:text-slate-400 font-bold mt-1">لوحة التحكم الذكية</p>
                </div>
            </div>

            <div class="flex items-center gap-3">
                <button onclick="toggleTheme()" class="w-10 h-10 rounded-full bg-slate-100 dark:bg-slate-800 text-slate-600 flex items-center justify-center">
                    <i class="fas fa-moon dark:hidden"></i>
                    <i class="fas fa-sun hidden dark:block text-yellow-400"></i>
                </button>
                <a href="dashboard.php" class="w-10 h-10 rounded-full bg-blue-50 dark:bg-blue-900/30 text-blue-600 flex items-center justify-center">
                    <i class="fas fa-home"></i>
                </a>
            </div>
        </div>
    </header>

    <div class="h-20"></div>

    <div class="container mx-auto max-w-7xl px-4 mt-6">

        <!-- Stats Dashboard -->
        <div class="grid grid-cols-3 gap-3 mb-6">
            <div class="bg-white dark:bg-dark-card p-4 rounded-2xl shadow-sm border border-slate-100 dark:border-slate-800 flex flex-col items-center text-center">
                <span class="text-xl font-black text-slate-800 dark:text-white"><?= $total_count ?></span>
                <span class="text-[9px] text-slate-400 font-bold">الكل</span>
            </div>
            <div class="bg-white dark:bg-dark-card p-4 rounded-2xl shadow-sm border border-slate-100 dark:border-slate-800 flex flex-col items-center text-center">
                <span class="text-xl font-black text-emerald-600 dark:text-emerald-400"><?= $completed_count ?></span>
                <span class="text-[9px] text-slate-400 font-bold">مكتمل</span>
            </div>
            <div class="bg-white dark:bg-dark-card p-4 rounded-2xl shadow-sm border border-slate-100 dark:border-slate-800 flex flex-col items-center text-center">
                <span class="text-xl font-black text-amber-600 dark:text-amber-400"><?= $pending_count ?></span>
                <span class="text-[9px] text-slate-400 font-bold">متبقي</span>
            </div>
        </div>

        <!-- Progress Bar -->
        <div class="mb-8 relative pt-1">
            <div class="flex mb-2 items-center justify-between">
                <span class="text-xs font-bold text-blue-600"><?= $percent ?>%</span>
            </div>
            <div class="overflow-hidden h-2 mb-4 text-xs flex rounded-full bg-blue-200 dark:bg-slate-700">
                <div style="width:<?= $percent ?>%" class="shadow-none flex flex-col text-center whitespace-nowrap text-white justify-center bg-gradient-to-r from-blue-500 to-indigo-600 transition-all duration-1000"></div>
            </div>
        </div>

        <!-- Controls & Filter -->
        <div class="bg-white dark:bg-dark-card p-5 rounded-3xl shadow-sm border border-slate-100 dark:border-slate-800 mb-8">
            <form id="filterForm" method="GET" class="space-y-4">
                <div class="relative group">
                    <i class="fas fa-search absolute right-4 top-1/2 -translate-y-1/2 text-slate-300"></i>
                    <input type="text" id="mainSearch" placeholder="ابحث عن مشترك..." class="w-full h-12 pr-11 pl-4 bg-slate-50 dark:bg-dark-input dark:text-white rounded-2xl text-sm font-bold border-none focus:ring-2 focus:ring-blue-500/50">
                </div>

                <div class="grid grid-cols-2 gap-3">
                    <select name="f_month" onchange="this.form.submit()" class="w-full h-12 px-4 bg-slate-50 dark:bg-dark-input dark:text-white rounded-2xl text-xs font-bold border-none appearance-none cursor-pointer">
                        <?php 
                        $months = [1=>'يناير',2=>'فبراير',3=>'مارس',4=>'أبريل',5=>'مايو',6=>'يونيو',7=>'يوليو',8=>'أغسطس',9=>'سبتمبر',10=>'أكتوبر',11=>'نوفمبر',12=>'ديسمبر'];
                        foreach($months as $num => $name) {
                            echo "<option value='$num' ".($f_month == $num ? 'selected' : '').">$name</option>";
                        }
                        ?>
                    </select>
                    <select name="f_year" onchange="this.form.submit()" class="w-full h-12 px-4 bg-slate-800 text-white rounded-2xl text-xs font-bold border-none cursor-pointer">
                        <?php 
                        for($y = date('Y')+1; $y >= 2023; $y--) {
                            echo "<option value='$y' ".($f_year == $y ? 'selected' : '').">سنة $y</option>";
                        }
                        ?>
                    </select>
                </div>
            </form>
        </div>

        <!-- Messages -->
        <?php if($message): ?>
            <div id="alertMsg" class="bg-emerald-500 text-white p-4 rounded-2xl mb-6 font-bold shadow-lg flex items-center gap-3 animate-bounce">
                <i class="fas fa-check-circle"></i> <?= $message ?>
            </div>
            <script>setTimeout(() => document.getElementById('alertMsg').style.display='none', 3000);</script>
        <?php endif; ?>
        
        <?php if($error): ?>
            <div class="bg-rose-500 text-white p-4 rounded-2xl mb-6 font-bold shadow-lg flex items-center gap-3">
                <i class="fas fa-times-circle"></i> <?= $error ?>
            </div>
        <?php endif; ?>

        <!-- Customers Grid -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-5" id="customersList">
            <?php foreach($customers as $index => $c): 
                $prev_val = $prev_map[$c['id']];
                $curr_val = $c['current_reading'] ?: '';
                $is_done = ($c['current_reading'] !== null);
                
                $border_color = $is_done ? 'border-emerald-500' : 'border-transparent';
            ?>
            <div class="customer-card card-anim bg-white dark:bg-dark-card rounded-[1.5rem] p-5 shadow-sm border-l-4 <?= $border_color ?> border-t border-r border-b border-slate-100 dark:border-slate-800" style="animation-delay: <?= $index * 50 ?>ms">
                
                <div class="flex justify-between items-start mb-5">
                    <div class="flex items-center gap-3">
                        <div class="w-3 h-3 rounded-full <?= $is_done ? 'bg-emerald-500' : 'bg-slate-300' ?>"></div>
                        <h3 class="font-bold text-slate-800 dark:text-white text-base truncate w-40"><?= htmlspecialchars($c['name']) ?></h3>
                    </div>
                    <?php if(!$is_month_closed): ?>
                        <button onclick="launchScanner(<?= $c['id'] ?>)" class="w-9 h-9 bg-blue-50 dark:bg-blue-900/30 text-blue-600 rounded-xl flex items-center justify-center">
                            <i class="fas fa-camera text-sm"></i>
                        </button>
                    <?php endif; ?>
                </div>

                <form method="POST">
                    <input type="hidden" name="save_reading" value="1">
                    <input type="hidden" name="customer_id" value="<?= $c['id'] ?>">

                    <div class="flex items-center gap-3 mb-4">
                        <div class="flex-1 bg-slate-50 dark:bg-dark-input p-3 rounded-2xl border border-slate-100 dark:border-slate-700">
                            <label class="block text-[9px] text-slate-400 font-bold mb-1 uppercase">السابقة</label>
                            <!-- عرض القراءة السابقة بوضوح -->
                            <input type="text" value="<?= $prev_val ?>" readonly class="w-full bg-transparent font-bold text-slate-600 dark:text-slate-400 text-sm outline-none">
                        </div>

                        <i class="fas fa-arrow-left text-slate-300 text-xs"></i>

                        <div class="flex-1 bg-white dark:bg-dark-input p-3 rounded-2xl border-2 <?= $is_done ? 'border-emerald-100' : 'border-blue-100 focus-within:border-blue-500' ?> transition-colors shadow-sm">
                            <label class="block text-[9px] <?= $is_done ? 'text-emerald-500' : 'text-blue-500' ?> font-bold mb-1 uppercase">الحالية</label>
                            <input type="number" step="0.01" name="current_reading" id="curr_<?= $c['id'] ?>" value="<?= $curr_val ?>" 
                                   <?= $is_month_closed ? 'disabled' : 'required' ?>
                                   oninput="reCalc(<?= $c['id'] ?>, <?= $prev_val ?>)" 
                                   class="w-full bg-transparent font-black text-slate-800 dark:text-white text-lg outline-none" placeholder="0.0">
                        </div>
                    </div>

                    <div class="flex justify-between items-end mt-2">
                        <div>
                            <span class="text-[9px] text-slate-400 font-bold block">الاستهلاك</span>
                            <span id="res_<?= $c['id'] ?>" class="font-black text-slate-800 dark:text-white text-sm">
                                <?= $is_done ? number_format($curr_val - $prev_val, 2) : '---' ?>
                            </span>
                        </div>
                        
                        <?php if(!$is_month_closed): ?>
                            <button type="submit" class="bg-slate-900 dark:bg-blue-600 text-white px-5 py-2 rounded-xl text-xs font-bold shadow-lg hover:bg-slate-800 transition-all active:scale-95">
                                <?= $is_done ? 'تحديث' : 'حفظ' ?>
                            </button>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- Scanner Modal -->
    <div id="scanModal" class="fixed inset-0 z-[100] hidden items-end sm:items-center justify-center bg-black/90 backdrop-blur-sm">
        <div class="w-full sm:max-w-md bg-white dark:bg-dark-card sm:rounded-[2rem] rounded-t-[2rem] overflow-hidden shadow-2xl relative">
            <div class="p-4 flex justify-between items-center border-b border-slate-100 dark:border-slate-800">
                <h3 class="font-bold text-slate-800 dark:text-white text-sm">ماسح العداد</h3>
                <button onclick="stopScanner()" class="w-8 h-8 rounded-full bg-slate-100 dark:bg-slate-700 text-slate-500 flex items-center justify-center"><i class="fas fa-times"></i></button>
            </div>
            <div class="relative bg-black h-80">
                <video id="video" class="w-full h-full object-cover" autoplay playsinline></video>
                <div class="absolute inset-0 flex flex-col items-center justify-center pointer-events-none">
                    <div class="w-64 h-32 border-2 border-white/50 rounded-xl relative overflow-hidden">
                        <div class="scan-line"></div>
                    </div>
                </div>
            </div>
            <div class="p-5 bg-white dark:bg-dark-card">
                <div id="ocrStatus" class="hidden mb-4 text-center">
                    <span class="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-blue-50 text-blue-600 text-xs font-bold animate-pulse">
                        <i class="fas fa-sync fa-spin"></i> جاري التحليل...
                    </span>
                </div>
                <button id="snapBtn" class="w-full py-4 bg-gradient-to-r from-blue-600 to-indigo-600 text-white rounded-2xl font-black text-sm shadow-xl flex items-center justify-center gap-2">
                    <i class="fas fa-camera text-lg"></i> التقاط وقراءة
                </button>
            </div>
        </div>
        <canvas id="canvas" class="hidden"></canvas>
    </div>

    <script>
        function toggleTheme() {
            document.documentElement.classList.toggle('dark');
            localStorage.setItem('theme', document.documentElement.classList.contains('dark') ? 'dark' : 'light');
        }
        if (localStorage.theme === 'dark') document.documentElement.classList.add('dark');

        document.getElementById('mainSearch').addEventListener('input', function() {
            const term = this.value.toLowerCase();
            document.querySelectorAll('.customer-card').forEach(card => {
                card.style.display = card.innerText.toLowerCase().includes(term) ? 'block' : 'none';
            });
        });

        function reCalc(id, prev) {
            const c = parseFloat(document.getElementById('curr_' + id).value) || 0;
            const resEl = document.getElementById('res_' + id);
            const diff = (c - prev).toFixed(2);
            resEl.innerText = diff;
            resEl.className = (c < prev) ? 'font-black text-rose-500 text-sm' : 'font-black text-slate-800 dark:text-white text-sm';
        }

        let activeId = null;
        let stream = null;
        const video = document.getElementById('video');
        const modal = document.getElementById('scanModal');

        async function launchScanner(id) {
            activeId = id;
            modal.classList.replace('hidden', 'flex');
            try {
                stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } });
                video.srcObject = stream;
            } catch (e) { alert("الكاميرا غير متاحة"); stopScanner(); }
        }

        function stopScanner() {
            if (stream) stream.getTracks().forEach(t => t.stop());
            modal.classList.replace('flex', 'hidden');
        }

        document.getElementById('snapBtn').addEventListener('click', async () => {
            document.getElementById('ocrStatus').classList.remove('hidden');
            const canvas = document.getElementById('canvas');
            canvas.width = video.videoWidth; canvas.height = video.videoHeight;
            canvas.getContext('2d').drawImage(video, 0, 0);

            try {
                const result = await Tesseract.recognize(canvas, 'eng', { tessedit_char_whitelist: '0123456789.' });
                const text = result.data.text;
                const numbers = text.match(/\d+(\.\d+)?/g);
                if (numbers) {
                    const finalNum = numbers.reduce((a, b) => a.length > b.length ? a : b);
                    document.getElementById('curr_' + activeId).value = finalNum;
                    // تفعيل الحدث يدوياً لتحديث الاستهلاك
                    const prevInput = document.querySelector(`#curr_${activeId}`).closest('form').querySelector('input[readonly]');
                    reCalc(activeId, parseFloat(prevInput.value));
                    stopScanner();
                } else { alert("لم يتم التعرف على الأرقام"); }
            } catch (e) { console.error(e); }
            document.getElementById('ocrStatus').classList.add('hidden');
        });
    </script>
</body>
</html>