<?php
// list_chat.php

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

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method Not Allowed']);
    log_activity("Method Not Allowed on list_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 list_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 list_chat.php");
        exit;
    }

    $user_id = $tokenData['user_id'];

    // 2) Ambil semua chat yang diikuti oleh user
    $stmt = $pdo->prepare("
        SELECT c.id, c.type, c.name
        FROM chats c
        JOIN chat_participants cp ON c.id = cp.chat_id
        WHERE cp.user_id = ?
    ");
    $stmt->execute([$user_id]);
    $chats = $stmt->fetchAll();

    // 3) Response data chat
    http_response_code(200);
    echo json_encode($chats);
    log_activity("All chats retrieved for user ID: " . $user_id);

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

?>