<?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_price' => 'تحديد سعر لشهر جديد',
        'month' => 'الشهر',
        'year' => 'السنة',
        'price_kwh' => 'سعر الكيلوواط (LBP)',
        'price_amp' => 'سعر الأمبير (USD)',
        'fixed_fee' => 'رسم الاشتراك الثابت (LBP)', // تم التعديل لليرة
        'exchange_rate' => 'سعر صرف الدولار (LBP)',
        'save' => 'حفظ وإعتماد الأسعار',
        'history' => 'سجل الأسعار السابقة',
        'actions' => 'العمليات',
        'success' => 'تم حفظ تسعيرة الشهر بنجاح',
        'error_closed' => 'خطأ: هذا الشهر مغلق مالياً ولا يمكن تعديل أسعاره!',
        'home' => 'الرئيسية',
        'closed_status' => 'مغلق مالياً'
    ]
];

// التأكد من وجود الحقول المطلوبة في الجداول
try {
    $pdo->exec("ALTER TABLE `monthly_pricing` MODIFY COLUMN `fixed_fee` DECIMAL(12,2) DEFAULT 0");
    $pdo->exec("ALTER TABLE `monthly_pricing` ADD COLUMN IF NOT EXISTS `fee_per_rated_amp` DECIMAL(10,2) DEFAULT 0 AFTER `fixed_fee` ");
} catch (PDOException $e) {}

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

// جلب الشهر والسنة المحددين للفحص (تلقائياً أو من الفورم)
$m_check = $_GET['m'] ?? ($_POST['month'] ?? date('n'));
$y_check = $_POST['year'] ?? date('Y');

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

// 2. معالجة الحفظ
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_pricing'])) {
    if ($is_month_closed) {
        $error = $texts[$lang]['error_closed'];
    } else {
        $m = $_POST['month'];
        $y = $_POST['year'];
        $pk = $_POST['price_kwh'];
        $pa = $_POST['price_amp'];
        $ff = $_POST['fixed_fee'] ?: 0; // القيمة بالليرة
        $er = $_POST['exchange_rate'];

        try {
            $sql = "INSERT INTO monthly_pricing (month, year, price_kwh, price_amp, fixed_fee, exchange_rate) 
                    VALUES (?, ?, ?, ?, ?, ?) 
                    ON DUPLICATE KEY UPDATE 
                    price_kwh=VALUES(price_kwh), price_amp=VALUES(price_amp), 
                    fixed_fee=VALUES(fixed_fee), exchange_rate=VALUES(exchange_rate)";
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$m, $y, $pk, $pa, $ff, $er]);
            $message = $texts[$lang]['success'];
            
            // سجل الأنشطة
            $pdo->prepare("INSERT INTO audit_log (user_id, action) VALUES (?, ?)")
                ->execute([$_SESSION['user_id'], "Updated prices for $m/$y: kWh=$pk LBP, FixedFee=$ff LBP, Rate=$er"]);
                
        } catch (PDOException $e) {
            $error = "خطأ في القاعدة: " . $e->getMessage();
        }
    }
}

// 3. جلب السجل
$history = $pdo->query("SELECT * FROM monthly_pricing ORDER BY year DESC, month DESC LIMIT 12")->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; }
        .closed-mode { filter: grayscale(0.5); pointer-events: none; opacity: 0.6; }
    </style>
</head>
<body class="pb-12 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 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-amber-500 text-white rounded-2xl flex items-center justify-center text-3xl shadow-xl shadow-amber-100">
                    <i class="fas fa-tags"></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 uppercase italic"><?= $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 animate-pulse flex items-center gap-3">
                <i class="fas fa-check-circle 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 flex items-center gap-3">
                <i class="fas fa-lock text-xl"></i> <?= $error ?>
            </div>
        <?php endif; ?>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <!-- Form Card -->
            <div class="lg:col-span-1">
                <div class="bg-white p-8 rounded-[2.5rem] shadow-sm border border-slate-100 sticky top-8">
                    <div class="flex justify-between items-center mb-8">
                        <h3 class="text-xl font-black text-slate-800 flex items-center gap-2 italic">
                            <i class="fas fa-plus-circle text-amber-500"></i> <?= $texts[$lang]['add_price'] ?>
                        </h3>
                        <?php if($is_month_closed): ?>
                            <span class="bg-rose-100 text-rose-600 px-3 py-1 rounded-full text-[10px] font-black uppercase"><i class="fas fa-lock"></i> مغلق</span>
                        <?php endif; ?>
                    </div>
                    
                    <form method="POST" class="space-y-6 <?= $is_month_closed ? 'closed-mode' : '' ?>">
                        <input type="hidden" name="save_pricing" value="1">
                        
                        <div class="grid grid-cols-2 gap-4">
                            <div>
                                <label class="block text-[10px] font-black text-slate-400 mb-2 uppercase"><?= $texts[$lang]['month'] ?></label>
                                <select name="month" onchange="window.location.href='?m='+this.value" class="w-full p-4 bg-slate-50 rounded-2xl border-none font-bold outline-none">
                                    <?php for($m=1;$m<=12;$m++): ?>
                                        <option value="<?= $m ?>" <?= ($m_check == $m) ? 'selected' : '' ?>><?= $m ?></option>
                                    <?php endfor; ?>
                                </select>
                            </div>
                            <div>
                                <label class="block text-[10px] font-black text-slate-400 mb-2 uppercase"><?= $texts[$lang]['year'] ?></label>
                                <select name="year" class="w-full p-4 bg-slate-50 rounded-2xl border-none font-bold outline-none">
                                    <option value="2025" selected>2025</option>
                                    <option value="2026">2026</option>
                                </select>
                            </div>
                        </div>

                        <!-- الكيلوواط بالليرة -->
                        <div class="p-4 bg-blue-50 rounded-2xl border border-blue-100">
                            <label class="block text-[10px] font-black text-blue-600 mb-2 uppercase"><?= $texts[$lang]['price_kwh'] ?></label>
                            <input type="number" name="price_kwh" required placeholder="مثلاً 45000" class="w-full bg-white p-3 rounded-xl border-none font-black text-blue-600 text-xl text-center outline-none">
                        </div>

                        <!-- الأمبير بالدولار -->
                        <div class="p-4 bg-orange-50 rounded-2xl border border-orange-100">
                            <label class="block text-[10px] font-black text-orange-600 mb-2 uppercase"><?= $texts[$lang]['price_amp'] ?></label>
                            <input type="number" step="0.01" name="price_amp" required placeholder="مثلاً 30.00" class="w-full bg-white p-3 rounded-xl border-none font-black text-orange-600 text-xl text-center outline-none">
                        </div>

                        <!-- الرسم الثابت بالليرة (الجديد) -->
                        <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"><?= $texts[$lang]['fixed_fee'] ?></label>
                            <input type="number" name="fixed_fee" placeholder="مثلاً 500000" class="w-full p-3 bg-white rounded-xl border-none font-black text-emerald-700 text-xl text-center outline-none">
                        </div>

                        <!-- سعر الصرف بالليرة -->
                        <div>
                            <label class="block text-[10px] font-black text-slate-400 mb-2 uppercase"><?= $texts[$lang]['exchange_rate'] ?></label>
                            <input type="number" name="exchange_rate" required placeholder="مثلاً 90000" class="w-full p-4 bg-slate-50 rounded-2xl border-none font-black text-slate-700 text-lg text-center outline-none">
                        </div>

                        <button type="submit" class="w-full p-6 bg-slate-900 text-white rounded-3xl font-black shadow-xl hover:bg-black transition transform active:scale-95 text-lg italic">
                            <?= $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-800 italic"><?= $texts[$lang]['history'] ?></h3>
                    </div>
                    <div class="overflow-x-auto">
                        <table class="w-full text-right font-bold">
                            <thead class="bg-slate-50 text-slate-400 text-[10px] font-black uppercase tracking-[0.2em]">
                                <tr>
                                    <th class="p-6">الفترة</th>
                                    <th class="p-6 text-center">الكيلوواط (L.L)</th>
                                    <th class="p-6 text-center">الثابت (L.L)</th>
                                    <th class="p-6 text-center">الصرف (L.L)</th>
                                    <th class="p-6 text-center">الحالة</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-50">
                                <?php foreach($history as $h): 
                                    $h_m = $h['month']; $h_y = $h['year'];
                                    $check_h = $pdo->prepare("SELECT id FROM closed_months WHERE month = ? AND year = ?");
                                    $check_h->execute([$h_m, $h_y]);
                                    $h_is_closed = (bool)$check_h->fetch();
                                ?>
                                <tr class="hover:bg-amber-50/20 transition group">
                                    <td class="p-6 font-black text-slate-800 text-lg italic"><?= $h['month'] ?> / <?= $h['year'] ?></td>
                                    <td class="p-6 text-center text-blue-600"><?= number_format($h['price_kwh']) ?></td>
                                    <td class="p-6 text-center text-emerald-600"><?= number_format($h['fixed_fee']) ?></td>
                                    <td class="p-6 text-center text-slate-400 italic"><?= number_format($h['exchange_rate']) ?></td>
                                    <td class="p-6 text-center">
                                        <?php if($h_is_closed): ?>
                                            <span class="bg-rose-100 text-rose-600 px-3 py-1 rounded-full text-[9px] font-black uppercase italic"><i class="fas fa-lock"></i> <?= $texts[$lang]['closed_status'] ?></span>
                                        <?php else: ?>
                                            <span class="bg-emerald-100 text-emerald-600 px-3 py-1 rounded-full text-[9px] font-black uppercase italic"><i class="fas fa-unlock"></i> مفتوح</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

</body>
</html>