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

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

$db = getDB();

// Generate license key
function generateLicenseKey() {
    return strtoupper(sprintf('%04X-%04X-%04X-%04X', 
        mt_rand(0, 0xFFFF), mt_rand(0, 0xFFFF), 
        mt_rand(0, 0xFFFF), mt_rand(0, 0xFFFF)
    ));
}

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        if ($_POST['action'] === 'generate') {
            $licenseKey = generateLicenseKey();
            $planType = $_POST['plan_type'];
            $maxDevices = (int)$_POST['max_devices'];
            $duration = (int)$_POST['duration'];
            
            $expiresAt = null;
            if ($planType !== 'lifetime') {
                $expiresAt = date('Y-m-d H:i:s', strtotime("+$duration days"));
            }
            
            $stmt = $db->prepare("INSERT INTO licenses (license_key, plan_type, max_devices, expires_at) VALUES (?, ?, ?, ?)");
            $stmt->execute([$licenseKey, $planType, $maxDevices, $expiresAt]);
        } elseif ($_POST['action'] === 'revoke' && isset($_POST['license_id'])) {
            $stmt = $db->prepare("UPDATE licenses SET status = 'revoked' WHERE id = ?");
            $stmt->execute([(int)$_POST['license_id']]);
        } elseif ($_POST['action'] === 'delete' && isset($_POST['license_id'])) {
            $stmt = $db->prepare("DELETE FROM licenses WHERE id = ?");
            $stmt->execute([(int)$_POST['license_id']]);
        }
        header('Location: licenses.php');
        exit;
    }
}

// Get licenses
$licenses = $db->query("
    SELECT l.*, u.email, u.username,
    (SELECT COUNT(*) FROM license_activations WHERE license_key = l.license_key) as active_devices
    FROM licenses l
    LEFT JOIN users u ON l.user_id = u.id
    ORDER BY l.created_at DESC
")->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>License Management - 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">
                    <h2 class="text-2xl font-bold text-gray-800">License Management</h2>
                </div>
            </header>
            <main class="p-8">
                <!-- Generate License Card -->
                <div class="bg-white rounded-lg shadow p-6 mb-6">
                    <h3 class="text-lg font-semibold mb-4">Generate New License</h3>
                    <form method="POST" class="grid grid-cols-1 md:grid-cols-5 gap-4">
                        <input type="hidden" name="action" value="generate">
                        <select name="plan_type" class="px-4 py-2 border rounded-lg" required>
                            <option value="trial">Trial (7 days)</option>
                            <option value="monthly">Monthly</option>
                            <option value="yearly">Yearly</option>
                            <option value="lifetime">Lifetime</option>
                        </select>
                        <input type="number" name="max_devices" placeholder="Max Devices" value="1" min="1" class="px-4 py-2 border rounded-lg" required>
                        <input type="number" name="duration" placeholder="Days" value="7" min="1" class="px-4 py-2 border rounded-lg" required>
                        <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-2 rounded-lg col-span-2">
                            Generate License Key
                        </button>
                    </form>
                </div>

                <!-- Licenses Table -->
                <div class="bg-white rounded-lg shadow overflow-hidden">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">License Key</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Plan</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">User</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Expires</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="bg-white divide-y divide-gray-200">
                            <?php foreach ($licenses as $license): ?>
                            <tr class="hover:bg-gray-50">
                                <td class="px-6 py-4 font-mono text-sm"><?= htmlspecialchars($license['license_key']) ?></td>
                                <td class="px-6 py-4 text-sm">
                                    <span class="px-2 py-1 text-xs font-semibold rounded-full bg-purple-100 text-purple-800">
                                        <?= ucfirst($license['plan_type']) ?>
                                    </span>
                                </td>
                                <td class="px-6 py-4 text-sm"><?= $license['active_devices'] ?> / <?= $license['max_devices'] ?></td>
                                <td class="px-6 py-4 text-sm">
                                    <?= $license['email'] ? htmlspecialchars($license['email']) : '<span class="text-gray-400">Unassigned</span>' ?>
                                </td>
                                <td class="px-6 py-4 text-sm">
                                    <?= $license['expires_at'] ? date('M d, Y', strtotime($license['expires_at'])) : '<span class="text-green-600">Never</span>' ?>
                                </td>
                                <td class="px-6 py-4">
                                    <?php
                                    $statusColors = [
                                        'active' => 'bg-green-100 text-green-800',
                                        'expired' => 'bg-red-100 text-red-800',
                                        'revoked' => 'bg-gray-100 text-gray-800'
                                    ];
                                    $color = $statusColors[$license['status']] ?? 'bg-gray-100 text-gray-800';
                                    ?>
                                    <span class="px-2 py-1 text-xs font-semibold rounded-full <?= $color ?>">
                                        <?= ucfirst($license['status']) ?>
                                    </span>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="flex gap-2">
                                        <?php if ($license['status'] === 'active'): ?>
                                        <form method="POST" class="inline">
                                            <input type="hidden" name="license_id" value="<?= $license['id'] ?>">
                                            <input type="hidden" name="action" value="revoke">
                                            <button class="px-3 py-1 bg-yellow-100 text-yellow-700 rounded hover:bg-yellow-200 text-xs font-medium">Revoke</button>
                                        </form>
                                        <?php endif; ?>
                                        <form method="POST" class="inline" onsubmit="return confirm('Delete this license?')">
                                            <input type="hidden" name="license_id" value="<?= $license['id'] ?>">
                                            <input type="hidden" name="action" value="delete">
                                            <button class="px-3 py-1 bg-red-100 text-red-700 rounded hover:bg-red-200 text-xs font-medium">Delete</button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php if (empty($licenses)): ?>
                            <tr>
                                <td colspan="7" class="px-6 py-8 text-center text-gray-500">No licenses generated yet</td>
                            </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </main>
        </div>
    </div>
</body>
</html>
