<?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)($_POST['room_id'] ?? 0);
$message = trim((string)($_POST['message'] ?? ''));

if ($roomId <= 0 || $message === '') {
    echo json_encode(['ok' => false, 'message' => 'بيانات غير مكتملة'], JSON_UNESCAPED_UNICODE);
    exit;
}

try {
  $ins = $pdo->prepare("
    INSERT INTO chat_messages (room_id, sender_id, message)
    VALUES (?, ?, ?)
");
$ins->execute([$roomId, $userId, $message]);
    if (!$chk->fetchColumn()) {
        http_response_code(403);
        echo json_encode(['ok' => false, 'message' => 'غير مصرح'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $ins = $pdo->prepare("
        INSERT INTO chat_messages (room_id, sender_id, message)
        VALUES (?, ?, ?)
    ");
    $ins->execute([$roomId, $userId, $message]);

    $messageId = (int)$pdo->lastInsertId();

    $members = $pdo->prepare("
        SELECT employee_id
        FROM chat_room_members
        WHERE room_id = ?
          AND employee_id <> ?
    ");
    $members->execute([$roomId, $userId]);
    $receivers = $members->fetchAll(PDO::FETCH_COLUMN);

    if ($receivers) {
        $insNotif = $pdo->prepare("
            INSERT INTO chat_notifications (employee_id, message_id, room_id, is_read)
            VALUES (?, ?, ?, 0)
        ");

        foreach ($receivers as $empId) {
            $insNotif->execute([(int)$empId, $messageId, $roomId]);
        }
    }

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

} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode([
        'ok' => false,
        'message' => $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
}