<?php
require "../config/database.php";
require "../includes/auth.php";

error_reporting(0);

header("Content-Type: application/json; charset=utf-8");
requireApiAuth();

$userId = (int)$_SESSION["user"]["id"];
$roleId = (int)($_SESSION["user"]["role_id"] ?? 0);
$otherId = (int)($_GET["user_id"] ?? 0);

if ($otherId <= 0 && $roleId !== 1) {
    http_response_code(422);
    echo json_encode(["success" => false, "error" => "user_id_required"]);
    exit;
}

if ($roleId === 1 && $otherId === 0) {
    $stmt = $pdo->prepare("
        SELECT m.*, u1.email AS sender_email, u2.email AS receiver_email
        FROM messages m
        LEFT JOIN users u1 ON u1.id = m.sender_id
        LEFT JOIN users u2 ON u2.id = m.receiver_id
        ORDER BY m.id DESC
        LIMIT 200
    ");
    $stmt->execute();
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

$stmt = $pdo->prepare("
    SELECT id, sender_id, receiver_id, text, status, created_at
    FROM messages
    WHERE (sender_id = ? AND receiver_id = ?)
       OR (sender_id = ? AND receiver_id = ?)
    ORDER BY id ASC
");
$stmt->execute([$userId, $otherId, $otherId, $userId]);
$messages = $stmt->fetchAll(PDO::FETCH_ASSOC);

$markRead = $pdo->prepare("
    UPDATE messages
    SET status = 'read'
    WHERE sender_id = ? AND receiver_id = ? AND status <> 'read'
");
$markRead->execute([$otherId, $userId]);

echo json_encode(["success" => true, "data" => $messages]);
