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

    $user_id = $tokenData['user_id'];

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

    // 3) Validasi data
    if (empty($type) || !in_array($type, ['group', 'private'])) {
        http_response_code(400);
        echo json_encode(['error' => 'Invalid chat type']);
        exit;
    }

    // 4) Insert data ke tabel chats
    $stmt = $pdo->prepare("INSERT INTO chats (type, name) VALUES (?, ?)");
    $stmt->execute([$type, $name]);
    $chat_id = $pdo->lastInsertId();

    // 5) Insert data ke tabel chat_participants
    $stmt = $pdo->prepare("INSERT INTO chat_participants (chat_id, user_id) VALUES (?, ?)");
    $stmt->execute([$chat_id, $user_id]);

    // 6) Response 
    http_response_code(201); 
    echo json_encode(['message' => 'Chat room created successfully', 'chat_id' => $chat_id]);
    log_activity("New chat room created by user ID: " . $user_id);

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

?>