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

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(["status" => "error", "message" => "Only POST allowed"]);
    exit();
}

require_once 'conn.php';

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

$allowed_actions = ['approve', 'reject', 'decline', 'reopen', 'close'];

if (!$id || !in_array($action, $allowed_actions)) {
    echo json_encode(["status" => "error", "message" => "Invalid data"]);
    exit();
}

// Define status mapping
$status_map = [
    "approve" => "approved",
    "reject" => "rejected",
    "decline" => "declined",
    "reopen" => "pending",
    "close" => "closed"
];

$new_status = $status_map[$action];

$stmt = $conn->prepare("UPDATE expenses SET status = ? WHERE id = ?");
if ($stmt->execute([$new_status, $id])) {
    echo json_encode(["status" => "success", "message" => "Status updated to $new_status"]);
} else {
    echo json_encode(["status" => "error", "message" => "Failed to update status"]);
}

$conn->close();
?>
