<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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");

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

// ---------------------
// HELPER FUNCTIONS
// ---------------------
function clean($data)
{
    global $conn;
    return htmlspecialchars(strip_tags(mysqli_real_escape_string($conn, $data)));
}

function getProfessionalNote($field, $value = null)
{
    switch ($field) {
        case 'payment_status':
            return "Payment marked as " . strtoupper($value);
        case 'inspection_done':
            return $value ? "Inspection completed" : "Inspection marked as pending";
        case 'shipment_booked':
            return $value ? "Shipment booked successfully" : "Shipment booking pending";
        case 'documents_issued':
            return $value ? "Documents issued successfully" : "Documents issuance pending";
        case 'status':
            return "Order status changed to " . strtoupper($value);
        case 'order_created':
            return "Order created successfully";
        default:
            return ucfirst(str_replace("_", " ", $field)) . " updated";
    }
}

function addHistory($order_id, $status, $changed_by, $note = "")
{
    global $conn;
    $order_id = clean($order_id);
    $status = clean($status);
    $changed_by = clean($changed_by);
    $note = clean($note);
    $q = "INSERT INTO order_history (order_id, status, changed_by, note)
          VALUES ('$order_id', '$status', '$changed_by', '$note')";
    mysqli_query($conn, $q);
}

// ---------------------
// AUTO-CANCEL ORDERS > 48H
// ---------------------
$autoCancelQuery = "SELECT o.id, o.car_id
                    FROM orders o
                    WHERE (o.status='pending' OR o.payment_status='pending')
                      AND TIMESTAMPDIFF(HOUR, o.created_at, NOW()) >= 48";

$res = mysqli_query($conn, $autoCancelQuery);
while ($order = mysqli_fetch_assoc($res)) {
    $order_id = $order['id'];
    $car_id = $order['car_id'];
    mysqli_query($conn, "UPDATE orders SET status='cancelled', payment_status='pending' WHERE id='$order_id'");
    mysqli_query($conn, "UPDATE cars SET status='available' WHERE id='$car_id'");
    $note = "Order automatically cancelled as payment not completed or status not approved within 48 hours.";
    addHistory($order_id, 'cancelled', 2, $note);
}

// ---------------------
// REQUEST METHOD
// ---------------------
$method = $_SERVER["REQUEST_METHOD"];

// ---------------------
// CREATE ORDER
// ---------------------
if ($method === "POST" && isset($_GET["create"])) {
    $data = json_decode(file_get_contents("php://input"), true);

    $required = ["order_number", "user_id", "car_id", "country_id", "port_id"];
    foreach ($required as $field) {
        if (empty($data[$field])) {
            echo json_encode(["status" => "error", "message" => "$field is required"]);
            exit;
        }
    }

    $order_number = clean($data["order_number"]);
    $user_id = clean($data["user_id"]);
    $car_id = clean($data["car_id"]);
    $country_id = clean($data["country_id"]);
    $port_id = clean($data["port_id"]);

    $inspection_fee = isset($data["inspection_fee"]) ? floatval($data["inspection_fee"]) : 0;
    $price_per_m3 = isset($data["price_per_m3"]) ? floatval($data["price_per_m3"]) : 0;

    // ---------------------
    // CHECK RESERVATION LIMIT
    // ---------------------
    // Count active orders (not completed, cancelled, or returned)
    $limit_check_q = "SELECT COUNT(*) as active_count FROM orders 
                      WHERE user_id='$user_id' 
                      AND status NOT IN ('completed', 'cancelled', 'returned')";
    $limit_res = mysqli_query($conn, $limit_check_q);
    $limit_data = mysqli_fetch_assoc($limit_res);
    
    if ($limit_data['active_count'] >= 2) {
        echo json_encode(["status" => "error", "message" => "You can only reserve 2 vehicles at a time. Please complete a purchase to reserve another one."]);
        exit;
    }

    // Get car details
    $res_car = mysqli_query($conn, "SELECT price, m3, status FROM cars WHERE id='$car_id'");
    if (mysqli_num_rows($res_car) === 0) {
        echo json_encode(["status" => "error", "message" => "Car not found"]);
        exit;
    }
    $car = mysqli_fetch_assoc($res_car);
    if ($car['status'] !== 'available') {
        echo json_encode(["status" => "error", "message" => "Car is already reserved or sold"]);
        exit;
    }

    $total_amount = floatval($car['price']) + $inspection_fee + ($price_per_m3 * floatval($car['m3']));

    $q = "INSERT INTO orders 
          (order_number, user_id, car_id, country_id, port_id, total_amount, inspection_done, shipment_booked, documents_issued)
          VALUES
          ('$order_number', '$user_id', '$car_id', '$country_id', '$port_id', '$total_amount', 0, 0, 0)";
    if (!mysqli_query($conn, $q)) {
        echo json_encode(["status" => "error", "message" => mysqli_error($conn)]);
        exit;
    }

    $order_id = mysqli_insert_id($conn);

    mysqli_query($conn, "UPDATE cars SET status='pending' WHERE id='$car_id'");

    addHistory($order_id, "order_created", $user_id, getProfessionalNote('order_created'));

    // ---------------------
    // NOTIFY ADMINS & AGENT
    // ---------------------
    $car_name = $car['car_name'] ?? 'A vehicle'; // Use car_name from res_car or just car
    $notif_title = "New Reservation: " . $order_number;
    $notif_msg = "A new vehicle has been reserved by user (ID: $user_id). Order #$order_number.";
    
    // 1. Notify Super Admins via target_role
    mysqli_query($conn, "INSERT INTO notifications (title, message, type, target_role) VALUES ('$notif_title', '$notif_msg', 'success', 'super_admin')");

    // 2. Notify Assigned Agent (if any)
    $user_q = mysqli_query($conn, "SELECT agent_id FROM users WHERE id='$user_id'");
    $user_data = mysqli_fetch_assoc($user_q);
    if ($user_data && $user_data['agent_id']) {
        $agent_id = $user_data['agent_id'];
        mysqli_query($conn, "INSERT INTO notifications (user_id, title, message, type) VALUES ('$agent_id', '$notif_title', '$notif_msg', 'success')");
    }

    echo json_encode(["status" => "success", "message" => "Order created successfully", "order_id" => $order_id, "total_amount" => $total_amount]);
    exit;
}

// ---------------------
// GET ALL ORDERS
// ---------------------
    $agent_id = isset($_GET['agent_id']) ? intval($_GET['agent_id']) : null;
    $where = "";
    if ($agent_id) {
        $where = " WHERE u.agent_id = $agent_id ";
    }

    $q = "SELECT o.*, 
                 u.full_name AS user_name, 
                 c.name AS car_name, c.model, c.make_year,
                 ctr.name AS country_name, p.port_name
          FROM orders o
          JOIN users u ON u.id = o.user_id
          JOIN cars c ON c.id = o.car_id
          JOIN countries ctr ON ctr.id = o.country_id
          JOIN ports p ON p.id = o.port_id
          $where
          ORDER BY o.id DESC";
    $res = mysqli_query($conn, $q);
    $rows = [];
    while ($row = mysqli_fetch_assoc($res))
        $rows[] = $row;
    echo json_encode(["status" => "success", "data" => $rows]);
    exit;


// ---------------------
// GET ORDER DETAILS + HISTORY
// ---------------------
if ($method === "GET" && isset($_GET["details"])) {
    $order_id = clean($_GET["details"]);

    $q1 = "SELECT o.*, u.full_name, u.email, u.phone, c.*, ctr.name AS country_name, p.port_name, p.price_per_m3
           FROM orders o
           JOIN users u ON u.id = o.user_id
           JOIN cars c ON c.id = o.car_id
           JOIN countries ctr ON ctr.id = o.country_id
           JOIN ports p ON p.id = o.port_id
           WHERE o.id='$order_id'";
    $res1 = mysqli_query($conn, $q1);
    if (mysqli_num_rows($res1) === 0) {
        echo json_encode(["status" => "error", "message" => "Order not found"]);
        exit;
    }
    $order = mysqli_fetch_assoc($res1);

    $q2 = "SELECT oh.*, u.full_name AS changed_by_name
           FROM order_history oh
           LEFT JOIN users u ON u.id = oh.changed_by
           WHERE oh.order_id='$order_id'
           ORDER BY oh.id DESC";
    $res2 = mysqli_query($conn, $q2);
    $history = [];
    while ($h = mysqli_fetch_assoc($res2))
        $history[] = $h;

    echo json_encode(["status" => "success", "order" => $order, "history" => $history]);
    exit;
}

// ---------------------
// UPDATE STATUS
// ---------------------
if ($method === "PUT" && isset($_GET["update_status"])) {
    $data = json_decode(file_get_contents("php://input"), true);
    $order_id = clean($data["order_id"]);
    $status = clean($data["status"]);
    $changed_by = clean($data["changed_by"]);
    $note = getProfessionalNote('status', $status);

    $res = mysqli_query($conn, "SELECT car_id FROM orders WHERE id='$order_id'");
    $order = mysqli_fetch_assoc($res);
    $car_id = $order['car_id'];

    if (mysqli_query($conn, "UPDATE orders SET status='$status' WHERE id='$order_id'")) {
        addHistory($order_id, 'status', $changed_by, $note);
        if (in_array($status, ['pending', 'approved'])) {
            mysqli_query($conn, "UPDATE cars SET status='pending' WHERE id='$car_id'");
        } elseif ($status === 'completed') {
            mysqli_query($conn, "UPDATE cars SET status='sold' WHERE id='$car_id'");
        } elseif (in_array($status, ['cancelled', 'returned'])) {
            mysqli_query($conn, "UPDATE cars SET status='available' WHERE id='$car_id'");
        }
        echo json_encode(["status" => "success", "message" => "Order status updated"]);
    } else {
        echo json_encode(["status" => "error", "message" => mysqli_error($conn)]);
    }
    exit;
}

// ---------------------
// UPDATE PAYMENT
// ---------------------
if ($method === "PUT" && isset($_GET["payment"])) {
    $data = json_decode(file_get_contents("php://input"), true);
    $order_id = clean($data["order_id"]);
    $payment_status = clean($data["payment_status"]);
    $changed_by = clean($data["changed_by"]);

    $q = "UPDATE orders SET payment_status='$payment_status' WHERE id='$order_id'";
    if (mysqli_query($conn, $q)) {
        addHistory($order_id, 'payment_status', $changed_by, getProfessionalNote('payment_status', $payment_status));
        echo json_encode(["status" => "success", "message" => "Payment updated"]);
    } else {
        echo json_encode(["status" => "error", "message" => mysqli_error($conn)]);
    }
    exit;
}

// ---------------------
// UPDATE FLAGS
// ---------------------
if ($method === "PUT" && isset($_GET["flags"])) {
    $data = json_decode(file_get_contents("php://input"), true);
    $order_id = clean($data["order_id"]);
    $changed_by = clean($data["changed_by"]);

    $fields = [];
    foreach (["inspection_done", "shipment_booked", "documents_issued"] as $f) {
        if (isset($data[$f])) {
            $val = $data[$f] ? 1 : 0;
            $fields[] = "$f='$val'";
            addHistory($order_id, $f, $changed_by, getProfessionalNote($f, $data[$f]));
        }
    }
    if (empty($fields)) {
        echo json_encode(["status" => "error", "message" => "No flag provided"]);
        exit;
    }
    mysqli_query($conn, "UPDATE orders SET " . implode(",", $fields) . " WHERE id='$order_id'");
    echo json_encode(["status" => "success", "message" => "Flags updated successfully"]);
    exit;
}

// ---------------------
// DELETE ORDER
// ---------------------
if ($method === "DELETE" && isset($_GET["delete"])) {
    $id = clean($_GET["delete"]);
    mysqli_query($conn, "DELETE FROM orders WHERE id='$id'");
    echo json_encode(["status" => "success", "message" => "Order deleted successfully"]);
    exit;
}

echo json_encode(["status" => "error", "message" => "Invalid API request"]);
exit;
?>