<?php
declare(strict_types=1);

require_once __DIR__ . '/session_auth.php';

function rvu_event_json($payload, int $status = 200): void {
    http_response_code($status);
    header('Content-Type: application/json; charset=utf-8');
    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
    header('Pragma: no-cache');
    echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE);
    exit;
}

function rvu_event_input(): array {
    $raw = file_get_contents('php://input');
    if ($raw === false || trim($raw) === '') return [];
    $decoded = json_decode($raw, true);
    if (!is_array($decoded)) {
        rvu_event_json(['detail' => 'Invalid JSON request body.'], 400);
    }
    return $decoded;
}

function rvu_event_require_user(PDO $pdo): array {
    $user = rvu_current_user($pdo);
    if (!$user) {
        rvu_event_json(['detail' => 'Your session is invalid. Please sign in again.'], 401);
    }
    return $user;
}

function rvu_event_role_is_admin(?string $role): bool {
    $role = strtolower(trim((string)$role));
    $compact = preg_replace('/[\s_-]+/', '', $role);
    return in_array($compact, ['admin', 'administrator', 'superadmin'], true);
}

function rvu_event_strlen(string $value): int {
    return function_exists('mb_strlen')
        ? mb_strlen($value, 'UTF-8')
        : strlen($value);
}

function rvu_event_substr(string $value, int $start, int $length): string {
    return function_exists('mb_substr')
        ? mb_substr($value, $start, $length, 'UTF-8')
        : substr($value, $start, $length);
}

function rvu_event_can_manage(array $user, ?int $authorId): bool {
    return ($authorId !== null && (int)$user['id'] === $authorId)
        || rvu_event_role_is_admin($user['role'] ?? '');
}

function rvu_ensure_event_social_tables(PDO $pdo): void {
    $pdo->exec("CREATE TABLE IF NOT EXISTS events (
        id BIGSERIAL PRIMARY KEY,
        author_id BIGINT NULL,
        title VARCHAR(180) NULL,
        description TEXT NULL,
        category VARCHAR(80) NULL DEFAULT 'General',
        campus VARCHAR(180) NULL,
        location VARCHAR(255) NULL,
        speakers VARCHAR(500) NULL,
        event_date TIMESTAMPTZ NULL,
        status VARCHAR(30) NULL DEFAULT 'Published',
        is_active BOOLEAN NULL DEFAULT TRUE,
        image_url TEXT NULL,
        created_at TIMESTAMPTZ NULL DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMPTZ NULL DEFAULT CURRENT_TIMESTAMP
    )");

    $alterStatements = [
        "ALTER TABLE events ADD COLUMN IF NOT EXISTS author_id BIGINT NULL",
        "ALTER TABLE events ADD COLUMN IF NOT EXISTS title VARCHAR(180) NULL",
        "ALTER TABLE events ADD COLUMN IF NOT EXISTS description TEXT NULL",
        "ALTER TABLE events ADD COLUMN IF NOT EXISTS category VARCHAR(80) NULL DEFAULT 'General'",
        "ALTER TABLE events ADD COLUMN IF NOT EXISTS campus VARCHAR(180) NULL",
        "ALTER TABLE events ADD COLUMN IF NOT EXISTS location VARCHAR(255) NULL",
        "ALTER TABLE events ADD COLUMN IF NOT EXISTS speakers VARCHAR(500) NULL",
        "ALTER TABLE events ADD COLUMN IF NOT EXISTS event_date TIMESTAMPTZ NULL",
        "ALTER TABLE events ADD COLUMN IF NOT EXISTS status VARCHAR(30) NULL DEFAULT 'Published'",
        "ALTER TABLE events ADD COLUMN IF NOT EXISTS is_active BOOLEAN NULL DEFAULT TRUE",
        "ALTER TABLE events ADD COLUMN IF NOT EXISTS image_url TEXT NULL",
        "ALTER TABLE events ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NULL DEFAULT CURRENT_TIMESTAMP",
        "ALTER TABLE events ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NULL DEFAULT CURRENT_TIMESTAMP"
    ];
    foreach ($alterStatements as $sql) {
        try { $pdo->exec($sql); } catch (Throwable $e) {}
    }

    $pdo->exec("CREATE TABLE IF NOT EXISTS campus_event_media (
        id BIGSERIAL PRIMARY KEY,
        event_id BIGINT NOT NULL,
        media_type VARCHAR(20) NOT NULL,
        media_path TEXT NOT NULL,
        thumbnail_path TEXT NULL,
        size_bytes BIGINT NOT NULL DEFAULT 0,
        position INTEGER NOT NULL DEFAULT 0,
        created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
    )");

    $pdo->exec("CREATE TABLE IF NOT EXISTS campus_event_likes (
        id BIGSERIAL PRIMARY KEY,
        event_id BIGINT NOT NULL,
        user_id BIGINT NOT NULL,
        created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
        CONSTRAINT campus_event_likes_unique UNIQUE(event_id, user_id)
    )");

    $pdo->exec("CREATE TABLE IF NOT EXISTS campus_event_comments (
        id BIGSERIAL PRIMARY KEY,
        event_id BIGINT NOT NULL,
        user_id BIGINT NOT NULL,
        parent_comment_id BIGINT NULL,
        comment TEXT NOT NULL,
        created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
    )");

    $pdo->exec("CREATE TABLE IF NOT EXISTS campus_event_comment_mentions (
        id BIGSERIAL PRIMARY KEY,
        comment_id BIGINT NOT NULL,
        mentioned_user_id BIGINT NOT NULL,
        created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
        CONSTRAINT campus_event_mentions_unique UNIQUE(comment_id, mentioned_user_id)
    )");

    $pdo->exec("CREATE TABLE IF NOT EXISTS campus_event_notifications (
        id BIGSERIAL PRIMARY KEY,
        recipient_user_id BIGINT NOT NULL,
        actor_user_id BIGINT NULL,
        event_id BIGINT NULL,
        comment_id BIGINT NULL,
        type VARCHAR(40) NOT NULL DEFAULT 'general',
        title VARCHAR(180) NOT NULL,
        message VARCHAR(300) NOT NULL,
        is_read BOOLEAN NOT NULL DEFAULT FALSE,
        created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
    )");

    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_events_social_date ON events(event_date DESC)");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_events_social_created ON events(created_at DESC)");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_event_media_event ON campus_event_media(event_id, position)");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_event_comments_event ON campus_event_comments(event_id, created_at)");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_event_comments_parent ON campus_event_comments(parent_comment_id, created_at)");
    $pdo->exec("CREATE INDEX IF NOT EXISTS idx_event_notifications_recipient ON campus_event_notifications(recipient_user_id, is_read, created_at DESC)");
}

function rvu_event_bool($value): bool {
    if (is_bool($value)) return $value;
    if (is_numeric($value)) return (int)$value !== 0;
    return in_array(strtolower(trim((string)$value)), ['1', 'true', 't', 'yes', 'y'], true);
}

function rvu_event_normalize(array $row): array {
    $row['id'] = isset($row['id']) ? (int)$row['id'] : 0;
    $row['author_id'] = isset($row['author_id']) && $row['author_id'] !== null ? (int)$row['author_id'] : 0;
    $row['like_count'] = isset($row['like_count']) ? (int)$row['like_count'] : 0;
    $row['comment_count'] = isset($row['comment_count']) ? (int)$row['comment_count'] : 0;
    $row['liked_by_me'] = rvu_event_bool($row['liked_by_me'] ?? false);
    $row['is_active'] = rvu_event_bool($row['is_active'] ?? true);
    if (isset($row['media']) && is_string($row['media'])) {
        $decoded = json_decode($row['media'], true);
        $row['media'] = is_array($decoded) ? $decoded : [];
    } elseif (!isset($row['media']) || !is_array($row['media'])) {
        $row['media'] = [];
    }
    return $row;
}

function rvu_event_select_sql(): string {
    return "SELECT
        e.id, e.author_id, e.title, e.description, e.category, e.campus, e.location,
        e.speakers, e.event_date, e.status, e.is_active, e.image_url, e.created_at, e.updated_at,
        COALESCE(u.full_name, 'Rockview Events') AS author_name,
        COALESCE(u.role, 'staff') AS author_role,
        COALESCE(u.profile_picture, '') AS author_profile_picture,
        (SELECT COUNT(*) FROM campus_event_likes l WHERE l.event_id = e.id) AS like_count,
        (SELECT COUNT(*) FROM campus_event_comments c WHERE c.event_id = e.id) AS comment_count,
        EXISTS(SELECT 1 FROM campus_event_likes ml WHERE ml.event_id = e.id AND ml.user_id = :viewer_id) AS liked_by_me,
        COALESCE((
            SELECT json_agg(json_build_object(
                'id', m.id,
                'event_id', m.event_id,
                'type', m.media_type,
                'path', m.media_path,
                'thumbnail_path', COALESCE(m.thumbnail_path, ''),
                'size_bytes', m.size_bytes
            ) ORDER BY m.position, m.id)
            FROM campus_event_media m
            WHERE m.event_id = e.id
        ), '[]'::json) AS media
      FROM events e
      LEFT JOIN users u ON u.id = e.author_id";
}

function rvu_event_fetch(PDO $pdo, int $eventId, int $viewerId): ?array {
    $sql = rvu_event_select_sql() . " WHERE e.id = :event_id LIMIT 1";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([':viewer_id' => $viewerId, ':event_id' => $eventId]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    return $row ? rvu_event_normalize($row) : null;
}

function rvu_event_fetch_comment(PDO $pdo, int $commentId): ?array {
    $stmt = $pdo->prepare("SELECT
        c.id, c.event_id, c.user_id, c.parent_comment_id, c.comment, c.created_at,
        u.full_name AS author_name, u.role AS author_role,
        COALESCE(u.profile_picture, '') AS author_profile_picture
      FROM campus_event_comments c
      INNER JOIN users u ON u.id = c.user_id
      WHERE c.id = ? LIMIT 1");
    $stmt->execute([$commentId]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$row) return null;
    $row['id'] = (int)$row['id'];
    $row['event_id'] = (int)$row['event_id'];
    $row['user_id'] = (int)$row['user_id'];
    $row['parent_comment_id'] = $row['parent_comment_id'] !== null ? (int)$row['parent_comment_id'] : null;
    return $row;
}

function rvu_event_fetch_comments(PDO $pdo, int $eventId): array {
    $stmt = $pdo->prepare("SELECT
        c.id, c.event_id, c.user_id, c.parent_comment_id, c.comment, c.created_at,
        u.full_name AS author_name, u.role AS author_role,
        COALESCE(u.profile_picture, '') AS author_profile_picture
      FROM campus_event_comments c
      INNER JOIN users u ON u.id = c.user_id
      WHERE c.event_id = ?
      ORDER BY COALESCE(c.parent_comment_id, c.id) ASC, c.created_at ASC, c.id ASC");
    $stmt->execute([$eventId]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    foreach ($rows as &$row) {
        $row['id'] = (int)$row['id'];
        $row['event_id'] = (int)$row['event_id'];
        $row['user_id'] = (int)$row['user_id'];
        $row['parent_comment_id'] = $row['parent_comment_id'] !== null ? (int)$row['parent_comment_id'] : null;
    }
    unset($row);
    return $rows;
}

function rvu_event_notify(
    PDO $pdo,
    int $recipientUserId,
    ?int $actorUserId,
    ?int $eventId,
    ?int $commentId,
    string $type,
    string $title,
    string $message
): void {
    if ($recipientUserId <= 0) return;
    if ($actorUserId !== null && $recipientUserId === $actorUserId) return;
    $stmt = $pdo->prepare("INSERT INTO campus_event_notifications
        (recipient_user_id, actor_user_id, event_id, comment_id, type, title, message)
        VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([
        $recipientUserId,
        $actorUserId,
        $eventId,
        $commentId,
        rvu_event_substr($type, 0, 40),
        rvu_event_substr($title, 0, 180),
        rvu_event_substr($message, 0, 300),
    ]);
}

function rvu_event_mentions(PDO $pdo, int $eventId): array {
    $stmt = $pdo->prepare('SELECT campus FROM events WHERE id = ? LIMIT 1');
    $stmt->execute([$eventId]);
    $campus = $stmt->fetchColumn();
    if ($campus === false) return [];

    if ($campus !== null && trim((string)$campus) !== '') {
        $stmt = $pdo->prepare("SELECT id, full_name, role, COALESCE(campus, '') AS campus,
            COALESCE(profile_picture, '') AS profile_picture
          FROM users
          WHERE campus = ?
          ORDER BY full_name ASC LIMIT 50");
        $stmt->execute([(string)$campus]);
    } else {
        $stmt = $pdo->query("SELECT id, full_name, role, COALESCE(campus, '') AS campus,
            COALESCE(profile_picture, '') AS profile_picture
          FROM users ORDER BY full_name ASC LIMIT 50");
    }
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    foreach ($rows as &$row) $row['id'] = (int)$row['id'];
    unset($row);
    return $rows;
}
