<?php
session_start();

// 1. إدارة اللغة والجلسة
if (isset($_GET['lang'])) {
    $_SESSION['lang'] = $_GET['lang'];
}
$lang = $_SESSION['lang'] ?? 'ar';
$is_ar = ($lang === 'ar');
$dir = $is_ar ? 'rtl' : 'ltr';

// نصوص الترجمة
$texts = [
    'ar' => [
        'title' => 'إغلاق الأشهر - أسامة إلكتريك',
        'header' => 'إدارة إغلاق الأشهر المالية',
        'sub_header' => 'حماية البيانات من التعديل بعد إصدار الفواتير النهائية والتحصيل',
        'home' => 'الرئيسية',
        'close_new_month' => 'إغلاق شهر جديد',
        'month' => 'الشهر',
        'year' => 'السنة',
        'closed_at' => 'تاريخ الإغلاق',
        'closed_by' => 'بواسطة',
        'history' => 'سجل الأشهر المغلقة',
        'save' => 'تأكيد الإغلاق النهائي',
        'success' => 'تم إغلاق الشهر بنجاح، لا يمكن التعديل عليه الآن.',
        'error_exists' => 'خطأ: هذا الشهر مغلق مسبقاً!',
        'warning' => 'تنبيه: بعد إغلاق الشهر، لن تتمكن من إصدار فواتير أو تعديل قراءات لهذا الشهر أبداً.',
        'no_data' => 'لا توجد أشهر مغلقة حالياً.'
    ],
    'en' => [
        'title' => 'Close Months - Osama Electric',
        'header' => 'Financial Month Closing',
        'sub_header' => 'Protect data from modification after final invoicing and collection',
        'home' => 'Home',
        'close_new_month' => 'Close New Month',
        'month' => 'Month',
        'year' => 'Year',
        'closed_at' => 'Closed At',
        'closed_by' => 'By',
        'history' => 'Closed Months History',
        'save' => 'Confirm Final Closing',
        'success' => 'Month closed successfully, modifications are now disabled.',
        'error_exists' => 'Error: This month is already closed!',
        'warning' => 'Warning: Once a month is closed, you cannot issue bills or edit readings for it.',
        'no_data' => 'No closed months found.'
    ]
];

// 2. تضمين ملف الاتصال PDO
if (file_exists('db.php')) {
    include 'db.php';
} else {
    die("Error: db.php not found.");
}

// ميزة الإصلاح التلقائي لجدول الأشهر المغلقة
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `closed_months` (
        `id` INT AUTO_INCREMENT PRIMARY KEY,
        `month` INT NOT NULL,
        `year` INT NOT NULL,
        `closed_by` INT DEFAULT NULL,
        `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        UNIQUE KEY `unique_month_year` (`month`, `year`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
} catch (PDOException $e) {}

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

// 3. معالجة إغلاق شهر
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['close_month_action'])) {
    $month = $_POST['month'];
    $year = $_POST['year'];
    
    try {
        $stmt = $pdo->prepare("INSERT INTO closed_months (month, year) VALUES (?, ?)");
        $stmt->execute([$month, $year]);
        $message = $texts[$lang]['success'];
    } catch (PDOException $e) {
        if ($e->getCode() == 23000) {
            $error = $texts[$lang]['error_exists'];
        } else {
            $error = "Error: " . $e->getMessage();
        }
    }
}

// 4. جلب سجل الأشهر المغلقة
$history = $pdo->query("SELECT * FROM closed_months ORDER BY year DESC, month DESC")->fetchAll();
?>

<!DOCTYPE html>
<html lang="<?= $lang ?>" dir="<?= $dir ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <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; }</style>
</head>
<body class="pb-12 text-slate-800">

    <div class="container mx-auto px-4 py-8 max-w-5xl">
        <!-- 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-slate-800 text-white rounded-2xl flex items-center justify-center text-3xl shadow-xl shadow-slate-200">
                    <i class="fas fa-lock"></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-10 py-3 rounded-2xl font-bold hover:bg-slate-200 transition">
                <?= $texts[$lang]['home'] ?>
            </a>
        </div>

        <?php if($message): ?>
            <div class="bg-emerald-500 text-white p-5 rounded-2xl mb-8 font-bold shadow-lg shadow-emerald-100 flex items-center gap-3 animate-in slide-in-from-top-4 duration-500">
                <i class="fas fa-check-double text-xl"></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 shadow-rose-100 flex items-center gap-3">
                <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">
            <!-- Close Month Form -->
            <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 class="font-black text-xl mb-6 text-slate-700"><?= $texts[$lang]['close_new_month'] ?></h3>
                    
                    <div class="bg-amber-50 border border-amber-100 p-4 rounded-2xl mb-6">
                        <p class="text-[10px] text-amber-700 font-black leading-relaxed">
                            <i class="fas fa-info-circle me-1"></i> <?= $texts[$lang]['warning'] ?>
                        </p>
                    </div>

                    <form method="POST" class="space-y-6">
                        <input type="hidden" name="close_month_action" value="1">
                        
                        <div>
                            <label class="block text-xs font-black text-slate-400 mb-2 uppercase tracking-widest"><?= $texts[$lang]['month'] ?></label>
                            <select name="month" class="w-full p-4 bg-slate-50 rounded-2xl border-none font-bold focus:ring-2 focus:ring-slate-800 transition">
                                <?php for($m=1; $m<=12; $m++): ?>
                                    <option value="<?= $m ?>" <?= date('n')-1 == $m ? 'selected' : '' ?>><?= $m ?></option>
                                <?php endfor; ?>
                            </select>
                        </div>

                        <div>
                            <label class="block text-xs font-black text-slate-400 mb-2 uppercase tracking-widest"><?= $texts[$lang]['year'] ?></label>
                            <select name="year" class="w-full p-4 bg-slate-50 rounded-2xl border-none font-bold focus:ring-2 focus:ring-slate-800 transition">
                                <?php for($y=2024; $y<=2026; $y++): ?>
                                    <option value="<?= $y ?>" <?= date('Y') == $y ? 'selected' : '' ?>><?= $y ?></option>
                                <?php endfor; ?>
                            </select>
                        </div>

                        <button type="submit" onclick="return confirm('تأكيد الإغلاق؟')" class="w-full p-5 bg-slate-800 text-white rounded-2xl font-black shadow-xl shadow-slate-200 hover:bg-black transition transform active:scale-95">
                            <?= $texts[$lang]['save'] ?>
                        </button>
                    </form>
                </div>
            </div>

            <!-- History Table -->
            <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 border-b border-slate-50 bg-slate-50/50">
                        <h3 class="font-black text-slate-700 flex items-center gap-3">
                            <i class="fas fa-history text-slate-400"></i> <?= $texts[$lang]['history'] ?>
                        </h3>
                    </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-widest">
                                <tr>
                                    <th class="p-6"><?= $texts[$lang]['month'] ?></th>
                                    <th class="p-6"><?= $texts[$lang]['year'] ?></th>
                                    <th class="p-6"><?= $texts[$lang]['closed_at'] ?></th>
                                    <th class="p-6 text-center">Status</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-50">
                                <?php foreach($history as $h): ?>
                                <tr class="hover:bg-slate-50 transition">
                                    <td class="p-6 font-black text-lg text-slate-800"><?= $h['month'] ?></td>
                                    <td class="p-6 font-black text-slate-500"><?= $h['year'] ?></td>
                                    <td class="p-6 text-xs text-slate-400 italic font-bold"><?= $h['created_at'] ?></td>
                                    <td class="p-6 text-center">
                                        <span class="bg-slate-100 text-slate-600 px-3 py-1.5 rounded-full text-[10px] font-black uppercase">
                                            <i class="fas fa-lock me-1"></i> CLOSED
                                        </span>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                                <?php if(empty($history)): ?>
                                    <tr>
                                        <td colspan="4" class="p-20 text-center text-slate-300 italic font-bold">
                                            <?= $texts[$lang]['no_data'] ?>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Technical Footer Info -->
                <div class="mt-8 p-6 bg-blue-50 rounded-3xl border border-blue-100 flex items-center gap-4">
                    <div class="w-10 h-10 bg-blue-500 text-white rounded-xl flex items-center justify-center">
                        <i class="fas fa-shield-alt"></i>
                    </div>
                    <div>
                        <p class="text-[11px] font-bold text-blue-800 leading-tight">
                            يستخدم النظام آلية التقييد البرمجي لمنع أي عمليات إدخال (`INSERT`) أو تحديث (`UPDATE`) في جدولي الفواتير والقراءات للشهر المقفل.
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </div>

</body>
</html>