<?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; }

$input = json_decode(file_get_contents('php://input'), true);
$message = trim($input['message'] ?? '');
$type = $input['type'] ?? 'ticket';

if (empty($message)) {
    echo json_encode(['success' => false, 'error' => 'Message required']);
    exit;
}

try {
    if ($type === 'live_chat') {
        // Get or create chat
        $chat = dbFetch("SELECT id FROM support_chats WHERE user_id = ? AND status = 'active'", [$user['id']]);
        
        if (!$chat) {
            $chatId = dbInsert('support_chats', [
                'user_id' => $user['id'],
                'status' => 'active'
            ]);
        } else {
            $chatId = $chat['id'];
        }
        
        // Insert message
        dbInsert('support_chat_messages', [
            'chat_id' => $chatId,
            'user_id' => $user['id'],
            'message' => $message,
            'is_admin' => 0
        ]);
        
        // Update chat timestamp
        dbQuery("UPDATE support_chats SET updated_at = NOW() WHERE id = ?", [$chatId]);
        
        echo json_encode(['success' => true, 'chat_id' => $chatId]);
    } else {
        // Regular support ticket
        dbInsert('support_messages', [
            'user_id' => $user['id'],
            'message' => $message,
            'is_admin' => 0
        ]);
        echo json_encode(['success' => true]);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
