<?php
/**
 * API: admin_chat.php
 * Purpose: Handle embedded admin-user chat within AI widget
 * Features: Create ticket, send/receive messages in real-time
 */

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../classes/Database.php';
require_once __DIR__ . '/../classes/Auth.php';

header('Content-Type: application/json; charset=utf-8');
$db = Database::getInstance();
$auth = new Auth($db);

// Verify user is logged in
if (!$auth->isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$currentUser = $auth->getCurrentUser();
$userId = intval($currentUser['id']);
$action = $_POST['action'] ?? $_GET['action'] ?? '';

try {
    // ACTION: Create or get existing admin chat ticket
    if ($action === 'get_or_create_ticket') {
        // Check if user already has an open admin chat ticket
        $existing = $db->fetch(
            "SELECT id FROM support_tickets 
             WHERE user_id = ? AND title = 'Admin Chat (AI Widget)' AND status IN ('open', 'pending')
             ORDER BY created_at DESC LIMIT 1",
            [$userId]
        );
        
        if ($existing) {
            echo json_encode([
                'success' => true,
                'ticket_id' => $existing['id'],
                'new' => false
            ]);
        } else {
            // Create new ticket
            $db->query(
                "INSERT INTO support_tickets (user_id, title, status, created_at) 
                 VALUES (?, 'Admin Chat (AI Widget)', 'open', NOW())",
                [$userId]
            );
            $ticketId = $db->getConnection()->lastInsertId();
            
            echo json_encode([
                'success' => true,
                'ticket_id' => $ticketId,
                'new' => true
            ]);
        }
        exit();
    }
    
    // ACTION: Get chat messages for ticket
    if ($action === 'get_messages') {
        $ticketId = intval($_POST['ticket_id'] ?? 0);
        
        if ($ticketId <= 0) {
            echo json_encode(['success' => false, 'message' => 'Invalid ticket']);
            exit();
        }
        
        // Verify user owns this ticket
        $ticket = $db->fetch(
            "SELECT user_id FROM support_tickets WHERE id = ?",
            [$ticketId]
        );
        
        if (!$ticket || $ticket['user_id'] != $userId) {
            http_response_code(403);
            echo json_encode(['success' => false, 'message' => 'Access denied']);
            exit();
        }
        
        // Fetch messages
        $messages = $db->fetchAll(
            "SELECT id, sender_id, message, created_at,
                    CASE WHEN sender_id = 1 THEN 'admin' ELSE 'user' END as sender_type,
                    (SELECT name FROM users WHERE id = sender_id) as sender_name
             FROM support_messages
             WHERE ticket_id = ?
             ORDER BY created_at ASC",
            [$ticketId]
        );
        
        echo json_encode([
            'success' => true,
            'messages' => $messages ?: []
        ]);
        exit();
    }
    
    // ACTION: Send message to admin
    if ($action === 'send_message') {
        $ticketId = intval($_POST['ticket_id'] ?? 0);
        $message = trim($_POST['message'] ?? '');
        
        if ($ticketId <= 0 || empty($message)) {
            echo json_encode(['success' => false, 'message' => 'Invalid input']);
            exit();
        }
        
        // Verify user owns this ticket
        $ticket = $db->fetch(
            "SELECT user_id FROM support_tickets WHERE id = ?",
            [$ticketId]
        );
        
        if (!$ticket || $ticket['user_id'] != $userId) {
            http_response_code(403);
            echo json_encode(['success' => false, 'message' => 'Access denied']);
            exit();
        }
        
        // Insert message
        $db->query(
            "INSERT INTO support_messages (ticket_id, sender_id, message, created_at)
             VALUES (?, ?, ?, NOW())",
            [$ticketId, $userId, $message]
        );
        
        // Get inserted message
        $newMessage = $db->fetch(
            "SELECT id, sender_id, message, created_at FROM support_messages
             ORDER BY id DESC LIMIT 1"
        );
        
        echo json_encode([
            'success' => true,
            'message' => [
                'id' => $newMessage['id'],
                'sender_id' => $newMessage['sender_id'],
                'sender_type' => 'user',
                'message' => $newMessage['message'],
                'created_at' => $newMessage['created_at']
            ]
        ]);
        exit();
    }
    
    // ACTION: Poll for new admin messages (real-time)
    if ($action === 'poll_messages') {
        $ticketId = intval($_POST['ticket_id'] ?? 0);
        $lastMessageId = intval($_POST['last_message_id'] ?? 0);
        
        if ($ticketId <= 0) {
            echo json_encode(['success' => false, 'messages' => []]);
            exit();
        }
        
        // Get new messages from admin (sender_id = 1)
        $newMessages = $db->fetchAll(
            "SELECT id, sender_id, message, created_at FROM support_messages
             WHERE ticket_id = ? AND id > ? AND sender_id = 1
             ORDER BY created_at ASC",
            [$ticketId, $lastMessageId]
        );
        
        echo json_encode([
            'success' => true,
            'messages' => array_map(function($msg) {
                return [
                    'id' => $msg['id'],
                    'sender_id' => $msg['sender_id'],
                    'sender_type' => 'admin',
                    'message' => $msg['message'],
                    'created_at' => $msg['created_at']
                ];
            }, $newMessages ?: [])
        ]);
        exit();
    }
    
    echo json_encode(['success' => false, 'message' => 'Unknown action']);
    exit();
    
} catch (Exception $e) {
    error_log('Admin chat error: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Server error']);
    exit();
}
