<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit;

ini_set("display_errors", 1);
ini_set("display_startup_errors", 1);
error_reporting(E_ALL);

include_once __DIR__ . "/config.php";
include_once __DIR__ . "/connection.php";

// Read input
$input = json_decode(file_get_contents("php://input"), true);
$id = $input['id'] ?? null;

if (!$id) {
    echo json_encode(["success" => false, "message" => "Reward ID is required"]);
    exit;
}

try {
    // Fetch reward details
    $stmt = $conn->prepare("SELECT * FROM lots_reward_users WHERE id = ? LIMIT 1");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $reward = $stmt->get_result()->fetch_assoc();
    if (!$reward) throw new Exception("Reward not found");

    $account_type_name = $reward['account_type'];
    $amount = (float)$reward['reward_amount'];

    // Check if Cent account
    $stmt_ac = $conn->prepare("SELECT ac_name FROM account_types WHERE ac_name = ?");
    $stmt_ac->bind_param("s", $account_type_name);
    $stmt_ac->execute();
    $ac_result = $stmt_ac->get_result()->fetch_assoc();
    $is_cent = ($ac_result['ac_name'] === 'Cent');

    $cancel_amount = $is_cent ? $amount : $amount;

    // Cancel reward in DB
    $stmt2 = $conn->prepare("UPDATE lots_reward_users SET reward_amount = 0 WHERE id = ?");
    $stmt2->bind_param("i", $id);
    $stmt2->execute();

    // Insert log
    $stmt_log = $conn->prepare("INSERT INTO lots_reward_logs (reward_id, user_email, account_name, account_type, action, amount) VALUES (?, ?, ?, ?, 'cancel', ?)");
    $stmt_log->bind_param("isssd", $id, $reward['user_email'], $reward['account_name'], $account_type_name, $cancel_amount);
    $stmt_log->execute();

    echo json_encode([
        "success" => true,
        "message" => "Reward canceled successfully",
        "reward_id" => $id
    ]);

} catch (Throwable $e) {
    echo json_encode([
        "success" => false,
        "message" => $e->getMessage()
    ]);
}
?>
