<?php
// kirim_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 kirim_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 kirim_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 kirim_chat.php");
        exit;
    }

    $user_id = $tokenData['user_id'];

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

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

    // 4) Periksa apakah user adalah participant di chat tersebut
    $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 a participant in this chat']);
        exit;
    }

    // 5) Sanitasi pesan untuk mengizinkan emoticon tetapi mencegah script
    $message = filter_var($message, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES);

    // 6) Insert pesan ke tabel chat_messages
    $stmt = $pdo->prepare("INSERT INTO chat_messages (chat_id, sender_id, message) VALUES (?, ?, ?)");
    $stmt->execute([$chat_id, $user_id, $message]);

    // 7) Response
    http_response_code(201);
    echo json_encode(['message' => 'Message sent successfully']);
    log_activity("New message sent by user ID: " . $user_id . " in chat ID: " . $chat_id);

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

?>