<?php
declare(strict_types=1);

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

require_once __DIR__ . '/../db.php';

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

if (empty($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode([
        'ok' => false,
        'message' => 'Unauthorized'
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

$pdo = db();

if (!$pdo instanceof PDO) {
    http_response_code(500);
    echo json_encode([
        'ok' => false,
        'message' => 'DB not ready'
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

$userId = (int)($_SESSION['user_id'] ?? 0);
$roomId = (int)($_GET['room_id'] ?? 0);
$lastId = (int)($_GET['last_id'] ?? 0);

if ($userId <= 0) {
    http_response_code(401);
    echo json_encode([
        'ok' => false,
        'message' => 'جلسة المستخدم غير صالحة'
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($roomId <= 0) {
    http_response_code(400);
    echo json_encode([
        'ok' => false,
        'message' => 'room_id required'
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    $memberCheck = $pdo->prepare("
        SELECT 1
        FROM chat_room_members
        WHERE room_id = ?
          AND employee_id = ?
        LIMIT 1
    ");
    $memberCheck->execute([$roomId, $userId]);

    if (!$memberCheck->fetchColumn()) {
        http_response_code(403);
        echo json_encode([
            'ok' => false,
            'message' => 'غير مصرح لك بالدخول لهذه الغرفة'
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $sql = "
        SELECT
            m.id,
            m.room_id,
            m.sender_id,
            m.message,
            m.message_type,
            m.created_at,
            COALESCE(NULLIF(e.full_name, ''), CONCAT('موظف #', m.sender_id)) AS sender_name
        FROM chat_messages m
        LEFT JOIN employees e ON e.id = m.sender_id
        WHERE m.room_id = ?
          AND m.is_deleted = 0
    ";

    $params = [$roomId];

    if ($lastId > 0) {
        $sql .= " AND m.id > ? ";
        $params[] = $lastId;
    }

    $sql .= " ORDER BY m.id ASC LIMIT 100";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);

    $messages = $stmt->fetchAll();

    echo json_encode([
        'ok' => true,
        'messages' => $messages
    ], JSON_UNESCAPED_UNICODE);

} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode([
        'ok' => false,
        'message' => 'فشل في جلب الرسائل',
        'error' => $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
    exit;
}