<?php
// /admin/subscriptions.php
$page_title = "Manage Subscription Plans";
require_once 'includes/header.php';

$errors = [];
$success_message = '';
$edit_mode = false;
$plan_to_edit = ['id' => '', 'name' => '', 'price_ngn' => '', 'duration_days' => '', 'ad_limit' => '', 'description' => '', 'promotion_type' => ''];

// --- Handle Deletion ---
if (isset($_POST['delete_plan_id'])) {
    $plan_id = (int)$_POST['delete_plan_id'];
    // You might want to add a check here to see if any users are currently subscribed to this plan
    $stmt_delete = $conn->prepare("DELETE FROM subscriptions WHERE id = ?");
    $stmt_delete->bind_param("i", $plan_id);
    if ($stmt_delete->execute()) {
        $success_message = "Subscription plan deleted successfully.";
    } else {
        $errors[] = "Failed to delete subscription plan.";
    }
    $stmt_delete->close();
}

// --- Handle Add/Update ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_plan'])) {
    $plan_id = (int)$_POST['plan_id'];
    $name = trim($_POST['name']);
    $price = filter_var($_POST['price_ngn'], FILTER_VALIDATE_FLOAT);
    $duration = filter_var($_POST['duration_days'], FILTER_VALIDATE_INT);
    $ad_limit = filter_var($_POST['ad_limit'], FILTER_VALIDATE_INT);
    $description = trim($_POST['description']);
    $promotion_type = $_POST['promotion_type'];

    if (empty($name)) $errors[] = "Plan name is required.";
    if ($price === false || $price < 0) $errors[] = "Invalid price.";
    if ($duration === false || $duration <= 0) $errors[] = "Duration must be a positive number of days.";
    if ($ad_limit === false || $ad_limit < 0) $errors[] = "Ad limit must be a non-negative number.";
    if (empty($promotion_type) || !in_array($promotion_type, ['related', 'category', 'listing', 'everywhere'])) {
        $errors[] = "A valid promotion type is required.";
    }

    if (empty($errors)) {
        if ($plan_id > 0) { // Update
            $stmt = $conn->prepare("UPDATE subscriptions SET name = ?, price_ngn = ?, duration_days = ?, ad_limit = ?, description = ?, promotion_type = ? WHERE id = ?");
            $stmt->bind_param("sdiissi", $name, $price, $duration, $ad_limit, $description, $promotion_type, $plan_id);
            if ($stmt->execute()) {
                $success_message = "Plan updated successfully.";
            } else {
                $errors[] = "Failed to update plan.";
            }
        } else { // Add
            $stmt = $conn->prepare("INSERT INTO subscriptions (name, price_ngn, duration_days, ad_limit, description, promotion_type) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("sdiiss", $name, $price, $duration, $ad_limit, $description, $promotion_type);
            if ($stmt->execute()) {
                $success_message = "Plan added successfully.";
            } else {
                $errors[] = "Failed to add plan.";
            }
        }
        $stmt->close();
    }
}


// --- Handle Edit Request ---
if (isset($_GET['edit_id'])) {
    $edit_id = (int)$_GET['edit_id'];
    $stmt = $conn->prepare("SELECT * FROM subscriptions WHERE id = ?");
    $stmt->bind_param("i", $edit_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $plan_to_edit = $result->fetch_assoc();
        $edit_mode = true;
    }
    $stmt->close();
}

// --- Fetch all plans for display ---
$plans_result = $conn->query("SELECT * FROM subscriptions ORDER BY price_ngn ASC");
$plans = $plans_result->fetch_all(MYSQLI_ASSOC);
?>

<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
    <div class="lg:col-span-1">
        <div class="bg-white p-6 rounded-lg shadow-md">
            <h2 class="text-xl font-bold mb-4"><?php echo $edit_mode ? 'Edit Plan' : 'Add New Plan'; ?></h2>
            
            <form action="/admin/subscriptions.php" method="POST" class="space-y-4">
                <input type="hidden" name="plan_id" value="<?php echo escape($plan_to_edit['id']); ?>">
                <div>
                    <label for="name" class="block text-sm font-medium text-gray-700">Plan Name</label>
                    <input type="text" name="name" id="name" value="<?php echo escape($plan_to_edit['name']); ?>" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm" required>
                </div>
                <div>
                    <label for="price_ngn" class="block text-sm font-medium text-gray-700">Price (₦)</label>
                    <input type="number" name="price_ngn" id="price_ngn" step="0.01" value="<?php echo escape($plan_to_edit['price_ngn']); ?>" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm" required>
                </div>
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label for="duration_days" class="block text-sm font-medium text-gray-700">Duration (Days)</label>
                        <input type="number" name="duration_days" id="duration_days" value="<?php echo escape($plan_to_edit['duration_days']); ?>" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm" required>
                    </div>
                    <div>
                        <label for="ad_limit" class="block text-sm font-medium text-gray-700">Ad Limit</label>
                        <input type="number" name="ad_limit" id="ad_limit" value="<?php echo escape($plan_to_edit['ad_limit']); ?>" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm" required>
                    </div>
                </div>
                <div>
                    <label for="description" class="block text-sm font-medium text-gray-700">Description</label>
                    <textarea name="description" id="description" rows="3" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm"><?php echo escape($plan_to_edit['description']); ?></textarea>
                </div>
                 <div>
                    <label for="promotion_type" class="block text-sm font-medium text-gray-700">Promotion Type</label>
                    <select name="promotion_type" id="promotion_type" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm" required>
                        <option value="">Select Promotion Type</option>
                        <option value="related" <?php echo ($plan_to_edit['promotion_type'] == 'related') ? 'selected' : ''; ?>>Related Ads Promotion</option>
                        <option value="category" <?php echo ($plan_to_edit['promotion_type'] == 'category') ? 'selected' : ''; ?>>Category Boosting</option>
                        <option value="listing" <?php echo ($plan_to_edit['promotion_type'] == 'listing') ? 'selected' : ''; ?>>Listing Page Boosting</option>
                        <option value="everywhere" <?php echo ($plan_to_edit['promotion_type'] == 'everywhere') ? 'selected' : ''; ?>>Home page promotion</option>
                    </select>
                </div>
                <div class="flex items-center space-x-4 pt-2">
                    <button type="submit" name="submit_plan" class="w-full bg-blue-600 text-white font-semibold py-2 px-4 rounded-lg hover:bg-blue-700">
                        <?php echo $edit_mode ? 'Update Plan' : 'Add Plan'; ?>
                    </button>
                    <?php if ($edit_mode): ?>
                    <a href="/admin/subscriptions.php" class="w-full text-center bg-gray-200 text-gray-800 font-semibold py-2 px-4 rounded-lg hover:bg-gray-300">Cancel</a>
                    <?php endif; ?>
                </div>
            </form>
        </div>
    </div>

    <div class="lg:col-span-2">
        <div class="bg-white p-6 rounded-lg shadow-md">
            <h2 class="text-xl font-bold mb-4">Existing Subscription Plans</h2>
            
            <?php if (!empty($errors)): ?>
                <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4" role="alert"><ul class="list-disc list-inside"><?php foreach ($errors as $error): ?><li><?php echo escape($error); ?></li><?php endforeach; ?></ul></div>
            <?php endif; ?>
            <?php if ($success_message): ?>
                <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative mb-4" role="alert"><?php echo escape($success_message); ?></div>
            <?php endif; ?>

            <div class="overflow-x-auto">
                <table class="min-w-full bg-white">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="text-left py-2 px-3">Plan Name</th>
                            <th class="text-right py-2 px-3">Price</th>
                            <th class="text-center py-2 px-3">Duration</th>
                            <th class="text-center py-2 px-3">Ad Limit</th>
                            <th class="text-center py-2 px-3">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($plans as $plan): ?>
                        <tr class="border-b hover:bg-gray-50">
                            <td class="py-2 px-3 font-medium"><?php echo escape($plan['name']); ?></td>
                            <td class="py-2 px-3 text-right font-semibold text-green-600">₦<?php echo number_format($plan['price_ngn'], 2); ?></td>
                            <td class="py-2 px-3 text-center"><?php echo escape($plan['duration_days']); ?> days</td>
                            <td class="py-2 px-3 text-center"><?php echo escape($plan['ad_limit']); ?></td>
                            <td class="py-2 px-3">
                                <div class="flex items-center justify-center space-x-2">
                                    <a href="?edit_id=<?php echo $plan['id']; ?>" class="text-blue-500 hover:text-blue-700 p-1"><i data-lucide="edit" class="w-4 h-4"></i></a>
                                    <form action="/admin/subscriptions.php" method="POST" onsubmit="return confirm('Are you sure you want to delete this plan?');">
                                        <input type="hidden" name="delete_plan_id" value="<?php echo $plan['id']; ?>">
                                        <button type="submit" class="text-red-500 hover:text-red-700 p-1"><i data-lucide="trash-2" class="w-4 h-4"></i></button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                         <?php if (empty($plans)): ?>
                            <tr><td colspan="5" class="text-center py-10 text-gray-500">No subscription plans have been created yet.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php
require_once 'includes/footer.php';
?>