<?php
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';

if (!empty($origin)) {
    header("Access-Control-Allow-Origin: $origin");
    header("Access-Control-Allow-Credentials: true");
} else {
    header("Access-Control-Allow-Origin: *");
}

header('Content-Type: application/json');
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header('Access-Control-Max-Age: 1728000');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

include_once __DIR__ . '/unified_config.php';
include_once __DIR__ . '/connection.php';

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

$user_id = $data['user_id'] ?? 0;
$action = $data['action'] ?? ''; // 'verify' or 'unverify'

if (!$user_id || !in_array($action, ['verify', 'unverify'])) {
    echo json_encode(["success" => false, "error" => "Invalid input"]);
    exit;
}

// Determine email_confirmed value
$email_confirmed = ($action === 'verify') ? 1 : 0;

// Update loginusers table
$stmt = $conn->prepare("UPDATE loginusers SET email_confirmed = ? WHERE id = ?");
$stmt->bind_param("ii", $email_confirmed, $user_id);

if ($stmt->execute()) {
    echo json_encode([
        "success" => true,
        "message" => "Email " . ($email_confirmed ? "verified" : "unverified") . " successfully"
    ]);
} else {
    echo json_encode(["success" => false, "error" => "Failed to update email: " . $stmt->error]);
}
$stmt->close();
?>
