<?php
require __DIR__ . '/config.php';

header('Content-Type: application/json');

$conn = getDbConnection();
$data = json_decode(file_get_contents("php://input"), true);

if (isset($data['site_id'])) {
    $site_id = intval($data['site_id']);

    // ✅ Step 1: Get the current status of the site
    $stmt = $conn->prepare("SELECT subscription_status FROM sites WHERE site_id = ?");
    $stmt->bind_param("i", $site_id);
    $stmt->execute();
    $stmt->bind_result($current_status);
    $stmt->fetch();
    $stmt->close();

    if ($current_status === null) {
        echo json_encode(["success" => false, "message" => "Site not found"]);
        exit;
    }

    // ✅ Step 2: Flip the status
    $new_status = ($current_status === "Active") ? "Inactive" : "Active";

    // ✅ Step 3: Update database with the new status
    $stmt = $conn->prepare("UPDATE sites SET subscription_status = ? WHERE site_id = ?");
    $stmt->bind_param("si", $new_status, $site_id);

    if ($stmt->execute()) {
        echo json_encode(["success" => true, "message" => "Site updated to $new_status", "new_status" => $new_status]);
    } else {
        echo json_encode(["success" => false, "message" => $stmt->error]);
    }
} else {
    echo json_encode(["success" => false, "message" => "Invalid input"]);
}

$conn->close();
?>
