<?php
header('Content-Type: application/json');
require_once 'auth/session.php';
require_once 'includes/permissions.php';
requireLogin();

$user = getCurrentUser();
$user_id = $user['id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'create';

    if ($action === 'create') {
        $channel_id = $_POST['channel_id'] ?? 0;
        $title = trim($_POST['title'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $start_date = $_POST['start_date'] ?? '';
        $start_time = $_POST['start_time'] ?? '';
        $end_date = $_POST['end_date'] ?? '';
        $end_time = $_POST['end_time'] ?? '';
        $frequency = $_POST['frequency'] ?? ''; // Expecting comma separated like "1,3,5"
        $is_permanent = isset($_POST['is_permanent']) ? (int)$_POST['is_permanent'] : 0;
        $enable_reactions = isset($_POST['enable_reactions']) ? (int)$_POST['enable_reactions'] : 0;
        $banner_color = $_POST['banner_color'] ?? null;

        if (!$channel_id || !$title || !$start_date || !$start_time || (!$is_permanent && (!$end_date || !$end_time))) {
            echo json_encode(['success' => false, 'error' => 'Champs obligatoires manquants']);
            exit;
        }

        // Check if channel exists and get server_id
        $stmt = db()->prepare("SELECT server_id FROM channels WHERE id = ?");
        $stmt->execute([$channel_id]);
        $channel = $stmt->fetch();

        if (!$channel) {
            echo json_encode(['success' => false, 'error' => 'Salon introuvable']);
            exit;
        }

        $server_id = $channel['server_id'];

        // Check permission
        if (!Permissions::canDoInChannel($user_id, $channel_id, Permissions::CREATE_EVENT)) {
            echo json_encode(['success' => false, 'error' => 'Permission refusée']);
            exit;
        }

        $banner_url = null;
        // Handle banner upload
        if (isset($_FILES['banner_image']) && $_FILES['banner_image']['error'] === UPLOAD_ERR_OK) {
            $file = $_FILES['banner_image'];
            $allowedTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
            $maxSize = 5 * 1024 * 1024; // 5MB for banners

            if (!in_array($file['type'], $allowedTypes)) {
                echo json_encode(['success' => false, 'error' => 'Format d\'image non supporté']);
                exit;
            }

            if ($file['size'] > $maxSize) {
                echo json_encode(['success' => false, 'error' => 'Image trop volumineuse (max 5Mo)']);
                exit;
            }

            $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
            if (empty($extension)) {
                $extensions = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp', 'image/gif' => 'gif'];
                $extension = $extensions[$file['type']] ?? 'png';
            }

            $filename = 'banner_' . $channel_id . '_' . time() . '_' . rand(1000, 9999) . '.' . $extension;
            $dir = __DIR__ . '/assets/images/banners/';
            if (!is_dir($dir)) mkdir($dir, 0775, true);

            $targetPath = $dir . $filename;
            if (move_uploaded_file($file['tmp_name'], $targetPath)) {
                $banner_url = 'assets/images/banners/' . $filename;
            }
        }

        try {
            $stmt = db()->prepare("INSERT INTO channel_events 
                (channel_id, user_id, title, description, banner_url, banner_color, start_date, start_time, end_date, end_time, frequency, is_permanent, enable_reactions) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([
                $channel_id, $user_id, $title, $description, $banner_url, $banner_color, 
                $start_date, $start_time, $end_date, $end_time, $frequency, $is_permanent, $enable_reactions
            ]);

            echo json_encode(['success' => true, 'event_id' => db()->lastInsertId()]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'error' => 'Erreur lors de la création : ' . $e->getMessage()]);
        }
        exit;
    }

    if ($action === 'update') {
        $event_id = $_POST['event_id'] ?? 0;
        $title = trim($_POST['title'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $start_date = $_POST['start_date'] ?? '';
        $start_time = $_POST['start_time'] ?? '';
        $end_date = $_POST['end_date'] ?? '';
        $end_time = $_POST['end_time'] ?? '';
        $frequency = $_POST['frequency'] ?? '';
        $is_permanent = isset($_POST['is_permanent']) ? (int)$_POST['is_permanent'] : 0;
        $enable_reactions = isset($_POST['enable_reactions']) ? (int)$_POST['enable_reactions'] : 0;
        $banner_color = $_POST['banner_color'] ?? null;

        if (!$event_id || !$title || !$start_date || !$start_time || (!$is_permanent && (!$end_date || !$end_time))) {
            echo json_encode(['success' => false, 'error' => 'Champs obligatoires manquants']);
            exit;
        }

        $stmt = db()->prepare("SELECT ce.*, c.server_id FROM channel_events ce JOIN channels c ON ce.channel_id = c.id WHERE ce.id = ?");
        $stmt->execute([$event_id]);
        $event = $stmt->fetch();

        if (!$event) {
            echo json_encode(['success' => false, 'error' => 'Événement introuvable']);
            exit;
        }

        if ($event['user_id'] != $user_id && !Permissions::canDoInChannel($user_id, $event['channel_id'], Permissions::EDIT_EVENT)) {
            echo json_encode(['success' => false, 'error' => 'Permission refusée']);
            exit;
        }

        $banner_url = $event['banner_url'];
        if (isset($_FILES['banner_image']) && $_FILES['banner_image']['error'] === UPLOAD_ERR_OK) {
            // ... (upload logic same as create)
            $file = $_FILES['banner_image'];
            $allowedTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
            $maxSize = 5 * 1024 * 1024;
            if (in_array($file['type'], $allowedTypes) && $file['size'] <= $maxSize) {
                $extension = pathinfo($file['name'], PATHINFO_EXTENSION) ?: 'png';
                $filename = 'banner_' . $event['channel_id'] . '_' . time() . '_' . rand(1000, 9999) . '.' . $extension;
                $dir = __DIR__ . '/assets/images/banners/';
                if (!is_dir($dir)) mkdir($dir, 0775, true);
                if (move_uploaded_file($file['tmp_name'], $dir . $filename)) {
                    if ($banner_url && file_exists(__DIR__ . '/' . $banner_url)) @unlink(__DIR__ . '/' . $banner_url);
                    $banner_url = 'assets/images/banners/' . $filename;
                }
            }
        }

        try {
            $stmt = db()->prepare("UPDATE channel_events SET 
                title = ?, description = ?, banner_url = ?, banner_color = ?, 
                start_date = ?, start_time = ?, end_date = ?, end_time = ?, 
                frequency = ?, is_permanent = ?, enable_reactions = ? 
                WHERE id = ?");
            $stmt->execute([
                $title, $description, $banner_url, $banner_color, 
                $start_date, $start_time, $end_date, $end_time, 
                $frequency, $is_permanent, $enable_reactions, $event_id
            ]);
            echo json_encode(['success' => true]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'error' => 'Erreur lors de la mise à jour']);
        }
        exit;
    }

    if ($action === 'participate') {
        $event_id = $_POST['event_id'] ?? 0;
        if (!$event_id) exit;

        $stmt = db()->prepare("SELECT * FROM event_participations WHERE event_id = ? AND user_id = ?");
        $stmt->execute([$event_id, $user_id]);
        if ($stmt->fetch()) {
            $stmt = db()->prepare("DELETE FROM event_participations WHERE event_id = ? AND user_id = ?");
            $stmt->execute([$event_id, $user_id]);
            echo json_encode(['success' => true, 'action' => 'removed']);
        } else {
            $stmt = db()->prepare("INSERT INTO event_participations (event_id, user_id) VALUES (?, ?)");
            $stmt->execute([$event_id, $user_id]);
            echo json_encode(['success' => true, 'action' => 'added']);
        }
        exit;
    }

    if ($action === 'delete') {
        $event_id = $_POST['event_id'] ?? 0;
        if (!$event_id) {
            echo json_encode(['success' => false, 'error' => 'ID d\'événement manquant']);
            exit;
        }

        // Get event to find channel and server
        $stmt = db()->prepare("SELECT ce.*, c.server_id FROM channel_events ce JOIN channels c ON ce.channel_id = c.id WHERE ce.id = ?");
        $stmt->execute([$event_id]);
        $event = $stmt->fetch();

        if (!$event) {
            echo json_encode(['success' => false, 'error' => 'Événement introuvable']);
            exit;
        }

        // Check permission (creator or delete_event)
        if ($event['user_id'] != $user_id && !Permissions::canDoInChannel($user_id, $event['channel_id'], Permissions::DELETE_EVENT)) {
            echo json_encode(['success' => false, 'error' => 'Permission refusée']);
            exit;
        }

        try {
            // Delete banner file if it exists
            if ($event['banner_url'] && file_exists(__DIR__ . '/' . $event['banner_url'])) {
                @unlink(__DIR__ . '/' . $event['banner_url']);
            }

            $stmt = db()->prepare("DELETE FROM channel_events WHERE id = ?");
            $stmt->execute([$event_id]);

            echo json_encode(['success' => true]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'error' => 'Erreur lors de la suppression']);
        }
        exit;
    }
}

echo json_encode(['success' => false, 'error' => 'Requête invalide']);
