<?php
ini_set('display_errors', 0);
error_reporting(E_ALL);

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

try {
    require_once '../db.php';

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

    $userId = $_SESSION['user_id'];
    $method = $_SERVER['REQUEST_METHOD'];

    if ($method === 'GET') {
        $stmtEv = $pdo->prepare("SELECT id, title, event_date, color FROM calendar_events WHERE user_id = :user_id");
        $stmtEv->execute(['user_id' => $userId]);
        $events = $stmtEv->fetchAll() ?: [];

        $stmtTasks = $pdo->prepare("
            SELECT id, title, COALESCE(due_date, completed_at) as event_date, 
            CASE 
                WHEN xp_reward >= 175 THEN '#f43f5e'
                WHEN xp_reward >= 100 THEN '#f59e0b'
                ELSE '#10b981'
            END as color 
            FROM tasks 
            WHERE user_id = :user_id AND (due_date IS NOT NULL OR completed_at IS NOT NULL)
        ");
        $stmtTasks->execute(['user_id' => $userId]);
        $taskEvents = $stmtTasks->fetchAll() ?: [];

        $stmtUser = $pdo->prepare("SELECT ical_url FROM users WHERE id = :user_id");
        $stmtUser->execute(['user_id' => $userId]);
        $userData = $stmtUser->fetch();
        $icalUrl = $userData['ical_url'] ?? '';

        $externalEvents = [];

        if (!empty($icalUrl)) {
            $context = stream_context_create([
                'http' => ['timeout' => 5, 'user_agent' => 'Mozilla/5.0']
            ]);
            $icsContent = @file_get_contents($icalUrl, false, $context);

            if ($icsContent) {
                $chunks = explode('BEGIN:VEVENT', $icsContent);
                foreach ($chunks as $chunk) {
                    if (strpos($chunk, 'END:VEVENT') === false) continue;
                    
                    preg_match('/SUMMARY:(.*?)(?:\r\n|\n|\r)/', $chunk, $sumMatch);
                    preg_match('/DTSTART(?:;[^:]+)?:(\d{8})(?:T\d{6}Z?)?/', $chunk, $dateMatch);

                    if (!empty($sumMatch[1]) && !empty($dateMatch[1])) {
                        $rawDate = $dateMatch[1];
                        $formattedDate = substr($rawDate, 0, 4) . '-' . substr($rawDate, 4, 2) . '-' . substr($rawDate, 6, 2);
                        
                        $externalEvents[] = [
                            'id' => 'ical_' . uniqid(),
                            'title' => trim(str_replace(['\\', ';', ','], ['\\\\', '\;', '\,'], $sumMatch[1])),
                            'event_date' => $formattedDate,
                            'color' => '#3b82f6'
                        ];
                    }
                }
            }
        }

        $allEvents = array_merge($events, $taskEvents, $externalEvents);

        echo json_encode([
            'success' => true,
            'events' => $allEvents,
            'ical_url' => $icalUrl
        ]);
        exit;
    }

    if ($method === 'POST') {
        $data = json_decode(file_get_contents('php://input'), true);

        if (isset($data['action']) && $data['action'] === 'save_ical') {
            $icalUrl = trim($data['ical_url'] ?? '');
            $stmt = $pdo->prepare("UPDATE users SET ical_url = :url WHERE id = :user_id");
            $stmt->execute(['url' => $icalUrl, 'user_id' => $userId]);
            echo json_encode(['success' => true, 'message' => 'Lien iCal sauvegardé !']);
            exit;
        }

        if (isset($data['action']) && $data['action'] === 'update') {
            $eventId = $data['id'] ?? null;
            $title = trim($data['title'] ?? '');
            $eventDate = $data['event_date'] ?? null;

            if ($eventId && !empty($title) && !empty($eventDate)) {
                $stmt = $pdo->prepare("UPDATE calendar_events SET title = :title, event_date = :event_date WHERE id = :id AND user_id = :user_id");
                $stmt->execute(['title' => $title, 'event_date' => $eventDate, 'id' => $eventId, 'user_id' => $userId]);
                echo json_encode(['success' => true, 'message' => 'Événement mis à jour !']);
                exit;
            } else {
                echo json_encode(['success' => false, 'message' => 'Informations requises manquantes.']);
                exit;
            }
        }

        $title = trim($data['title'] ?? '');
        $date = $data['event_date'] ?? null;
        $color = $data['color'] ?? '#6366f1';

        if (empty($title) || empty($date)) {
            echo json_encode(['success' => false, 'message' => 'Titre et date requis.']);
            exit;
        }

        $stmt = $pdo->prepare("INSERT INTO calendar_events (user_id, title, event_date, color, created_at) VALUES (:user_id, :title, :event_date, :color, NOW())");
        $stmt->execute(['user_id' => $userId, 'title' => $title, 'event_date' => $date, 'color' => $color]);

        echo json_encode(['success' => true, 'message' => 'Événement ajouté !']);
        exit;
    }

    if ($method === 'DELETE') {
        $data = json_decode(file_get_contents('php://input'), true);
        $eventId = $data['id'] ?? null;

        if ($eventId) {
            $stmt = $pdo->prepare("DELETE FROM calendar_events WHERE id = :id AND user_id = :user_id");
            $stmt->execute(['id' => $eventId, 'user_id' => $userId]);
            echo json_encode(['success' => true, 'message' => 'Événement supprimé !']);
        } else {
            echo json_encode(['success' => false, 'message' => 'ID manquant.']);
        }
        exit;
    }

} catch (Throwable $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>