<?php
require_once __DIR__ . '/../includes/config.php';

$createdBy = requireAuth();
$method = $_SERVER['REQUEST_METHOD'];

try {
    switch ($method) {
        case 'GET':
            if (isset($_GET['id'])) {
                $stmt = $pdo->prepare("
                    SELECT ce.*, a.name as created_by_name, a.color as admin_color 
                    FROM calendar_events ce 
                    LEFT JOIN administrators a ON ce.created_by = a.id 
                    WHERE ce.id = ?
                ");
                $stmt->execute([$_GET['id']]);
                $event = $stmt->fetch();
                
                if ($event) {
                    jsonResponse($event);
                } else {
                    jsonResponse(['error' => 'Evento não encontrado'], 404);
                }
            } else {
                $start = $_GET['start'] ?? date('Y-m-01');
                $end = $_GET['end'] ?? date('Y-m-t');
                
                $stmt = $pdo->prepare("
                    SELECT ce.*, a.name as created_by_name, a.color as admin_color 
                    FROM calendar_events ce 
                    LEFT JOIN administrators a ON ce.created_by = a.id 
                    WHERE ce.start_date <= ? AND (ce.end_date >= ? OR ce.end_date IS NULL OR ce.start_date >= ?)
                    ORDER BY ce.start_date ASC
                ");
                $stmt->execute([$end, $start, $start]);
                jsonResponse($stmt->fetchAll());
            }
            break;

        case 'POST':
            $data = getJsonInput();
            
            if (empty($data['title'])) {
                jsonResponse(['error' => 'Título é obrigatório'], 400);
            }
            if (empty($data['start_date'])) {
                jsonResponse(['error' => 'Data de início é obrigatória'], 400);
            }
            
            $id = generateId();
            
            // Convert all_day to proper boolean for MySQL (1/0)
            $allDay = isset($data['all_day']) && ($data['all_day'] === true || $data['all_day'] === 'true' || $data['all_day'] === 1 || $data['all_day'] === '1') ? 1 : 0;
            
            $stmt = $pdo->prepare("
                INSERT INTO calendar_events (id, title, description, start_date, end_date, all_day, created_by)
                VALUES (?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $id,
                $data['title'],
                $data['description'] ?? null,
                $data['start_date'],
                $data['end_date'] ?? null,
                $allDay,
                $createdBy
            ]);
            
            $stmt = $pdo->prepare("
                SELECT ce.*, a.name as created_by_name, a.color as admin_color 
                FROM calendar_events ce 
                LEFT JOIN administrators a ON ce.created_by = a.id 
                WHERE ce.id = ?
            ");
            $stmt->execute([$id]);
            jsonResponse($stmt->fetch(), 201);
            break;

        case 'PUT':
            $id = $_GET['id'] ?? null;
            if (!$id) {
                jsonResponse(['error' => 'ID é obrigatório'], 400);
            }
            
            $stmt = $pdo->prepare("SELECT created_by FROM calendar_events WHERE id = ?");
            $stmt->execute([$id]);
            $event = $stmt->fetch();
            
            if (!$event) {
                jsonResponse(['error' => 'Evento não encontrado'], 404);
            }
            
            if ($event['created_by'] !== $createdBy) {
                jsonResponse(['error' => 'Você só pode editar seus próprios eventos'], 403);
            }
            
            $data = getJsonInput();
            
            if (empty($data['title'])) {
                jsonResponse(['error' => 'Título é obrigatório'], 400);
            }
            
            // Convert all_day to proper boolean for MySQL (1/0)
            $allDay = isset($data['all_day']) && ($data['all_day'] === true || $data['all_day'] === 'true' || $data['all_day'] === 1 || $data['all_day'] === '1') ? 1 : 0;
            
            $stmt = $pdo->prepare("
                UPDATE calendar_events 
                SET title = ?, description = ?, start_date = ?, end_date = ?, all_day = ?
                WHERE id = ?
            ");
            $stmt->execute([
                $data['title'],
                $data['description'] ?? null,
                $data['start_date'],
                $data['end_date'] ?? null,
                $allDay,
                $id
            ]);
            
            $stmt = $pdo->prepare("
                SELECT ce.*, a.name as created_by_name, a.color as admin_color 
                FROM calendar_events ce 
                LEFT JOIN administrators a ON ce.created_by = a.id 
                WHERE ce.id = ?
            ");
            $stmt->execute([$id]);
            jsonResponse($stmt->fetch());
            break;

        case 'DELETE':
            $id = $_GET['id'] ?? null;
            if (!$id) {
                jsonResponse(['error' => 'ID é obrigatório'], 400);
            }
            
            $stmt = $pdo->prepare("SELECT created_by FROM calendar_events WHERE id = ?");
            $stmt->execute([$id]);
            $event = $stmt->fetch();
            
            if (!$event) {
                jsonResponse(['error' => 'Evento não encontrado'], 404);
            }
            
            if ($event['created_by'] !== $createdBy) {
                jsonResponse(['error' => 'Você só pode excluir seus próprios eventos'], 403);
            }
            
            $stmt = $pdo->prepare("DELETE FROM calendar_events WHERE id = ?");
            $stmt->execute([$id]);
            jsonResponse(['success' => true]);
            break;

        default:
            jsonResponse(['error' => 'Método não permitido'], 405);
    }
} catch (PDOException $e) {
    jsonResponse(['error' => 'Erro no banco de dados: ' . $e->getMessage()], 500);
}
