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

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

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

/* --------------------------------
MESSAGING NOTES (OPTIONAL)
---------------------------------*/
function getMessageNote($action)
{
    switch ($action) {
        case 'sent':
            return "Message sent successfully.";
        case 'read':
            return "Message marked as read.";
        default:
            return "Message status updated.";
    }
}

/* --------------------------------
ADD MESSAGE HISTORY (OPTIONAL)
---------------------------------*/
// function addMessageHistory($sender_id, $receiver_id, $note)
// {
//     global $conn;
//     $sender_id = clean($sender_id);
//     $receiver_id = clean($receiver_id);
//     $note = clean($note);

//     mysqli_query(
//         $conn,
//         "INSERT INTO messages_history (sender_id, receiver_id, note)
//                 VALUES ('$sender_id', '$receiver_id', '$note')"
//     );
// }

$method = $_SERVER["REQUEST_METHOD"];

/* --------------------------------
SEND MESSAGE
---------------------------------*/
if ($method === "POST" && isset($_GET["send"])) {

    $sender_id = clean($_POST['sender_id'] ?? '');
    $receiver_id = clean($_POST['receiver_id'] ?? '');
    $message = clean($_POST['message'] ?? '');

    if (!$sender_id || !$receiver_id || !$message) {
        echo json_encode(["status" => "error", "message" => "Required fields missing"]);
        exit;
    }

    $q = "INSERT INTO messages (sender_id, receiver_id, message)
          VALUES ('$sender_id', '$receiver_id', '$message')";

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

    // addMessageHistory($sender_id, $receiver_id, getMessageNote('sent'));

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

/* --------------------------------
GET CONVERSATION BETWEEN TWO USERS
---------------------------------*/
if ($method === "GET" && isset($_GET["conversation"])) {

    $user_id = clean($_GET["user_id"] ?? '');
    $other_user_id = clean($_GET["other_user_id"] ?? '');

    if (!$user_id || !$other_user_id) {
        echo json_encode(["status" => "error", "message" => "Missing user IDs"]);
        exit;
    }

    $q = "SELECT m.*, u.full_name AS sender_name
          FROM messages m
          JOIN users u ON u.id = m.sender_id
          WHERE (m.sender_id='$user_id' AND m.receiver_id='$other_user_id')
             OR (m.sender_id='$other_user_id' AND m.receiver_id='$user_id')
          ORDER BY m.created_at ASC";

    $res = mysqli_query($conn, $q);
    $rows = [];
    while ($row = mysqli_fetch_assoc($res)) {
        $rows[] = $row;
    }

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

/* --------------------------------
GET INBOX (LATEST MESSAGE PER CONVERSATION)
---------------------------------*/
if ($method === "GET" && isset($_GET["inbox"])) {

    $user_id = clean($_GET["user_id"] ?? '');
    if (!$user_id) {
        echo json_encode(["status" => "error", "message" => "Missing user ID"]);
        exit;
    }

    $q = "SELECT m.*
          FROM messages m
          INNER JOIN (
              SELECT LEAST(sender_id, receiver_id) AS u1,
                     GREATEST(sender_id, receiver_id) AS u2,
                     MAX(id) AS last_id
              FROM messages
              WHERE sender_id='$user_id' OR receiver_id='$user_id'
              GROUP BY u1, u2
          ) x ON m.id = x.last_id
          ORDER BY m.created_at DESC";

    $res = mysqli_query($conn, $q);
    $rows = [];
    while ($row = mysqli_fetch_assoc($res)) {
        $rows[] = $row;
    }

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

/* --------------------------------
MARK MESSAGES AS READ
---------------------------------*/
if ($method === "PUT" && isset($_GET["markRead"])) {

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

    $sender_id = clean($data['sender_id'] ?? '');
    $receiver_id = clean($data['receiver_id'] ?? '');

    if (!$sender_id || !$receiver_id) {
        echo json_encode(["status" => "error", "message" => "Missing sender or receiver ID"]);
        exit;
    }

    $q = "UPDATE messages
          SET is_read=1
          WHERE sender_id='$sender_id' AND receiver_id='$receiver_id'";

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

    // addMessageHistory($sender_id, $receiver_id, getMessageNote('read'));

    echo json_encode(["status" => "success", "message" => "Messages marked as read"]);
    exit;
}

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