<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);


session_start();
require_once '../config.php';

if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: ../admin_panel.php");
    exit;
}

$stmt = $pdo->prepare("SELECT * FROM admin WHERE id = ?");
$stmt->execute([$_SESSION['admin_id']]);
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

if (isset($_POST['add_plan'])) {
    $name = trim($_POST['name']);
    $panel_id = (int)$_POST['panel_id'];
    $volume_input = (float)$_POST['volume_gb']; // اعشاری
    $days = (int)$_POST['days'];
    $price = (int)$_POST['price'];
    $status = isset($_POST['status']) ? 1 : 0;
    
    // تبدیل حجم اعشاری به گیگابایت مناسب برای دیتابیس
    // اگر عدد کوچک است (مثل 0.5 به معنای 500 مگابایت) همان 0.5 ذخیره می‌شود
    $volume_gb = $volume_input;
    
    $stmt = $pdo->prepare("INSERT INTO plans (name, panel_id, volume_gb, days, price, status) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->execute([$name, $panel_id, $volume_gb, $days, $price, $status]);
    header("Location: plans.php");
    exit;
}

if (isset($_POST['edit_plan'])) {
    $id = (int)$_POST['id'];
    $name = trim($_POST['name']);
    $panel_id = (int)$_POST['panel_id'];
    $volume_input = (float)$_POST['volume_gb'];
    $days = (int)$_POST['days'];
    $price = (int)$_POST['price'];
    $status = isset($_POST['status']) ? 1 : 0;
    
    $volume_gb = $volume_input;
    
    $stmt = $pdo->prepare("UPDATE plans SET name = ?, panel_id = ?, volume_gb = ?, days = ?, price = ?, status = ? WHERE id = ?");
    $stmt->execute([$name, $panel_id, $volume_gb, $days, $price, $status, $id]);
    header("Location: plans.php");
    exit;
}

if (isset($_GET['delete_plan'])) {
    $id = (int)$_GET['delete_plan'];
    $pdo->prepare("DELETE FROM plans WHERE id = ?")->execute([$id]);
    header("Location: plans.php");
    exit;
}

if (isset($_GET['get_plan_json'])) {
    $stmt = $pdo->prepare("SELECT * FROM plans WHERE id = ?");
    $stmt->execute([$_GET['get_plan_json']]);
    header('Content-Type: application/json');
    echo json_encode($stmt->fetch(PDO::FETCH_ASSOC));
    exit;
}

$plans = $pdo->query("SELECT p.*, pnl.name as panel_name FROM plans p LEFT JOIN panels pnl ON p.panel_id = pnl.id ORDER BY p.id DESC")->fetchAll();
$panels = $pdo->query("SELECT id, name FROM panels WHERE status = 1 ORDER BY name")->fetchAll();
?>
<!DOCTYPE html>
<html dir="rtl" lang="fa">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>مدیریت پلن‌ها | رهگذر</title>
    <link rel="stylesheet" href="../style.css">
</head>
<body>
<div class="container">
    <div class="admin-header">
        <div class="brand">
            <img src="../picture/rahgozar.png" alt="مدیریت" class="brand-logo">
            <span class="brand-name">مدیریت پلن‌ها</span>
        </div>
        <div class="admin-info">
            <div class="admin-welcome">خوش آمدید، <strong><?= htmlspecialchars($admin['full_name'] ?? $admin['username']) ?></strong></div>
            <a href="../admin_panel.php" class="logout-btn">بازگشت به داشبورد</a>
            <a href="../admin_panel.php?logout=1" class="logout-btn">خروج</a>
        </div>
    </div>

    <div class="content-card">
        <div class="section-header">
            <div class="section-title">لیست پلن‌ها</div>
            <button class="add-btn" onclick="openAddPlanModal()">+ افزودن پلن</button>
        </div>
        <div class="table-wrapper">
            <table>
                <thead>
                    <tr><th>آیدی</th><th>نام</th><th>پنل</th><th>حجم</th><th>مدت</th><th>قیمت</th><th>وضعیت</th><th>عملیات</th></tr>
                </thead>
                <tbody>
                    <?php foreach($plans as $plan): ?>
                    <tr>
                        <td><?= $plan['id'] ?></td>
                        <td><?= htmlspecialchars($plan['name']) ?></td>
                        <td><?= htmlspecialchars($plan['panel_name'] ?? '-') ?></td>
                        <td>
                            <?php 
                            $vol = $plan['volume_gb'];
                            if ($vol == 0) {
                                echo 'نامحدود';
                            } elseif ($vol < 1) {
                                // نمایش به مگابایت برای اعداد کوچک
                                echo number_format($vol * 1000) . ' MB';
                            } else {
                                echo number_format($vol) . ' GB';
                            }
                            ?>
                        </td>
                        <td><?= $plan['days'] == 0 ? 'نامحدود' : number_format($plan['days']) . ' روز' ?></td>
                        <td><?= number_format($plan['price']) ?> تومان</td>
                        <td><span class="badge <?= $plan['status'] ? 'badge-active' : 'badge-inactive' ?>"><?= $plan['status'] ? 'فعال' : 'غیرفعال' ?></span></td>
                        <td class="action-buttons">
                            <button class="edit-btn" onclick="openEditPlanModal(<?= $plan['id'] ?>)">ویرایش</button>
                            <a href="?delete_plan=<?= $plan['id'] ?>" class="delete-btn" onclick="return confirm('حذف پلن؟')">حذف</a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div id="planModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 id="planModalTitle">افزودن پلن</h3>
            <button class="close-modal" onclick="closeModal('planModal')">×</button>
        </div>
        <form id="planForm" method="POST">
            <input type="hidden" name="id" id="plan_id">
            <div class="form-group"><label>نام پلن</label><input type="text" name="name" id="plan_name" required></div>
            <div class="form-group">
                <label>پنل</label>
                <select name="panel_id" id="plan_panel_id" required>
                    <option value="">انتخاب پنل</option>
                    <?php foreach($panels as $panel): ?>
                        <option value="<?= $panel['id'] ?>"><?= htmlspecialchars($panel['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label>حجم - 0 = نامحدود | مثال: 0.5 = 500 مگابایت ، 0.05 = 50 مگابایت</label>
                <input type="number" step="any" name="volume_gb" id="plan_volume_gb" value="0">
            </div>
            <div class="form-group"><label>مدت (روز) - 0 = نامحدود</label><input type="number" name="days" id="plan_days" value="0"></div>
            <div class="form-group"><label>قیمت (تومان)</label><input type="number" name="price" id="plan_price" required></div>
            <div class="form-group checkbox-group"><input type="checkbox" name="status" id="plan_status" value="1" checked><label>فعال</label></div>
            <div class="form-actions"><button type="submit" class="btn-submit" id="planSubmitBtn">افزودن</button><button type="button" class="btn-cancel" onclick="closeModal('planModal')">انصراف</button></div>
        </form>
    </div>
</div>

<script>
function closeModal(modalId) { document.getElementById(modalId).style.display = 'none'; }
function openAddPlanModal() {
    document.getElementById('planModalTitle').innerHTML = 'افزودن پلن';
    document.getElementById('planForm').reset();
    document.getElementById('plan_id').value = '';
    document.getElementById('plan_status').checked = true;
    let oldInput = document.querySelector('#planForm input[name="add_plan"], #planForm input[name="edit_plan"]');
    if (oldInput) oldInput.remove();
    let input = document.createElement('input');
    input.type = 'hidden'; input.name = 'add_plan'; input.value = '1';
    document.getElementById('planForm').appendChild(input);
    document.getElementById('planModal').style.display = 'flex';
}
function openEditPlanModal(id) {
    fetch('?get_plan_json=' + id).then(r => r.json()).then(plan => {
        document.getElementById('planModalTitle').innerHTML = 'ویرایش پلن';
        document.getElementById('plan_id').value = plan.id;
        document.getElementById('plan_name').value = plan.name;
        document.getElementById('plan_volume_gb').value = plan.volume_gb;
        document.getElementById('plan_days').value = plan.days;
        document.getElementById('plan_price').value = plan.price;
        document.getElementById('plan_status').checked = (plan.status == 1);
        document.getElementById('plan_panel_id').value = plan.panel_id;
        let oldInput = document.querySelector('#planForm input[name="add_plan"], #planForm input[name="edit_plan"]');
        if (oldInput) oldInput.remove();
        let input = document.createElement('input');
        input.type = 'hidden'; input.name = 'edit_plan'; input.value = '1';
        document.getElementById('planForm').appendChild(input);
        document.getElementById('planModal').style.display = 'flex';
    });
}
</script>
</body>
</html>