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

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

$method = $_SERVER["REQUEST_METHOD"];

// ---------------------- Helper: log JSON for debugging ----------------------
function debug_log($label, $data)
{
    echo json_encode([
        "status" => "debug",
        "label" => $label,
        "data" => $data
    ]);
    exit;
}

// -------------------------------------------------------
// 1️⃣ USER CREATES INQUIRY + FIRST MESSAGE
// -------------------------------------------------------
if ($method === "POST" && isset($_GET["submit"])) {

    $data = json_decode(file_get_contents("php://input"), true);

    // Debug log to see received payload
    // debug_log("Received Payload", $data);

    $required = ["user_id", "car_make", "car_model", "message"];
    foreach ($required as $field) {
        if (empty($data[$field])) {
            echo json_encode([
                "status" => "error",
                "message" => "$field is required",
                "received" => $data
            ]);
            exit;
        }
    }

    $user_id = clean($data["user_id"]);
    $car_make = clean($data["car_make"]);
    $car_model = clean($data["car_model"]);
    $fuel_type = clean($data["fuel_type"] ?? "");
    $transmission = clean($data["transmission"] ?? "");
    $body_type = clean($data["body_type"] ?? "");
    $color = clean($data["color"] ?? "");
    $budget = clean($data["budget"] ?? "");
    $message = clean($data["message"]);

    // Insert inquiry
    $q1 = "INSERT INTO inquiries 
        (user_id, car_make, car_model, fuel_type, transmission, body_type, color, budget, status)
        VALUES 
        ('$user_id', '$car_make', '$car_model', '$fuel_type', '$transmission', '$body_type', '$color', '$budget', 'pending')";

    if (!mysqli_query($conn, $q1)) {
        echo json_encode([
            "status" => "error",
            "message" => mysqli_error($conn),
            "query" => $q1
        ]);
        exit;
    }

    $inquiry_id = mysqli_insert_id($conn);

    // Insert first message (receiver_id = 2)
    $q2 = "INSERT INTO inquiry_messages 
        (inquiry_id, sender_id, receiver_id, message, is_admin_sender)
        VALUES 
        ('$inquiry_id', '$user_id', 2, '$message', 0)";

    if (!mysqli_query($conn, $q2)) {
        echo json_encode([
            "status" => "error",
            "message" => mysqli_error($conn),
            "query" => $q2
        ]);
        exit;
    }

    echo json_encode([
        "status" => "success",
        "message" => "Inquiry submitted successfully",
        "inquiry_id" => $inquiry_id
    ]);
    exit;
}

// -------------------------------------------------------
// 2️⃣ ADMIN GETS ALL INQUIRIES + FIRST MESSAGE PREVIEW
// -------------------------------------------------------
if ($method === "GET" && isset($_GET["all"])) {

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

    $q = "SELECT 
            i.*,
            u.full_name AS user_name,
            (SELECT message FROM inquiry_messages 
             WHERE inquiry_id = i.id ORDER BY id ASC LIMIT 1) AS first_message
        FROM inquiries i
        JOIN users u ON i.user_id = u.id
        $where
        ORDER BY i.id DESC";

    $res = mysqli_query($conn, $q);
    $rows = [];

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

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

// -------------------------------------------------------
// 3️⃣ GET FULL DETAILS (INQUIRY + ALL MESSAGES)
// -------------------------------------------------------
if ($method === "GET" && isset($_GET["details"])) {

    $inquiry_id = clean($_GET["details"]);

    $q1 = "SELECT i.*, u.full_name AS user_name, u.email AS user_email
           FROM inquiries i
           JOIN users u ON i.user_id = u.id
           WHERE i.id = '$inquiry_id'";

    $res1 = mysqli_query($conn, $q1);

    if (mysqli_num_rows($res1) === 0) {
        echo json_encode(["status" => "error", "message" => "Inquiry not found"]);
        exit;
    }

    $inquiry = mysqli_fetch_assoc($res1);

    $q2 = "SELECT im.*, 
                sender.full_name AS sender_name, 
                receiver.full_name AS receiver_name
            FROM inquiry_messages im
            JOIN users sender ON sender.id = im.sender_id
            JOIN users receiver ON receiver.id = im.receiver_id
            WHERE inquiry_id = '$inquiry_id'
            ORDER BY im.id ASC";

    $res2 = mysqli_query($conn, $q2);
    $messages = [];

    while ($msg = mysqli_fetch_assoc($res2)) {
        $messages[] = $msg;
    }

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

// -------------------------------------------------------
// 4️⃣ ADMIN REPLY
// -------------------------------------------------------
if ($method === "POST" && isset($_GET["admin_reply"])) {
    $data = json_decode(file_get_contents("php://input"), true);

    $inquiry_id = clean($data["inquiry_id"]);
    $admin_id = clean($data["admin_id"]);
    $message = clean($data["message"]);

    if (!$inquiry_id || !$admin_id || !$message) {
        echo json_encode(["status" => "error", "message" => "inquiry_id, admin_id, and message are required"]);
        exit;
    }

    $res = mysqli_query($conn, "SELECT user_id FROM inquiries WHERE id='$inquiry_id'");
    $row = mysqli_fetch_assoc($res);
    $user_id = $row["user_id"];

    $q = "INSERT INTO inquiry_messages 
        (inquiry_id, sender_id, receiver_id, message, is_admin_sender)
        VALUES 
        ('$inquiry_id', '$admin_id', '$user_id', '$message', 1)";

    mysqli_query($conn, $q);
    mysqli_query($conn, "UPDATE inquiries SET status='responded' WHERE id='$inquiry_id'");

    echo json_encode(["status" => "success", "message" => "Reply sent successfully"]);
    exit;
}

// -------------------------------------------------------
// 5️⃣ UPDATE INQUIRY STATUS (ADMIN)
// -------------------------------------------------------
if ($method === "PUT" && isset($_GET["status"])) {
    $data = json_decode(file_get_contents("php://input"), true);
    $inquiry_id = clean($data["inquiry_id"]);
    $status = clean($data["status"]);

    if (mysqli_query($conn, "UPDATE inquiries SET status='$status' WHERE id='$inquiry_id'")) {
        echo json_encode(["status" => "success", "message" => "Status updated"]);
    } else {
        echo json_encode(["status" => "error", "message" => mysqli_error($conn)]);
    }
    exit;
}

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

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