<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header("Content-Type: application/json; charset=UTF-8");

require_once "../../dbcon.php";

/* -------------------------------
HELPERS
------------------------------- */
function sanitize($data)
{
    global $conn;
    return htmlspecialchars(strip_tags(mysqli_real_escape_string($conn, $data)));
}

$method = $_SERVER["REQUEST_METHOD"];

switch ($method) {

    /* -------------------------------
    GET
    ------------------------------- */
    case "GET":
        if (isset($_GET['id'])) {
            $id = intval($_GET['id']);
            $stmt = mysqli_prepare($conn, "SELECT * FROM countries WHERE id=?");
            mysqli_stmt_bind_param($stmt, "i", $id);
            mysqli_stmt_execute($stmt);
            $res = mysqli_stmt_get_result($stmt);
            echo json_encode(["status" => "success", "data" => mysqli_fetch_assoc($res)]);
            mysqli_stmt_close($stmt);
        } else {
            $res = mysqli_query($conn, "SELECT * FROM countries ORDER BY name ASC");
            $data = [];
            while ($row = mysqli_fetch_assoc($res)) {
                $data[] = $row;
            }
            echo json_encode(["status" => "success", "data" => $data]);
        }
        break;

    /* -------------------------------
    POST (INSERT / UPDATE)
    ------------------------------- */
    case "POST":
    
        // Read JSON body
        $input = json_decode(file_get_contents("php://input"), true);

        $id = intval($input['id'] ?? 0);
        $name = sanitize($input['name'] ?? '');
        $code = sanitize($input['code'] ?? '');
        $status = intval($input['status'] ?? 1);

        if (!$name) {
            echo json_encode(["status" => "error", "message" => "Country name required"]);
            exit;
        }

        if ($id > 0) {
            $stmt = mysqli_prepare($conn, "
            UPDATE countries SET
                name=?, code=?, status=?
            WHERE id=?
        ");
            mysqli_stmt_bind_param($stmt, "ssii", $name, $code, $status, $id);
            $msg = "Country updated";
        } else {
            $stmt = mysqli_prepare($conn, "
            INSERT INTO countries (name, code, status)
            VALUES (?, ?, ?)
        ");
            mysqli_stmt_bind_param($stmt, "ssi", $name, $code, $status);
            $msg = "Country added";
        }

        mysqli_stmt_execute($stmt)
            ? print json_encode(["status" => "success", "message" => $msg])
            : print json_encode(["status" => "error", "message" => "DB error"]);

        mysqli_stmt_close($stmt);
        break;

    /* -------------------------------
    DELETE
    ------------------------------- */
    case "DELETE":
        parse_str(file_get_contents("php://input"), $_DELETE);
        $id = intval($_DELETE['id'] ?? 0);

        $stmt = mysqli_prepare($conn, "DELETE FROM countries WHERE id=?");
        mysqli_stmt_bind_param($stmt, "i", $id);
        mysqli_stmt_execute($stmt);
        mysqli_stmt_close($stmt);

        echo json_encode(["status" => "success"]);
        break;

    case "OPTIONS":
        http_response_code(200);
        break;
}

mysqli_close($conn);
?>