<?php
require_once 'db.php';
session_start();

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

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Non authentifié']);
    exit;
}

$data = json_decode(file_get_contents('php://input'), true);
$action = $data['action'] ?? '';

$db = getDB1Connection();

switch ($action) {
    case 'create':
        if ($_SESSION['roleinimators'] !== 'CEO') {
            echo json_encode(['success' => false, 'message' => 'Seuls les CEO peuvent créer des réunions']);
            exit;
        }
        
        $title = $data['title'] ?? 'Réunion sans titre';
        $description = $data['description'] ?? '';
        $meetingCode = generateMeetingCode();
        $meetingId = bin2hex(random_bytes(16));
        
        $stmt = $db->prepare("INSERT INTO meetings (id, code, title, description, host_id, created_at, status) VALUES (?, ?, ?, ?, ?, NOW(), 'active')");
        $stmt->execute([$meetingId, $meetingCode, $title, $description, $_SESSION['user_id']]);
        
        echo json_encode([
            'success' => true,
            'meetingId' => $meetingId,
            'meetingCode' => $meetingCode
        ]);
        break;
        
    case 'join':
        $meetingCode = strtoupper($data['meetingCode'] ?? '');
        
        $stmt = $db->prepare("SELECT id, title, host_id FROM meetings WHERE code = ? AND status = 'active'");
        $stmt->execute([$meetingCode]);
        $meeting = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$meeting) {
            echo json_encode(['success' => false, 'message' => 'Réunion introuvable ou terminée']);
            exit;
        }
        
        $stmt = $db->prepare("INSERT INTO meeting_participants (meeting_id, user_id, joined_at) VALUES (?, ?, NOW())");
        $stmt->execute([$meeting['id'], $_SESSION['user_id']]);
        
        echo json_encode([
            'success' => true,
            'meetingId' => $meeting['id'],
            'meetingTitle' => $meeting['title'],
            'isHost' => $meeting['host_id'] == $_SESSION['user_id']
        ]);
        break;
        
    case 'leave':
        $meetingId = $data['meetingId'] ?? '';
        
        $stmt = $db->prepare("UPDATE meeting_participants SET left_at = NOW() WHERE meeting_id = ? AND user_id = ? AND left_at IS NULL");
        $stmt->execute([$meetingId, $_SESSION['user_id']]);
        
        echo json_encode(['success' => true]);
        break;
        
    case 'end':
        $meetingId = $data['meetingId'] ?? '';
        
        $stmt = $db->prepare("SELECT host_id FROM meetings WHERE id = ?");
        $stmt->execute([$meetingId]);
        $meeting = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($meeting['host_id'] != $_SESSION['user_id']) {
            echo json_encode(['success' => false, 'message' => 'Seul l\'hôte peut terminer la réunion']);
            exit;
        }
        
        $stmt = $db->prepare("UPDATE meetings SET status = 'completed', ended_at = NOW() WHERE id = ?");
        $stmt->execute([$meetingId]);
        
        $stmt = $db->prepare("UPDATE meeting_participants SET left_at = NOW() WHERE meeting_id = ? AND left_at IS NULL");
        $stmt->execute([$meetingId]);
        
        echo json_encode(['success' => true]);
        break;
        
    case 'get_active':
        $stmt = $db->query("
            SELECT m.*, 
                   COUNT(DISTINCT mp.user_id) as participants,
                   TIMESTAMPDIFF(MINUTE, m.created_at, NOW()) as duration_minutes
            FROM meetings m
            LEFT JOIN meeting_participants mp ON m.id = mp.meeting_id AND mp.left_at IS NULL
            WHERE m.status = 'active'
            GROUP BY m.id
            ORDER BY m.created_at DESC
        ");
        
        $meetings = [];
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $meetings[] = [
                'id' => $row['id'],
                'code' => $row['code'],
                'title' => $row['title'],
                'participants' => $row['participants'],
                'duration' => formatDuration($row['duration_minutes'])
            ];
        }
        
        echo json_encode(['success' => true, 'meetings' => $meetings]);
        break;
        
    case 'get_history':
        if ($_SESSION['roleinimators'] !== 'CEO') {
            echo json_encode(['success' => false, 'message' => 'Accès refusé']);
            exit;
        }
        
        $stmt = $db->query("
            SELECT m.*, 
                   COUNT(DISTINCT mp.user_id) as participants,
                   TIMESTAMPDIFF(MINUTE, m.created_at, COALESCE(m.ended_at, NOW())) as duration_minutes
            FROM meetings m
            LEFT JOIN meeting_participants mp ON m.id = mp.meeting_id
            GROUP BY m.id
            ORDER BY m.created_at DESC
            LIMIT 20
        ");
        
        $meetings = [];
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $meetings[] = [
                'id' => $row['id'],
                'title' => $row['title'],
                'date' => date('d/m/Y H:i', strtotime($row['created_at'])),
                'participants' => $row['participants'],
                'duration' => formatDuration($row['duration_minutes']),
                'status' => $row['status']
            ];
        }
        
        echo json_encode(['success' => true, 'meetings' => $meetings]);
        break;
        
    case 'get_participants':
        $meetingId = $data['meetingId'] ?? '';
        
        $stmt = $db->prepare("
            SELECT u.username, u.id, m.host_id
            FROM meeting_participants mp
            JOIN utilisateurs u ON mp.user_id = u.id
            JOIN meetings m ON mp.meeting_id = m.id
            WHERE mp.meeting_id = ? AND mp.left_at IS NULL
        ");
        $stmt->execute([$meetingId]);
        
        $participants = [];
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $participants[] = [
                'id' => $row['id'],
                'name' => $row['username'],
                'isHost' => $row['id'] == $row['host_id']
            ];
        }
        
        echo json_encode(['success' => true, 'participants' => $participants]);
        break;
        
    default:
        echo json_encode(['success' => false, 'message' => 'Action invalide']);
}

function generateMeetingCode() {
    $characters = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    $code = '';
    for ($i = 0; $i < 12; $i++) {
        $code .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $code;
}

function formatDuration($minutes) {
    if ($minutes < 60) {
        return $minutes . ' min';
    }
    $hours = floor($minutes / 60);
    $mins = $minutes % 60;
    return $hours . 'h' . ($mins > 0 ? ' ' . $mins . 'min' : '');
}