<?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['country_id'])) {
            $country_id = intval($_GET['country_id']);
            $stmt = mysqli_prepare($conn, "
                SELECT p.*, c.name AS country_name
                FROM ports p
                JOIN countries c ON c.id = p.country_id
                WHERE p.country_id=?
                ORDER BY p.port_name ASC
            ");
            mysqli_stmt_bind_param($stmt, "i", $country_id);
            mysqli_stmt_execute($stmt);
            $res = mysqli_stmt_get_result($stmt);

        } elseif (isset($_GET['id'])) {
            $id = intval($_GET['id']);
            $stmt = mysqli_prepare($conn, "SELECT * FROM ports WHERE id=?");
            mysqli_stmt_bind_param($stmt, "i", $id);
            mysqli_stmt_execute($stmt);
            $res = mysqli_stmt_get_result($stmt);

        } else {
            $stmt = mysqli_prepare($conn, "
                SELECT p.*, c.name AS country_name
                FROM ports p
                JOIN countries c ON c.id = p.country_id
                ORDER BY c.name, p.port_name
            ");
            mysqli_stmt_execute($stmt);
            $res = mysqli_stmt_get_result($stmt);
        }

        $data = [];
        while ($row = mysqli_fetch_assoc($res)) {
            $data[] = $row;
        }

        echo json_encode(["status" => "success", "data" => $data]);
        mysqli_stmt_close($stmt);
        break;

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

        $id = intval($input['id'] ?? 0);
        $country_id = intval($input['country_id'] ?? 0);
        $port_name = sanitize($input['port_name'] ?? '');
        $inspection_fee = floatval($input['inspection_fee'] ?? 0);
        $price_per_m3 = floatval($input['price_per_m3'] ?? 0);
        $status = intval($input['status'] ?? 1);

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

        if ($id > 0) {
            $stmt = mysqli_prepare($conn, "
                UPDATE ports SET
                    country_id=?, port_name=?, inspection_fee=?, price_per_m3=?, status=?
                WHERE id=?
            ");
            mysqli_stmt_bind_param(
                $stmt,
                "isddii",
                $country_id,
                $port_name,
                $inspection_fee,
                $price_per_m3,
                $status,
                $id
            );
            $msg = "Port updated";
        } else {
            $stmt = mysqli_prepare($conn, "
                INSERT INTO ports
                (country_id, port_name, inspection_fee, price_per_m3, status)
                VALUES (?, ?, ?, ?, ?)
            ");
            mysqli_stmt_bind_param(
                $stmt,
                "isddi",
                $country_id,
                $port_name,
                $inspection_fee,
                $price_per_m3,
                $status
            );
            $msg = "Port 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 ports 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);
?>