<?php
require_once dirname(__DIR__) . '/config/config.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['error' => 'Unauthorized']);
    exit;
}

$pdo = getDBConnection();
$userId = $_SESSION['user_id'];
$action = $_GET['action'] ?? $_POST['action'] ?? '';

// Get or create conversation
function getConversation($pdo, $userId) {
    $stmt = $pdo->prepare("SELECT * FROM support_conversations WHERE user_id = ? ORDER BY created_at DESC LIMIT 1");
    $stmt->execute([$userId]);
    return $stmt->fetch();
}

if ($action === 'get') {
    try {
        $conv = getConversation($pdo, $userId);
        
        if (!$conv) {
            echo json_encode(['messages' => []]);
            exit;
        }
        
        // Mark admin messages as read
        $stmt = $pdo->prepare("UPDATE support_messages SET is_read = 1 WHERE conversation_id = ? AND sender_role != 'user'");
        $stmt->execute([$conv['id']]);
        
        // Get messages
        $stmt = $pdo->prepare("SELECT * FROM support_messages WHERE conversation_id = ? ORDER BY created_at ASC");
        $stmt->execute([$conv['id']]);
        $messages = $stmt->fetchAll();
        
        $result = [];
        foreach ($messages as $m) {
            $result[] = [
                'id' => $m['id'],
                'message' => htmlspecialchars($m['message']),
                'sender_role' => $m['sender_role'],
                'time' => date('M d, H:i', strtotime($m['created_at']))
            ];
        }
        
        echo json_encode(['messages' => $result]);
    } catch (Exception $e) {
        echo json_encode(['messages' => [], 'error' => $e->getMessage()]);
    }
    exit;
}

if ($action === 'send') {
    $input = json_decode(file_get_contents('php://input'), true);
    $message = trim($input['message'] ?? '');
    
    if (!$message) {
        echo json_encode(['error' => 'Message required']);
        exit;
    }
    
    try {
        $conv = getConversation($pdo, $userId);
        
        if (!$conv) {
            $stmt = $pdo->prepare("INSERT INTO support_conversations (user_id, status, created_at, updated_at) VALUES (?, 'open', NOW(), NOW())");
            $stmt->execute([$userId]);
            $convId = $pdo->lastInsertId();
        } else {
            $convId = $conv['id'];
            $stmt = $pdo->prepare("UPDATE support_conversations SET status = 'open', updated_at = NOW() WHERE id = ?");
            $stmt->execute([$convId]);
        }
        
        $stmt = $pdo->prepare("INSERT INTO support_messages (conversation_id, sender_id, sender_role, message, created_at) VALUES (?, ?, 'user', ?, NOW())");
        $stmt->execute([$convId, $userId, $message]);
        
        echo json_encode(['success' => true, 'message_id' => $pdo->lastInsertId()]);
    } catch (Exception $e) {
        echo json_encode(['error' => $e->getMessage()]);
    }
    exit;
}

if ($action === 'unread') {
    try {
        $conv = getConversation($pdo, $userId);
        
        if (!$conv) {
            echo json_encode(['count' => 0]);
            exit;
        }
        
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM support_messages WHERE conversation_id = ? AND sender_role != 'user' AND is_read = 0");
        $stmt->execute([$conv['id']]);
        $count = $stmt->fetchColumn();
        
        echo json_encode(['count' => intval($count)]);
    } catch (Exception $e) {
        echo json_encode(['count' => 0]);
    }
    exit;
}

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