<?php
session_start();
require_once(__DIR__ . '/../includes/db.php');

/* ===== ADMIN LOGIN CHECK ===== */
if (!isset($_SESSION['admin_id'])) {
    header("Location: adminlogin.php");
    exit;
}

$update_id = (int)($_POST['update_id'] ?? 0);
$action    = $_POST['action'] ?? '';

if ($update_id === 0 || !in_array($action, ['approve','reject'])) {
    die("Invalid request");
}

/* ===== FETCH UPDATE REQUEST ===== */
$stmt = $conn->prepare("
    SELECT user_id, old_plan_id, new_plan_name
    FROM hosting_plan_updates
    WHERE id = ? AND status = 'pending'
");
$stmt->bind_param("i", $update_id);
$stmt->execute();
$req = $stmt->get_result()->fetch_assoc();

if (!$req) {
    die("Request not found");
}

/* ===== IF APPROVED ===== */
if ($action === 'approve') {

    // Renew plan: 1 year from today
    $updatePlan = $conn->prepare("
        UPDATE hosting_plans
        SET
            plan_name = ?,
            activated_at = NOW(),
            expiry_date = DATE_ADD(NOW(), INTERVAL 1 YEAR)
        WHERE id = ?
    ");
    $updatePlan->bind_param("si", $req['new_plan_name'], $req['old_plan_id']);
    $updatePlan->execute();

    // Mark request approved
    $conn->query("
        UPDATE hosting_plan_updates
        SET status='approved'
        WHERE id=$update_id
    ");

}

/* ===== IF REJECTED ===== */
if ($action === 'reject') {
    $conn->query("
        UPDATE hosting_plan_updates
        SET status='rejected'
        WHERE id=$update_id
    ");
}

header("Location: admin-update-plans.php");
exit;
