<?php
// baca_chat.php

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

require 'security.php';
require 'logger.php';
require 'db.php';
require 'rate_limit.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method Not Allowed']);
    log_activity("Method Not Allowed on baca_chat.php from IP: " . $_SERVER['REMOTE_ADDR']);
    exit;
}

// Mendapatkan token dari header Authorization
$headers = apache_request_headers();
if (isset($headers['Authorization'])) {
    $authorizationHeader = $headers['Authorization'];
    // Mengambil token dari string "Bearer <token>"
    $token = str_replace("Bearer ", "", $authorizationHeader);
} else {
    http_response_code(401);
    echo json_encode(['error' => 'Authorization header missing']);
    log_activity("Authorization header missing in baca_chat.php");
    exit;
}

try {
    // 1) Cari user_id berdasarkan token
    $stmt = $pdo->prepare("SELECT user_id FROM tokens WHERE token = ? AND expires_at >= NOW()");
    $stmt->execute([$token]);
    $tokenData = $stmt->fetch();

    if (!$tokenData) {
        http_response_code(401);
        echo json_encode(['error' => 'Invalid or expired token']);
        log_activity("Invalid or expired token in baca_chat.php");
        exit;
    }

    $user_id = $tokenData['user_id'];

    // 2) Ambil chat_id dari request body
    $data = json_decode(file_get_contents('php://input'), true);
    $chat_id = $data['chat_id'] ?? null;

    // 3) Validasi data
    if (empty($chat_id)) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing chat_id']);
        exit;
    }

    // 4) Periksa apakah user adalah participant di chat tersebut, jika chat_id = 1, tambahkan sebagai participant
    if ($chat_id == 1) {
        $stmt = $pdo->prepare("SELECT id FROM chat_participants WHERE chat_id = ? AND user_id = ?");
        $stmt->execute([$chat_id, $user_id]);
        $participant = $stmt->fetch();

        if (!$participant) {
            // Tambahkan user sebagai participant di chat_id = 1
            $stmt = $pdo->prepare("INSERT INTO chat_participants (chat_id, user_id) VALUES (?, ?)");
            $stmt->execute([$chat_id, $user_id]);
        }
    } else {
        $stmt = $pdo->prepare("SELECT id FROM chat_participants WHERE chat_id = ? AND user_id = ?");
        $stmt->execute([$chat_id, $user_id]);
        $participant = $stmt->fetch();

        if (!$participant) {
            http_response_code(403); // Forbidden
            echo json_encode(['error' => 'You are not authorized to access this chat. You are not a participant.']);
            exit;
        }
    }

    // 5) Ambil pesan dari tabel chat_messages
$stmt = $pdo->prepare("
    SELECT cm.id, cm.sender_id, cm.message, cm.sent_at, u.name AS sender_name
    FROM chat_messages cm
    JOIN users u ON cm.sender_id = u.id
    WHERE cm.chat_id = ?
    ORDER BY cm.id DESC
");
    $stmt->execute([$chat_id]);
    $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // 6) Tambahkan informasi "me" 
    foreach ($messages as &$message) {
        $message['me'] = ($message['sender_id'] == $user_id) ? 'yes' : 'no';
    }

    // 7) Response
    http_response_code(200);
    echo json_encode($messages);
    log_activity("Chat messages retrieved by user ID: " . $user_id . " for chat ID: " . $chat_id);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Server error: ' . $e->getMessage()]);
    log_activity("baca_chat.php error: " . $e->getMessage());
    exit;
}

?>