<?php
require_once 'auth_check.php';
require_once 'db.php';

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

if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 1) {
    http_response_code(403);
    echo json_encode(['error' => 'Access denied']);
    exit;
}

$action = $_POST['action'] ?? $_GET['action'] ?? '';

$db = getDB1Connection();

switch ($action) {
    case 'get_staff_list':
        getStaffList($db);
        break;
    
    case 'get_channels':
        getChannels($db);
        break;
    
    case 'get_messages':
        getMessages($db);
        break;
    
    case 'send_message':
        sendMessage($db);
        break;
    
    case 'get_private_conversations':
        getPrivateConversations($db);
        break;
    
    case 'update_status':
        updateUserStatus($db);
        break;
    
    case 'mark_typing':
        markTyping($db);
        break;
    
    case 'get_unread_count':
        getUnreadCount($db);
        break;
    
    default:
        http_response_code(400);
        echo json_encode(['error' => 'Invalid action']);
}

function getStaffList($db) {
    $stmt = $db->prepare("
        SELECT id, username, roleinimators, last_seen, status 
        FROM utilisateurs 
        WHERE role = 1 AND id != ? 
        ORDER BY status DESC, username ASC
    ");
    $stmt->execute([$_SESSION['user_id']]);
    $staff = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($staff as &$member) {
        $member['is_online'] = (time() - strtotime($member['last_seen'])) < 300;
        $member['last_seen_formatted'] = timeAgo($member['last_seen']);
    }
    
    echo json_encode($staff);
}

function getChannels($db) {
    $channels = [
        ['id' => 'general', 'name' => 'General', 'description' => 'Canal général du staff'],
        ['id' => 'dev', 'name' => 'Développement', 'description' => 'Discussions techniques'],
        ['id' => 'support', 'name' => 'Support', 'description' => 'Questions support client']
    ];
    
    echo json_encode($channels);
}

function getMessages($db) {
    $channel = $_GET['channel'] ?? 'general';
    $conversation_id = $_GET['conversation_id'] ?? null;
    $last_id = $_GET['last_id'] ?? 0;
    
    if ($conversation_id) {
        $stmt = $db->prepare("
            SELECT m.*, u.username, u.roleinimators
            FROM chat_messages m
            JOIN utilisateurs u ON m.user_id = u.id
            WHERE m.conversation_id = ? AND m.id > ?
            ORDER BY m.created_at ASC
            LIMIT 50
        ");
        $stmt->execute([$conversation_id, $last_id]);
    } else {
        $stmt = $db->prepare("
            SELECT m.*, u.username, u.roleinimators
            FROM chat_messages m
            JOIN utilisateurs u ON m.user_id = u.id
            WHERE m.channel = ? AND m.conversation_id IS NULL AND m.id > ?
            ORDER BY m.created_at ASC
            LIMIT 50
        ");
        $stmt->execute([$channel, $last_id]);
    }
    
    $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($messages as &$message) {
        $message['time_formatted'] = date('H:i', strtotime($message['created_at']));
        $message['date_formatted'] = date('Y-m-d', strtotime($message['created_at']));
        $message['is_own'] = $message['user_id'] == $_SESSION['user_id'];
    }
    
    echo json_encode($messages);
}

function sendMessage($db) {
    $input = json_decode(file_get_contents('php://input'), true);
    
    $message = trim($input['message'] ?? '');
    $channel = $input['channel'] ?? 'general';
    $conversation_id = $input['conversation_id'] ?? null;
    $recipient_id = $input['recipient_id'] ?? null;
    
    if (empty($message)) {
        http_response_code(400);
        echo json_encode(['error' => 'Message cannot be empty']);
        return;
    }
    
    if ($recipient_id && !$conversation_id) {
        $conversation_id = createOrGetConversation($db, $_SESSION['user_id'], $recipient_id);
    }
    
    $stmt = $db->prepare("
        INSERT INTO chat_messages (user_id, channel, conversation_id, message, created_at)
        VALUES (?, ?, ?, ?, NOW())
    ");
    $stmt->execute([$_SESSION['user_id'], $conversation_id ? null : $channel, $conversation_id, $message]);
    
    $message_id = $db->lastInsertId();
    
    $stmt = $db->prepare("
        SELECT m.*, u.username, u.roleinimators
        FROM chat_messages m
        JOIN utilisateurs u ON m.user_id = u.id
        WHERE m.id = ?
    ");
    $stmt->execute([$message_id]);
    $new_message = $stmt->fetch(PDO::FETCH_ASSOC);
    
    $new_message['time_formatted'] = date('H:i', strtotime($new_message['created_at']));
    $new_message['date_formatted'] = date('Y-m-d', strtotime($new_message['created_at']));
    $new_message['is_own'] = true;
    
    updateUserActivity($db);
    
    echo json_encode($new_message);
}

function getPrivateConversations($db) {
    $stmt = $db->prepare("
        SELECT DISTINCT 
            c.id as conversation_id,
            CASE 
                WHEN c.user1_id = ? THEN u2.id 
                ELSE u1.id 
            END as other_user_id,
            CASE 
                WHEN c.user1_id = ? THEN u2.username 
                ELSE u1.username 
            END as other_username,
            CASE 
                WHEN c.user1_id = ? THEN u2.roleinimators 
                ELSE u1.roleinimators 
            END as other_role,
            m.message as last_message,
            m.created_at as last_message_time,
            COUNT(m2.id) as unread_count
        FROM chat_conversations c
        JOIN utilisateurs u1 ON c.user1_id = u1.id
        JOIN utilisateurs u2 ON c.user2_id = u2.id
        LEFT JOIN chat_messages m ON c.id = m.conversation_id
        LEFT JOIN chat_messages m2 ON c.id = m2.conversation_id AND m2.user_id != ? AND m2.is_read = 0
        WHERE (c.user1_id = ? OR c.user2_id = ?)
        GROUP BY c.id
        ORDER BY m.created_at DESC
    ");
    
    $user_id = $_SESSION['user_id'];
    $stmt->execute([$user_id, $user_id, $user_id, $user_id, $user_id, $user_id]);
    $conversations = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($conversations as &$conv) {
        $conv['last_message_formatted'] = $conv['last_message_time'] ? timeAgo($conv['last_message_time']) : '';
    }
    
    echo json_encode($conversations);
}

function createOrGetConversation($db, $user1_id, $user2_id) {
    // Vérifier si une conversation existe déjà
    $stmt = $db->prepare("
        SELECT id FROM chat_conversations 
        WHERE (user1_id = ? AND user2_id = ?) OR (user1_id = ? AND user2_id = ?)
    ");
    $stmt->execute([$user1_id, $user2_id, $user2_id, $user1_id]);
    $conversation = $stmt->fetch();
    
    if ($conversation) {
        return $conversation['id'];
    }
    
    // Créer une nouvelle conversation en s'assurant que user1_id < user2_id pour éviter les doublons
    $smaller_id = min($user1_id, $user2_id);
    $larger_id = max($user1_id, $user2_id);
    
    try {
        $stmt = $db->prepare("
            INSERT INTO chat_conversations (user1_id, user2_id, created_at)
            VALUES (?, ?, NOW())
        ");
        $stmt->execute([$smaller_id, $larger_id]);
        
        return $db->lastInsertId();
    } catch (PDOException $e) {
        // Si erreur de doublon, récupérer l'ID existant
        $stmt = $db->prepare("
            SELECT id FROM chat_conversations 
            WHERE user1_id = ? AND user2_id = ?
        ");
        $stmt->execute([$smaller_id, $larger_id]);
        $conversation = $stmt->fetch();
        
        return $conversation ? $conversation['id'] : null;
    }
}

function updateUserStatus($db) {
    $input = json_decode(file_get_contents('php://input'), true);
    $status = $input['status'] ?? 'online';
    
    $stmt = $db->prepare("UPDATE utilisateurs SET status = ?, last_seen = NOW() WHERE id = ?");
    $stmt->execute([$status, $_SESSION['user_id']]);
    
    echo json_encode(['success' => true]);
}

function markTyping($db) {
    $input = json_decode(file_get_contents('php://input'), true);
    $channel = $input['channel'] ?? 'general';
    $conversation_id = $input['conversation_id'] ?? null;
    
    // Supprimer les anciens indicateurs de frappe pour cet utilisateur
    $stmt = $db->prepare("
        DELETE FROM chat_typing 
        WHERE user_id = ? AND 
              ((channel = ? AND conversation_id IS NULL) OR 
               (conversation_id = ? AND channel IS NULL))
    ");
    $stmt->execute([$_SESSION['user_id'], $conversation_id ? null : $channel, $conversation_id]);
    
    // Ajouter le nouvel indicateur
    $stmt = $db->prepare("
        INSERT INTO chat_typing (user_id, channel, conversation_id, created_at)
        VALUES (?, ?, ?, NOW())
    ");
    $stmt->execute([$_SESSION['user_id'], $conversation_id ? null : $channel, $conversation_id]);
    
    echo json_encode(['success' => true]);
}

function getUnreadCount($db) {
    $stmt = $db->prepare("
        SELECT COUNT(*) as count 
        FROM chat_messages m
        JOIN chat_conversations c ON m.conversation_id = c.id
        WHERE (c.user1_id = ? OR c.user2_id = ?) 
        AND m.user_id != ? 
        AND m.is_read = 0
    ");
    $stmt->execute([$_SESSION['user_id'], $_SESSION['user_id'], $_SESSION['user_id']]);
    $result = $stmt->fetch();
    
    echo json_encode(['count' => $result['count']]);
}

function updateUserActivity($db) {
    $stmt = $db->prepare("UPDATE utilisateurs SET last_seen = NOW() WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
}

function timeAgo($datetime) {
    $time = time() - strtotime($datetime);
    
    if ($time < 60) return 'À l\'instant';
    if ($time < 3600) return floor($time/60) . 'min';
    if ($time < 86400) return floor($time/3600) . 'h';
    if ($time < 2592000) return floor($time/86400) . 'j';
    
    return date('d/m/Y', strtotime($datetime));
}
?>