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

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

if (!isLoggedIn()) {
    echo json_encode(['error' => 'Not authenticated']);
    exit;
}

try {
    $pdo = getDBConnection();
} catch (Exception $e) {
    echo json_encode(['error' => 'Database error']);
    exit;
}

$userId = $_SESSION['user_id'];
$action = $_GET['action'] ?? '';

// Get or create conversation for this user
function getOrCreateConversation($pdo, $userId) {
    // Check if user has a conversation
    $stmt = $pdo->prepare("SELECT id FROM support_conversations WHERE user_id = ? ORDER BY id DESC LIMIT 1");
    $stmt->execute([$userId]);
    $conv = $stmt->fetch();
    
    if ($conv) {
        return $conv['id'];
    }
    
    // Create new conversation
    $stmt = $pdo->prepare("INSERT INTO support_conversations (user_id, status, created_at, updated_at) VALUES (?, 'open', NOW(), NOW())");
    $stmt->execute([$userId]);
    return $pdo->lastInsertId();
}

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

// SEND MESSAGE
if ($action === 'send' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $input = file_get_contents('php://input');
        $data = json_decode($input, true);
        $message = trim($data['message'] ?? '');
        
        if (empty($message)) {
            echo json_encode(['success' => false, 'error' => 'Empty message']);
            exit;
        }
        
        $convId = getOrCreateConversation($pdo, $userId);
        
        // Insert message
        $stmt = $pdo->prepare("INSERT INTO support_messages (conversation_id, sender_id, sender_role, message, is_read, created_at) VALUES (?, ?, 'user', ?, 0, NOW())");
        $stmt->execute([$convId, $userId, $message]);
        
        // Update conversation timestamp
        $pdo->prepare("UPDATE support_conversations SET status = 'open', updated_at = NOW() WHERE id = ?")->execute([$convId]);
        
        echo json_encode(['success' => true, 'id' => $pdo->lastInsertId()]);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

// CHECK UNREAD
if ($action === 'unread') {
    try {
        $stmt = $pdo->prepare("
            SELECT COUNT(*) FROM support_messages m 
            JOIN support_conversations c ON m.conversation_id = c.id 
            WHERE c.user_id = ? AND m.sender_role != 'user' AND m.is_read = 0
        ");
        $stmt->execute([$userId]);
        echo json_encode(['success' => true, 'count' => (int)$stmt->fetchColumn()]);
    } catch (Exception $e) {
        echo json_encode(['success' => true, 'count' => 0]);
    }
    exit;
}

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