<?php
session_start();
require_once('includes/functions.php');

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    exit('Unauthorized');
}

$userId = $_SESSION['user_id'];
$role = $_SESSION['role'];
$action = isset($_POST['action']) ? $_POST['action'] : (isset($_GET['action']) ? $_GET['action'] : '');

// Helper: get group code from display name
$groupMap = array_flip(getChatGroups());

if ($action == 'send') {
    $groupDisplay = isset($_POST['group']) ? $_POST['group'] : '';
    $message = isset($_POST['message']) ? trim($_POST['message']) : '';
    
    if (!isset($groupMap[$groupDisplay])) {
        echo json_encode(['error' => 'Invalid group']);
        exit;
    }
    $groupCode = $groupMap[$groupDisplay];
    
    $fileAttachment = null;
    
    // Handle file upload
    if (isset($_FILES['file']) && $_FILES['file']['error'] == 0) {
        $allowed = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'application/pdf', 'text/plain'];
        $maxSize = 5 * 1024 * 1024; // 5MB
        if (in_array($_FILES['file']['type'], $allowed) && $_FILES['file']['size'] < $maxSize) {
            $uploadDir = 'uploads/chat/';
            if (!file_exists($uploadDir)) mkdir($uploadDir, 0777, true);
            $ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
            $filename = 'chat_' . time() . '_' . rand(1000,9999) . '.' . $ext;
            if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadDir . $filename)) {
                $fileAttachment = $uploadDir . $filename;
            }
        }
    }
    
    if (!empty($message) || $fileAttachment) {
        saveChatMessage($groupCode, $userId, $message, $fileAttachment);
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['error' => 'Empty message or file too large']);
    }
    exit;
}

if ($action == 'fetch') {
    $groupDisplay = isset($_GET['group']) ? $_GET['group'] : '';
    $lastId = isset($_GET['last_id']) ? intval($_GET['last_id']) : 0;
    
    if (!isset($groupMap[$groupDisplay])) {
        echo json_encode(['error' => 'Invalid group']);
        exit;
    }
    $groupCode = $groupMap[$groupDisplay];
    
    $messages = getChatMessages($groupCode, 200);
    $isAdmin = ($role == 'admin');
    $newMessages = [];
    foreach ($messages as $msg) {
        if ($msg['id'] > $lastId) {
            $newMessages[] = [
                'id' => $msg['id'],
                'display_name' => getChatDisplayName($msg['user_id'], $isAdmin),
                'message' => htmlspecialchars($msg['message']),
                'file' => $msg['file'],
                'timestamp' => date('g:i A', strtotime($msg['timestamp'])),
                'full_date' => date('M j, Y g:i A', strtotime($msg['timestamp']))
            ];
        }
    }
    echo json_encode(['messages' => $newMessages]);
    exit;
}

echo json_encode(['error' => 'Invalid action']);
?>