<?php
declare(strict_types=1);

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/events_common.php';

try {
    rvu_ensure_event_social_tables($pdo);
    $user = rvu_event_require_user($pdo);
    $viewerId = (int)$user['id'];
    $method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');

    if ($method === 'GET') {
        $scope = strtolower(trim((string)($_GET['scope'] ?? 'upcoming')));
        $page = max(1, (int)($_GET['page'] ?? 1));
        $limit = max(1, min(30, (int)($_GET['limit'] ?? 8)));
        $offset = ($page - 1) * $limit;
        $campus = trim((string)($_GET['campus'] ?? ''));
        $q = trim((string)($_GET['q'] ?? ''));

        $isAdmin = rvu_event_role_is_admin($user['role'] ?? '');
        $params = [':viewer_id' => $viewerId];

        if ($scope === 'all') {
            // The complete event archive contains drafts and inactive records and is
            // reserved for the administrator delete center.
            if (!$isAdmin) {
                rvu_event_json(['detail' => 'Administrator access is required to view all events.'], 403);
            }
            $conditions = ['1 = 1'];
        } else {
            // Public/staff event feeds expose only active, non-draft events.
            $conditions = ["COALESCE(LOWER(e.status), 'published') <> 'draft'", "COALESCE(e.is_active, TRUE) = TRUE"];
            if ($scope === 'past') {
                $conditions[] = 'e.event_date < CURRENT_TIMESTAMP';
            } else {
                $conditions[] = 'e.event_date >= CURRENT_TIMESTAMP';
            }
        }

        if ($campus !== '') {
            $conditions[] = 'e.campus = :campus';
            $params[':campus'] = $campus;
        }

        if ($q !== '') {
            $conditions[] = "(e.title ILIKE :q OR e.description ILIKE :q OR e.location ILIKE :q OR e.speakers ILIKE :q)";
            $params[':q'] = '%' . $q . '%';
        }

        $where = ' WHERE ' . implode(' AND ', $conditions);
        $order = $scope === 'past'
            ? ' ORDER BY e.event_date DESC NULLS LAST, e.id DESC'
            : ' ORDER BY e.created_at DESC NULLS LAST, e.event_date ASC NULLS LAST, e.id DESC';

        $countStmt = $pdo->prepare('SELECT COUNT(*) FROM events e' . $where);
        $countParams = $params;
        unset($countParams[':viewer_id']);
        $countStmt->execute($countParams);
        $total = (int)$countStmt->fetchColumn();

        $sql = rvu_event_select_sql() . $where . $order . " LIMIT {$limit} OFFSET {$offset}";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        $rows = array_map('rvu_event_normalize', $rows);

        rvu_event_json([
            'data' => $rows,
            'pagination' => [
                'page' => $page,
                'limit' => $limit,
                'total' => $total,
                'has_more' => ($offset + count($rows)) < $total,
            ],
        ]);
    }

    if ($method === 'POST') {
        $input = rvu_event_input();
        $title = trim((string)($input['title'] ?? ''));
        $description = trim((string)($input['description'] ?? ''));
        $category = trim((string)($input['category'] ?? 'General'));
        $eventDate = trim((string)($input['event_date'] ?? ''));
        $location = trim((string)($input['location'] ?? ''));
        $speakers = trim((string)($input['speakers'] ?? ''));

        if (rvu_event_strlen($title) < 4 || rvu_event_strlen($title) > 180) rvu_event_json(['detail' => 'Event title must contain 4 to 180 characters.'], 422);
        if (rvu_event_strlen($description) < 10) rvu_event_json(['detail' => 'Please provide a meaningful event description.'], 422);
        if ($eventDate === '' || strtotime($eventDate) === false) rvu_event_json(['detail' => 'A valid event date and time is required.'], 422);
        if ($location === '') rvu_event_json(['detail' => 'Event location is required.'], 422);

        $campus = trim((string)($user['campus'] ?? ''));
        if ($campus === '') $campus = 'University Wide';

        $stmt = $pdo->prepare("INSERT INTO events
            (author_id, title, description, category, campus, location, speakers, event_date, status, is_active, created_at, updated_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'Published', TRUE, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
            RETURNING id");
        $stmt->execute([$viewerId, $title, $description, $category ?: 'General', $campus, $location, $speakers, $eventDate]);
        $id = (int)$stmt->fetchColumn();
        rvu_event_json(['message' => 'Event published successfully.', 'id' => $id], 201);
    }

    $eventId = isset($_GET['id']) ? (int)$_GET['id'] : 0;
    if (($method === 'PUT' || $method === 'DELETE') && $eventId <= 0) {
        rvu_event_json(['detail' => 'A valid event id is required.'], 422);
    }

    if ($method === 'PUT') {
        $event = rvu_event_fetch($pdo, $eventId, $viewerId);
        if (!$event) rvu_event_json(['detail' => 'Event not found.'], 404);
        if (!rvu_event_can_manage($user, $event['author_id'] ?: null)) rvu_event_json(['detail' => 'You cannot edit this event.'], 403);

        $input = rvu_event_input();
        $allowed = ['title', 'description', 'category', 'location', 'speakers', 'event_date', 'status', 'is_active'];
        $fields = [];
        $params = [];
        foreach ($allowed as $field) {
            if (!array_key_exists($field, $input)) continue;
            $fields[] = "$field = ?";
            $params[] = $input[$field];
        }
        if (!$fields) rvu_event_json(['detail' => 'No event changes supplied.'], 422);
        $fields[] = 'updated_at = CURRENT_TIMESTAMP';
        $params[] = $eventId;
        $stmt = $pdo->prepare('UPDATE events SET ' . implode(', ', $fields) . ' WHERE id = ?');
        $stmt->execute($params);
        rvu_event_json(['message' => 'Event updated successfully.']);
    }

    if ($method === 'DELETE') {
        $event = rvu_event_fetch($pdo, $eventId, $viewerId);
        if (!$event) rvu_event_json(['detail' => 'Event not found.'], 404);
        // Permanent event deletion is an administrator-only operation.
        if (!rvu_event_role_is_admin($user['role'] ?? '')) {
            rvu_event_json(['detail' => 'Only an administrator can permanently delete events.'], 403);
        }

        $mediaStmt = $pdo->prepare('SELECT media_path, thumbnail_path FROM campus_event_media WHERE event_id = ?');
        $mediaStmt->execute([$eventId]);
        $files = $mediaStmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
        $pdo->beginTransaction();
        try {
            $pdo->prepare('DELETE FROM campus_event_likes WHERE event_id = ?')->execute([$eventId]);
            $commentIdsStmt = $pdo->prepare('SELECT id FROM campus_event_comments WHERE event_id = ?');
            $commentIdsStmt->execute([$eventId]);
            $commentIds = array_map('intval', $commentIdsStmt->fetchAll(PDO::FETCH_COLUMN) ?: []);
            if ($commentIds) {
                $placeholders = implode(',', array_fill(0, count($commentIds), '?'));
                $pdo->prepare("DELETE FROM campus_event_comment_mentions WHERE comment_id IN ($placeholders)")->execute($commentIds);
            }
            $pdo->prepare('DELETE FROM campus_event_comments WHERE event_id = ?')->execute([$eventId]);
            $pdo->prepare('DELETE FROM campus_event_notifications WHERE event_id = ?')->execute([$eventId]);
            $pdo->prepare('DELETE FROM campus_event_media WHERE event_id = ?')->execute([$eventId]);
            $pdo->prepare('DELETE FROM events WHERE id = ?')->execute([$eventId]);
            $pdo->commit();
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            throw $e;
        }
        $root = realpath(__DIR__ . '/..');
        foreach ($files as $file) {
            foreach (['media_path', 'thumbnail_path'] as $key) {
                $relative = trim((string)($file[$key] ?? ''));
                if ($root && $relative !== '' && str_starts_with(str_replace('\\', '/', $relative), 'uploads/events/')) {
                    $absolute = $root . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $relative);
                    if (is_file($absolute)) @unlink($absolute);
                }
            }
        }
        rvu_event_json(['message' => 'Event deleted.']);
    }

    rvu_event_json(['detail' => 'Unsupported request.'], 405);
} catch (Throwable $e) {
    rvu_event_json(['detail' => 'Events server error: ' . $e->getMessage()], 500);
}
