<?php
header('Content-Type: application/json');
require_once '../../config/config.php';
require_once '../../config/database.php';
require_once '../../includes/functions.php';
require_once '../../includes/Auth.php';

if (session_status() === PHP_SESSION_NONE) session_start();
$user = auth()->getUser();
if (!$user) { echo json_encode(['success' => false, 'error' => 'Not logged in']); exit; }

$type = $_GET['type'] ?? 'ticket';

try {
    if ($type === 'live_chat') {
        $chat = dbFetch("SELECT id FROM support_chats WHERE user_id = ? AND status = 'active'", [$user['id']]);
        
        if ($chat) {
            $messages = dbFetchAll("SELECT * FROM support_chat_messages WHERE chat_id = ? ORDER BY created_at ASC", [$chat['id']]);
            echo json_encode(['success' => true, 'messages' => $messages]);
        } else {
            echo json_encode(['success' => true, 'messages' => []]);
        }
    } else {
        $messages = dbFetchAll("SELECT * FROM support_messages WHERE user_id = ? ORDER BY created_at DESC LIMIT 50", [$user['id']]);
        echo json_encode(['success' => true, 'messages' => $messages]);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
