<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech

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

// Check if user is admin
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    header('Location: ../login.php');
    exit();
}

// Verify admin status
$stmt = $pdo->prepare("SELECT is_admin FROM users WHERE id = :user_id");
$stmt->bindParam(':user_id', $_SESSION['user_id'], PDO::PARAM_INT);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user || $user['is_admin'] != 1) {
    header('Location: ../user/dashboard.php');
    exit();
}

// Handle Key Generation
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['generate_keys'])) {
    $plan_id = (int)$_POST['plan_id'];
    $quantity = (int)$_POST['quantity'];
    $notes = trim($_POST['notes']);
    
    if ($quantity < 1 || $quantity > 100) {
        $_SESSION['error'] = "Quantity must be between 1 and 100!";
    } else {
        try {
            $generated_keys = [];
            
            for ($i = 0; $i < $quantity; $i++) {
                // Generate unique key
                $key = strtoupper(substr(md5(uniqid(rand(), true)), 0, 16));
                
                // Insert key
                $stmt = $pdo->prepare("INSERT INTO activation_keys (activation_key, plan_id, status, generated_by, notes) VALUES (?, ?, 'unused', ?, ?)");
                $stmt->execute([$key, $plan_id, $_SESSION['user_id'], $notes]);
                
                $generated_keys[] = $key;
            }
            
            $_SESSION['success'] = count($generated_keys) . " activation key(s) generated successfully!";
            $_SESSION['generated_keys'] = $generated_keys;
            
        } catch(PDOException $e) {
            $_SESSION['error'] = "Error generating keys: " . $e->getMessage();
        }
    }
    
    header('Location: generate-keys.php');
    exit();
}

// Handle Key Deletion
if (isset($_GET['delete_key'])) {
    $key_id = (int)$_GET['delete_key'];
    
    try {
        $stmt = $pdo->prepare("DELETE FROM activation_keys WHERE id = ? AND status = 'unused'");
        $stmt->execute([$key_id]);
        
        if ($stmt->rowCount() > 0) {
            $_SESSION['success'] = "Activation key deleted successfully!";
        } else {
            $_SESSION['error'] = "Cannot delete used or non-existent key!";
        }
    } catch(PDOException $e) {
        $_SESSION['error'] = "Error deleting key!";
    }
    
    header('Location: generate-keys.php');
    exit();
}

// Fetch all plans
$plans = $pdo->query("SELECT * FROM subscription_plans WHERE status = 'active' ORDER BY price ASC")->fetchAll(PDO::FETCH_ASSOC);

// Fetch all keys with pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 20;
$offset = ($page - 1) * $per_page;

$total_keys = $pdo->query("SELECT COUNT(*) FROM activation_keys")->fetchColumn();
$total_pages = ceil($total_keys / $per_page);

$keys = $pdo->query("
    SELECT ak.*, sp.plan_name, sp.price, u.username as activated_by_username
    FROM activation_keys ak
    LEFT JOIN subscription_plans sp ON ak.plan_id = sp.id
    LEFT JOIN users u ON ak.activated_by = u.id
    ORDER BY ak.created_at DESC
    LIMIT $per_page OFFSET $offset
")->fetchAll(PDO::FETCH_ASSOC);

$page_title = WEB_NAME . " | Generate Activation Keys";
?>
<!DOCTYPE html>
<html lang="en" class="light">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <link rel="shortcut icon" type="image/png" href="<?php echo $site_data['web_url']; ?>/public/favicons/favicon.png">
</head>
<body class="bg-gradient-to-br from-slate-50 to-slate-100 min-h-screen p-4 lg:p-8">

<div class="max-w-7xl mx-auto space-y-6">
    
    <!-- Header -->
    <div class="flex items-center justify-between">
        <div>
            <h1 class="text-3xl font-bold text-slate-900">Generate Activation Keys</h1>
            <p class="text-slate-600 mt-1">Create activation keys for subscription plans</p>
        </div>
        <a href="dashboard.php" class="px-4 py-2 bg-slate-200 hover:bg-slate-300 rounded-lg transition-colors">
            <i class="fas fa-arrow-left mr-2"></i>Back to Dashboard
        </a>
    </div>

    <!-- Alert Messages -->
    <?php if (isset($_SESSION['success'])): ?>
        <div class="p-4 bg-green-50 border border-green-200 rounded-lg">
            <div class="flex items-center">
                <i class="fas fa-check-circle text-green-600 mr-3"></i>
                <span class="text-green-800 font-medium"><?php echo $_SESSION['success']; ?></span>
            </div>
        </div>
        <?php unset($_SESSION['success']); ?>
    <?php endif; ?>

    <?php if (isset($_SESSION['error'])): ?>
        <div class="p-4 bg-red-50 border border-red-200 rounded-lg">
            <div class="flex items-center">
                <i class="fas fa-exclamation-circle text-red-600 mr-3"></i>
                <span class="text-red-800 font-medium"><?php echo $_SESSION['error']; ?></span>
            </div>
        </div>
        <?php unset($_SESSION['error']); ?>
    <?php endif; ?>

    <!-- Generated Keys Display -->
    <?php if (isset($_SESSION['generated_keys'])): ?>
        <div class="p-6 bg-blue-50 border border-blue-200 rounded-lg">
            <h3 class="text-lg font-bold text-blue-900 mb-4">
                <i class="fas fa-key mr-2"></i>Generated Keys (Copy & Save):
            </h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-3">
                <?php foreach ($_SESSION['generated_keys'] as $key): ?>
                    <div class="flex items-center justify-between p-3 bg-white rounded-lg border border-blue-200">
                        <code class="text-sm font-mono text-blue-700"><?php echo $key; ?></code>
                        <button onclick="copyToClipboard('<?php echo $key; ?>')" class="px-3 py-1 bg-blue-600 hover:bg-blue-700 text-white rounded transition-colors text-sm">
                            <i class="fas fa-copy"></i>
                        </button>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php unset($_SESSION['generated_keys']); ?>
    <?php endif; ?>

    <!-- Generate Keys Form -->
    <div class="bg-white rounded-2xl shadow-lg p-6">
        <h2 class="text-xl font-bold text-slate-900 mb-6">
            <i class="fas fa-plus-circle text-primary-600 mr-2"></i>Generate New Keys
        </h2>
        
        <form method="POST" action="generate-keys.php" class="space-y-4">
            <input type="hidden" name="generate_keys" value="1">
            
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <!-- Plan Selection -->
                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-2">Subscription Plan</label>
                    <select name="plan_id" required class="w-full px-4 py-3 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                        <option value="">Select Plan</option>
                        <?php foreach ($plans as $plan): ?>
                            <option value="<?php echo $plan['id']; ?>">
                                <?php echo $plan['plan_name']; ?> - <?php echo $plan['currency']; ?> <?php echo number_format($plan['price'], 2); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <!-- Quantity -->
                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-2">Quantity (Max: 100)</label>
                    <input type="number" name="quantity" min="1" max="100" value="1" required 
                           class="w-full px-4 py-3 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                </div>

                <!-- Notes -->
                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-2">Notes (Optional)</label>
                    <input type="text" name="notes" placeholder="e.g., Promo batch"
                           class="w-full px-4 py-3 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                </div>
            </div>

            <button type="submit" class="w-full md:w-auto px-6 py-3 bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white font-semibold rounded-lg transition-all">
                <i class="fas fa-magic mr-2"></i>Generate Keys
            </button>
        </form>
    </div>

    <!-- Keys List -->
    <div class="bg-white rounded-2xl shadow-lg p-6">
        <h2 class="text-xl font-bold text-slate-900 mb-6">
            <i class="fas fa-list text-primary-600 mr-2"></i>All Activation Keys (<?php echo $total_keys; ?>)
        </h2>

        <div class="overflow-x-auto">
            <table class="w-full">
                <thead>
                    <tr class="border-b border-slate-200">
                        <th class="text-left p-3 text-sm font-semibold text-slate-700">Key</th>
                        <th class="text-left p-3 text-sm font-semibold text-slate-700">Plan</th>
                        <th class="text-left p-3 text-sm font-semibold text-slate-700">Status</th>
                        <th class="text-left p-3 text-sm font-semibold text-slate-700">Activated By</th>
                        <th class="text-left p-3 text-sm font-semibold text-slate-700">Notes</th>
                        <th class="text-left p-3 text-sm font-semibold text-slate-700">Created</th>
                        <th class="text-left p-3 text-sm font-semibold text-slate-700">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($keys as $key): ?>
                        <tr class="border-b border-slate-100 hover:bg-slate-50">
                            <td class="p-3">
                                <code class="text-sm font-mono text-blue-600"><?php echo $key['activation_key']; ?></code>
                            </td>
                            <td class="p-3 text-sm"><?php echo $key['plan_name']; ?></td>
                            <td class="p-3">
                                <?php if ($key['status'] == 'unused'): ?>
                                    <span class="px-2 py-1 bg-green-100 text-green-700 rounded text-xs font-semibold">Unused</span>
                                <?php elseif ($key['status'] == 'used'): ?>
                                    <span class="px-2 py-1 bg-blue-100 text-blue-700 rounded text-xs font-semibold">Used</span>
                                <?php else: ?>
                                    <span class="px-2 py-1 bg-red-100 text-red-700 rounded text-xs font-semibold">Expired</span>
                                <?php endif; ?>
                            </td>
                            <td class="p-3 text-sm"><?php echo $key['activated_by_username'] ?: '-'; ?></td>
                            <td class="p-3 text-sm text-slate-600"><?php echo $key['notes'] ?: '-'; ?></td>
                            <td class="p-3 text-sm text-slate-600"><?php echo date('M d, Y', strtotime($key['created_at'])); ?></td>
                            <td class="p-3">
                                <?php if ($key['status'] == 'unused'): ?>
                                    <button onclick="copyToClipboard('<?php echo $key['activation_key']; ?>')" class="px-3 py-1 bg-blue-600 hover:bg-blue-700 text-white rounded text-xs mr-2">
                                        <i class="fas fa-copy"></i>
                                    </button>
                                    <a href="?delete_key=<?php echo $key['id']; ?>" onclick="return confirm('Delete this unused key?')" class="px-3 py-1 bg-red-600 hover:bg-red-700 text-white rounded text-xs">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
            <div class="flex justify-center mt-6 gap-2">
                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                    <a href="?page=<?php echo $i; ?>" class="px-4 py-2 <?php echo $page == $i ? 'bg-blue-600 text-white' : 'bg-slate-200 text-slate-700 hover:bg-slate-300'; ?> rounded transition-colors">
                        <?php echo $i; ?>
                    </a>
                <?php endfor; ?>
            </div>
        <?php endif; ?>
    </div>

</div>

<script>
function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(() => {
        alert('Activation key copied to clipboard!');
    }).catch(err => {
        console.error('Failed to copy:', err);
    });
}
</script>

</body>
</html>