<?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 Plan Creation
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['create_plan'])) {
    $plan_name = trim($_POST['plan_name']);
    $duration_value = (int)$_POST['duration_value'];
    $duration_unit = $_POST['duration_unit'];
    $price = (float)$_POST['price'];
    $currency = trim($_POST['currency']);
    $payment_url = trim($_POST['payment_url']);
    $bulk_sending = isset($_POST['bulk_sending']) ? 1 : 0;
    $explorer = isset($_POST['explorer']) ? 1 : 0;
    $receipt_generator = isset($_POST['receipt_generator']) ? 1 : 0;
    $is_popular = isset($_POST['is_popular']) ? 1 : 0;
    $is_premium = isset($_POST['is_premium']) ? 1 : 0;
    $status = $_POST['status'];
    
    try {
        $stmt = $pdo->prepare("INSERT INTO subscription_plans (plan_name, duration_value, duration_unit, price, currency, payment_url, bulk_sending, explorer, receipt_generator, is_popular, is_premium, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$plan_name, $duration_value, $duration_unit, $price, $currency, $payment_url, $bulk_sending, $explorer, $receipt_generator, $is_popular, $is_premium, $status]);
        
        $_SESSION['success'] = "Subscription plan created successfully!";
    } catch(PDOException $e) {
        $_SESSION['error'] = "Error creating plan: " . $e->getMessage();
    }
    
    header('Location: manage-plans.php');
    exit();
}

// Handle Plan Update
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_plan'])) {
    $plan_id = (int)$_POST['plan_id'];
    $plan_name = trim($_POST['plan_name']);
    $duration_value = (int)$_POST['duration_value'];
    $duration_unit = $_POST['duration_unit'];
    $price = (float)$_POST['price'];
    $currency = trim($_POST['currency']);
    $payment_url = trim($_POST['payment_url']);
    $bulk_sending = isset($_POST['bulk_sending']) ? 1 : 0;
    $explorer = isset($_POST['explorer']) ? 1 : 0;
    $receipt_generator = isset($_POST['receipt_generator']) ? 1 : 0;
    $is_popular = isset($_POST['is_popular']) ? 1 : 0;
    $is_premium = isset($_POST['is_premium']) ? 1 : 0;
    $status = $_POST['status'];
    
    try {
        $stmt = $pdo->prepare("UPDATE subscription_plans SET plan_name = ?, duration_value = ?, duration_unit = ?, price = ?, currency = ?, payment_url = ?, bulk_sending = ?, explorer = ?, receipt_generator = ?, is_popular = ?, is_premium = ?, status = ? WHERE id = ?");
        $stmt->execute([$plan_name, $duration_value, $duration_unit, $price, $currency, $payment_url, $bulk_sending, $explorer, $receipt_generator, $is_popular, $is_premium, $status, $plan_id]);
        
        $_SESSION['success'] = "Subscription plan updated successfully!";
    } catch(PDOException $e) {
        $_SESSION['error'] = "Error updating plan: " . $e->getMessage();
    }
    
    header('Location: manage-plans.php');
    exit();
}

// Handle Plan Deletion
if (isset($_GET['delete_plan'])) {
    $plan_id = (int)$_GET['delete_plan'];
    
    try {
        // Check if plan has any activation keys
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM activation_keys WHERE plan_id = ?");
        $stmt->execute([$plan_id]);
        $key_count = $stmt->fetchColumn();
        
        if ($key_count > 0) {
            $_SESSION['error'] = "Cannot delete plan with existing activation keys!";
        } else {
            $stmt = $pdo->prepare("DELETE FROM subscription_plans WHERE id = ?");
            $stmt->execute([$plan_id]);
            $_SESSION['success'] = "Subscription plan deleted successfully!";
        }
    } catch(PDOException $e) {
        $_SESSION['error'] = "Error deleting plan!";
    }
    
    header('Location: manage-plans.php');
    exit();
}

// Fetch plan for editing
$edit_plan = null;
if (isset($_GET['edit'])) {
    $edit_id = (int)$_GET['edit'];
    $stmt = $pdo->prepare("SELECT * FROM subscription_plans WHERE id = ?");
    $stmt->execute([$edit_id]);
    $edit_plan = $stmt->fetch(PDO::FETCH_ASSOC);
}

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

$page_title = WEB_NAME . " | Manage Subscription Plans";
?>
<!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">Manage Subscription Plans</h1>
            <p class="text-slate-600 mt-1">Create, edit, and manage 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; ?>

    <!-- Create/Edit Plan 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-<?php echo $edit_plan ? 'edit' : 'plus-circle'; ?> text-blue-600 mr-2"></i>
            <?php echo $edit_plan ? 'Edit Plan' : 'Create New Plan'; ?>
        </h2>
        
        <form method="POST" action="manage-plans.php" class="space-y-6">
            <?php if ($edit_plan): ?>
                <input type="hidden" name="update_plan" value="1">
                <input type="hidden" name="plan_id" value="<?php echo $edit_plan['id']; ?>">
            <?php else: ?>
                <input type="hidden" name="create_plan" value="1">
            <?php endif; ?>
            
            <!-- Basic Information -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-2">Plan Name *</label>
                    <input type="text" name="plan_name" value="<?php echo $edit_plan['plan_name'] ?? ''; ?>" required 
                           placeholder="e.g., Monthly Plan"
                           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>
                    <label class="block text-sm font-semibold text-slate-700 mb-2">Status *</label>
                    <select name="status" 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="active" <?php echo ($edit_plan['status'] ?? 'active') == 'active' ? 'selected' : ''; ?>>Active</option>
                        <option value="inactive" <?php echo ($edit_plan['status'] ?? '') == 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                    </select>
                </div>
            </div>

            <!-- Duration -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-2">Duration Value *</label>
                    <input type="number" name="duration_value" value="<?php echo $edit_plan['duration_value'] ?? '1'; ?>" min="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>

                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-2">Duration Unit *</label>
                    <select name="duration_unit" 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="day" <?php echo ($edit_plan['duration_unit'] ?? '') == 'day' ? 'selected' : ''; ?>>Day(s)</option>
                        <option value="week" <?php echo ($edit_plan['duration_unit'] ?? '') == 'week' ? 'selected' : ''; ?>>Week(s)</option>
                        <option value="month" <?php echo ($edit_plan['duration_unit'] ?? 'month') == 'month' ? 'selected' : ''; ?>>Month(s)</option>
                        <option value="year" <?php echo ($edit_plan['duration_unit'] ?? '') == 'year' ? 'selected' : ''; ?>>Year(s)</option>
                    </select>
                </div>
            </div>

            <!-- Pricing -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-2">Price *</label>
                    <input type="number" name="price" value="<?php echo $edit_plan['price'] ?? '0'; ?>" step="0.01" min="0" 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>

                <div>
                    <label class="block text-sm font-semibold text-slate-700 mb-2">Currency *</label>
                    <input type="text" name="currency" value="<?php echo $edit_plan['currency'] ?? 'NGN'; ?>" required 
                           placeholder="e.g., NGN, USD"
                           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>

            <!-- Payment URL -->
            <div>
                <label class="block text-sm font-semibold text-slate-700 mb-2">Payment URL</label>
                <input type="url" name="payment_url" value="<?php echo $edit_plan['payment_url'] ?? ''; ?>" 
                       placeholder="https://pay.example.com/checkout"
                       class="w-full px-4 py-3 border border-slate-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
            </div>

            <!-- Features -->
            <div>
                <label class="block text-sm font-semibold text-slate-700 mb-3">Features</label>
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <label class="flex items-center p-3 border border-slate-300 rounded-lg cursor-pointer hover:bg-slate-50">
                        <input type="checkbox" name="bulk_sending" <?php echo ($edit_plan['bulk_sending'] ?? 0) ? 'checked' : ''; ?> class="mr-3">
                        <span class="text-sm text-slate-700">Bulk Sending</span>
                    </label>
                    <label class="flex items-center p-3 border border-slate-300 rounded-lg cursor-pointer hover:bg-slate-50">
                        <input type="checkbox" name="explorer" <?php echo ($edit_plan['explorer'] ?? 1) ? 'checked' : ''; ?> class="mr-3">
                        <span class="text-sm text-slate-700">Explorer</span>
                    </label>
                    <label class="flex items-center p-3 border border-slate-300 rounded-lg cursor-pointer hover:bg-slate-50">
                        <input type="checkbox" name="receipt_generator" <?php echo ($edit_plan['receipt_generator'] ?? 1) ? 'checked' : ''; ?> class="mr-3">
                        <span class="text-sm text-slate-700">Receipt Generator</span>
                    </label>
                </div>
            </div>

            <!-- Display Options -->
            <div>
                <label class="block text-sm font-semibold text-slate-700 mb-3">Display Options</label>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <label class="flex items-center p-3 border border-slate-300 rounded-lg cursor-pointer hover:bg-slate-50">
                        <input type="checkbox" name="is_popular" <?php echo ($edit_plan['is_popular'] ?? 0) ? 'checked' : ''; ?> class="mr-3">
                        <span class="text-sm text-slate-700">Mark as Popular</span>
                    </label>
                    <label class="flex items-center p-3 border border-slate-300 rounded-lg cursor-pointer hover:bg-slate-50">
                        <input type="checkbox" name="is_premium" <?php echo ($edit_plan['is_premium'] ?? 0) ? 'checked' : ''; ?> class="mr-3">
                        <span class="text-sm text-slate-700">Mark as Premium</span>
                    </label>
                </div>
            </div>

            <!-- Buttons -->
            <div class="flex gap-3">
                <button type="submit" class="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-save mr-2"></i><?php echo $edit_plan ? 'Update Plan' : 'Create Plan'; ?>
                </button>
                <?php if ($edit_plan): ?>
                    <a href="manage-plans.php" class="px-6 py-3 bg-slate-200 hover:bg-slate-300 text-slate-700 font-semibold rounded-lg transition-colors">
                        <i class="fas fa-times mr-2"></i>Cancel
                    </a>
                <?php endif; ?>
            </div>
        </form>
    </div>

    <!-- Plans 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-blue-600 mr-2"></i>All Subscription Plans (<?php echo count($plans); ?>)
        </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">Plan Name</th>
                        <th class="text-left p-3 text-sm font-semibold text-slate-700">Duration</th>
                        <th class="text-left p-3 text-sm font-semibold text-slate-700">Price</th>
                        <th class="text-left p-3 text-sm font-semibold text-slate-700">Features</th>
                        <th class="text-left p-3 text-sm font-semibold text-slate-700">Badges</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">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($plans as $plan): ?>
                        <tr class="border-b border-slate-100 hover:bg-slate-50">
                            <td class="p-3 font-semibold text-slate-900"><?php echo $plan['plan_name']; ?></td>
                            <td class="p-3 text-sm text-slate-600"><?php echo $plan['duration_value']; ?> <?php echo $plan['duration_unit']; ?>(s)</td>
                            <td class="p-3 text-sm font-semibold text-blue-600"><?php echo $plan['currency']; ?> <?php echo number_format($plan['price'], 2); ?></td>
                            <td class="p-3 text-xs">
                                <div class="flex flex-wrap gap-1">
                                    <?php if ($plan['bulk_sending']): ?>
                                        <span class="px-2 py-1 bg-purple-100 text-purple-700 rounded">Bulk</span>
                                    <?php endif; ?>
                                    <?php if ($plan['explorer']): ?>
                                        <span class="px-2 py-1 bg-blue-100 text-blue-700 rounded">Explorer</span>
                                    <?php endif; ?>
                                    <?php if ($plan['receipt_generator']): ?>
                                        <span class="px-2 py-1 bg-green-100 text-green-700 rounded">Receipt</span>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td class="p-3 text-xs">
                                <div class="flex flex-wrap gap-1">
                                    <?php if ($plan['is_popular']): ?>
                                        <span class="px-2 py-1 bg-orange-100 text-orange-700 rounded font-semibold">Popular</span>
                                    <?php endif; ?>
                                    <?php if ($plan['is_premium']): ?>
                                        <span class="px-2 py-1 bg-yellow-100 text-yellow-700 rounded font-semibold">Premium</span>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td class="p-3">
                                <?php if ($plan['status'] == 'active'): ?>
                                    <span class="px-2 py-1 bg-green-100 text-green-700 rounded text-xs font-semibold">Active</span>
                                <?php else: ?>
                                    <span class="px-2 py-1 bg-red-100 text-red-700 rounded text-xs font-semibold">Inactive</span>
                                <?php endif; ?>
                            </td>
                            <td class="p-3">
                                <div class="flex gap-2">
                                    <a href="?edit=<?php echo $plan['id']; ?>" class="px-3 py-1 bg-blue-600 hover:bg-blue-700 text-white rounded text-xs">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <a href="?delete_plan=<?php echo $plan['id']; ?>" onclick="return confirm('Are you sure you want to delete this plan?')" class="px-3 py-1 bg-red-600 hover:bg-red-700 text-white rounded text-xs">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

</div>

</body>
</html>