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

if (!isset($_SESSION['admin_logged_in'])) {
    header('Location: login.php');
    exit;
}

$pdo = getDB();

// Handle package actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        if ($_POST['action'] === 'add' || $_POST['action'] === 'edit') {
            $id = $_POST['id'] ?? null;
            $name = $_POST['name'];
            $plan_type = $_POST['plan_type'];
            $duration_days = $plan_type === 'lifetime' ? null : $_POST['duration_days'];
            $price = $_POST['price'];
            $max_devices = $_POST['max_devices'];
            $features = $_POST['features'];
            $is_active = isset($_POST['is_active']) ? 1 : 0;
            $sort_order = $_POST['sort_order'];

            if ($id) {
                $stmt = $pdo->prepare("UPDATE packages SET name=?, plan_type=?, duration_days=?, price=?, max_devices=?, features=?, is_active=?, sort_order=? WHERE id=?");
                $stmt->execute([$name, $plan_type, $duration_days, $price, $max_devices, $features, $is_active, $sort_order, $id]);
            } else {
                $stmt = $pdo->prepare("INSERT INTO packages (name, plan_type, duration_days, price, max_devices, features, is_active, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$name, $plan_type, $duration_days, $price, $max_devices, $features, $is_active, $sort_order]);
            }
        } elseif ($_POST['action'] === 'delete') {
            $stmt = $pdo->prepare("DELETE FROM packages WHERE id=?");
            $stmt->execute([$_POST['id']]);
        } elseif ($_POST['action'] === 'toggle') {
            $stmt = $pdo->prepare("UPDATE packages SET is_active = NOT is_active WHERE id=?");
            $stmt->execute([$_POST['id']]);
        }
        header('Location: packages.php');
        exit;
    }
}

$packages = $pdo->query("SELECT * FROM packages ORDER BY sort_order, id")->fetchAll();
$payments = $pdo->query("SELECT p.*, u.username, u.email, pkg.name as package_name FROM payments p LEFT JOIN users u ON p.user_id = u.id LEFT JOIN packages pkg ON p.package_id = pkg.id ORDER BY p.created_at DESC LIMIT 50")->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Packages & Pricing - RSecurity Admin</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100">
    <div class="flex h-screen">
        <?php include 'sidebar.php'; ?>
        
        <div class="flex-1 overflow-auto">
            <header class="bg-white shadow-sm">
                <div class="px-8 py-4 flex justify-between items-center">
                    <h2 class="text-2xl font-bold text-gray-800">Packages & Pricing</h2>
                    <button onclick="openAddModal()" class="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700">
                        + Add Package
                    </button>
                </div>
            </header>
            <main class="p-8">

            <!-- Packages Table -->
            <div class="bg-white rounded-lg shadow mb-8">
                <div class="p-6 border-b">
                    <h2 class="text-xl font-semibold">Available Packages</h2>
                </div>
                <table class="w-full">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Name</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Type</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Duration</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Price</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Devices</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y">
                        <?php foreach ($packages as $pkg): ?>
                        <tr>
                            <td class="px-6 py-4"><?= htmlspecialchars($pkg['name']) ?></td>
                            <td class="px-6 py-4">
                                <span class="px-2 py-1 text-xs rounded bg-blue-100 text-blue-800">
                                    <?= strtoupper($pkg['plan_type']) ?>
                                </span>
                            </td>
                            <td class="px-6 py-4"><?= $pkg['duration_days'] ? $pkg['duration_days'] . ' days' : 'Lifetime' ?></td>
                            <td class="px-6 py-4 font-semibold">₹<?= number_format($pkg['price'], 2) ?></td>
                            <td class="px-6 py-4"><?= $pkg['max_devices'] ?></td>
                            <td class="px-6 py-4">
                                <span class="px-2 py-1 text-xs rounded <?= $pkg['is_active'] ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800' ?>">
                                    <?= $pkg['is_active'] ? 'Active' : 'Inactive' ?>
                                </span>
                            </td>
                            <td class="px-6 py-4">
                                <button onclick='editPackage(<?= json_encode($pkg) ?>)' class="text-blue-600 hover:underline mr-3">Edit</button>
                                <form method="POST" class="inline" onsubmit="return confirm('Toggle status?')">
                                    <input type="hidden" name="action" value="toggle">
                                    <input type="hidden" name="id" value="<?= $pkg['id'] ?>">
                                    <button type="submit" class="text-yellow-600 hover:underline mr-3">Toggle</button>
                                </form>
                                <form method="POST" class="inline" onsubmit="return confirm('Delete this package?')">
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="id" value="<?= $pkg['id'] ?>">
                                    <button type="submit" class="text-red-600 hover:underline">Delete</button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <!-- Recent Payments -->
            <div class="bg-white rounded-lg shadow">
                <div class="p-6 border-b">
                    <h2 class="text-xl font-semibold">Recent Payments</h2>
                </div>
                <table class="w-full">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">User</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Package</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Amount</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Payment ID</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Date</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y">
                        <?php foreach ($payments as $payment): ?>
                        <tr>
                            <td class="px-6 py-4">
                                <div class="font-medium"><?= htmlspecialchars($payment['username'] ?? 'N/A') ?></div>
                                <div class="text-sm text-gray-500"><?= htmlspecialchars($payment['email'] ?? 'N/A') ?></div>
                            </td>
                            <td class="px-6 py-4"><?= htmlspecialchars($payment['package_name'] ?? 'N/A') ?></td>
                            <td class="px-6 py-4 font-semibold">₹<?= number_format($payment['amount'], 2) ?></td>
                            <td class="px-6 py-4 text-sm"><?= htmlspecialchars($payment['razorpay_payment_id'] ?? 'Pending') ?></td>
                            <td class="px-6 py-4">
                                <span class="px-2 py-1 text-xs rounded <?= $payment['status'] === 'success' ? 'bg-green-100 text-green-800' : ($payment['status'] === 'failed' ? 'bg-red-100 text-red-800' : 'bg-yellow-100 text-yellow-800') ?>">
                                    <?= strtoupper($payment['status']) ?>
                                </span>
                            </td>
                            <td class="px-6 py-4 text-sm"><?= date('d M Y, h:i A', strtotime($payment['created_at'])) ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            </main>
        </div>
    </div>

    <!-- Add/Edit Modal -->
    <div id="packageModal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center">
        <div class="bg-white rounded-lg p-8 max-w-2xl w-full max-h-screen overflow-y-auto">
            <h2 id="modalTitle" class="text-2xl font-bold mb-4">Add Package</h2>
            <form method="POST">
                <input type="hidden" name="action" id="formAction" value="add">
                <input type="hidden" name="id" id="packageId">
                
                <div class="grid grid-cols-2 gap-4 mb-4">
                    <div>
                        <label class="block text-sm font-medium mb-2">Package Name</label>
                        <input type="text" name="name" id="packageName" required class="w-full border rounded px-3 py-2">
                    </div>
                    <div>
                        <label class="block text-sm font-medium mb-2">Plan Type</label>
                        <select name="plan_type" id="planType" required class="w-full border rounded px-3 py-2" onchange="toggleDuration()">
                            <option value="trial">Trial</option>
                            <option value="monthly">Monthly</option>
                            <option value="yearly">Yearly</option>
                            <option value="lifetime">Lifetime</option>
                        </select>
                    </div>
                </div>

                <div class="grid grid-cols-2 gap-4 mb-4">
                    <div id="durationField">
                        <label class="block text-sm font-medium mb-2">Duration (Days)</label>
                        <input type="number" name="duration_days" id="durationDays" class="w-full border rounded px-3 py-2">
                    </div>
                    <div>
                        <label class="block text-sm font-medium mb-2">Price (₹)</label>
                        <input type="number" step="0.01" name="price" id="price" required class="w-full border rounded px-3 py-2">
                    </div>
                </div>

                <div class="grid grid-cols-2 gap-4 mb-4">
                    <div>
                        <label class="block text-sm font-medium mb-2">Max Devices</label>
                        <input type="number" name="max_devices" id="maxDevices" required class="w-full border rounded px-3 py-2">
                    </div>
                    <div>
                        <label class="block text-sm font-medium mb-2">Sort Order</label>
                        <input type="number" name="sort_order" id="sortOrder" value="0" class="w-full border rounded px-3 py-2">
                    </div>
                </div>

                <div class="mb-4">
                    <label class="block text-sm font-medium mb-2">Features (one per line)</label>
                    <textarea name="features" id="features" rows="4" class="w-full border rounded px-3 py-2"></textarea>
                </div>

                <div class="mb-4">
                    <label class="flex items-center">
                        <input type="checkbox" name="is_active" id="isActive" checked class="mr-2">
                        <span class="text-sm font-medium">Active</span>
                    </label>
                </div>

                <div class="flex justify-end gap-2">
                    <button type="button" onclick="closeModal()" class="px-4 py-2 border rounded hover:bg-gray-100">Cancel</button>
                    <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700">Save</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        function openAddModal() {
            document.getElementById('modalTitle').textContent = 'Add Package';
            document.getElementById('formAction').value = 'add';
            document.getElementById('packageId').value = '';
            document.getElementById('packageName').value = '';
            document.getElementById('planType').value = 'trial';
            document.getElementById('durationDays').value = '';
            document.getElementById('price').value = '';
            document.getElementById('maxDevices').value = '1';
            document.getElementById('sortOrder').value = '0';
            document.getElementById('features').value = '';
            document.getElementById('isActive').checked = true;
            document.getElementById('packageModal').classList.remove('hidden');
            toggleDuration();
        }

        function editPackage(pkg) {
            document.getElementById('modalTitle').textContent = 'Edit Package';
            document.getElementById('formAction').value = 'edit';
            document.getElementById('packageId').value = pkg.id;
            document.getElementById('packageName').value = pkg.name;
            document.getElementById('planType').value = pkg.plan_type;
            document.getElementById('durationDays').value = pkg.duration_days || '';
            document.getElementById('price').value = pkg.price;
            document.getElementById('maxDevices').value = pkg.max_devices;
            document.getElementById('sortOrder').value = pkg.sort_order;
            document.getElementById('features').value = pkg.features || '';
            document.getElementById('isActive').checked = pkg.is_active == 1;
            document.getElementById('packageModal').classList.remove('hidden');
            toggleDuration();
        }

        function closeModal() {
            document.getElementById('packageModal').classList.add('hidden');
        }

        function toggleDuration() {
            const planType = document.getElementById('planType').value;
            const durationField = document.getElementById('durationField');
            if (planType === 'lifetime') {
                durationField.style.display = 'none';
                document.getElementById('durationDays').required = false;
            } else {
                durationField.style.display = 'block';
                document.getElementById('durationDays').required = true;
            }
        }
    </script>
</body>
</html>
