<?php
// api/club_registry.php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/club_common.php';

try {
    rvu_ensure_club_tables($pdo);
    $user = rvu_club_require_user($pdo);
    $method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');
    $path = trim((string)($_SERVER['PATH_INFO'] ?? ''), '/');
    $clubId = ctype_digit($path) ? (int)$path : null;
    $isAdmin = rvu_club_role_is_admin($user['role'] ?? '');

    if ($method === 'GET' && $clubId !== null) {
        $club = rvu_club_fetch($pdo, $clubId);
        $club = rvu_club_require_view($user, $club);
        rvu_club_json($club);
    }

    if ($method === 'GET') {
        $status = strtolower(trim((string)($_GET['status'] ?? 'active')));
        $scope = strtolower(trim((string)($_GET['scope'] ?? 'directory')));
        $campus = trim((string)($_GET['campus'] ?? ''));
        $category = trim((string)($_GET['category'] ?? ''));
        $query = trim((string)($_GET['q'] ?? ''));
        $limit = min(300, max(1, (int)($_GET['limit'] ?? 200)));

        $where = [];
        $params = [];

        if (!$isAdmin) {
            $userCampus = trim((string)($user['campus'] ?? ''));
            if ($userCampus === '') {
                rvu_club_json(['detail' => 'Your staff account is not assigned to a campus. Contact administration.'], 422);
            }
            if ($scope === 'my_submissions') {
                $where[] = 'c.created_by = ?';
                $params[] = (int)$user['id'];
            } else {
                $where[] = 'LOWER(c.campus) = LOWER(?)';
                $params[] = $userCampus;
                $where[] = "c.status = 'active'";
            }
        } else {
            if ($scope === 'my_submissions') {
                $where[] = 'c.created_by = ?';
                $params[] = (int)$user['id'];
            }
            if ($campus !== '') {
                $where[] = 'LOWER(c.campus) = LOWER(?)';
                $params[] = $campus;
            }
            if ($status !== '' && $status !== 'all') {
                if (!in_array($status, ['pending','active','rejected','inactive'], true)) {
                    $status = 'active';
                }
                $where[] = 'c.status = ?';
                $params[] = $status;
            }
        }

        // Staff my-submissions can filter status too.
        if (!$isAdmin && $scope === 'my_submissions' && $status !== '' && $status !== 'all') {
            if (in_array($status, ['pending','active','rejected','inactive'], true)) {
                $where[] = 'c.status = ?';
                $params[] = $status;
            }
        }

        if ($category !== '') {
            $where[] = 'c.category = ?';
            $params[] = $category;
        }
        if ($query !== '') {
            $where[] = '(c.name ILIKE ? OR c.acronym ILIKE ? OR c.category ILIKE ? OR c.purpose ILIKE ? OR c.description ILIKE ? OR c.patron_name ILIKE ?)';
            $like = '%' . $query . '%';
            for ($i = 0; $i < 6; $i++) $params[] = $like;
        }

        $whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';
        $countStmt = $pdo->prepare("SELECT COUNT(*) FROM campus_clubs c $whereSql");
        $countStmt->execute($params);
        $total = (int)$countStmt->fetchColumn();

        $sql = "SELECT
            c.*,
            u.full_name AS creator_name,
            u.role AS creator_role,
            u.profile_picture AS creator_profile_picture,
            COALESCE((SELECT COUNT(*) FROM campus_club_members m WHERE m.club_id = c.id AND m.status = 'active'), 0) AS member_count,
            COALESCE((SELECT COUNT(*) FROM campus_club_documents d WHERE d.club_id = c.id), 0) AS document_count
          FROM campus_clubs c
          LEFT JOIN users u ON u.id = c.created_by
          $whereSql
          ORDER BY c.campus ASC, c.name ASC, c.created_at DESC
          LIMIT $limit";
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        foreach ($rows as &$row) {
            $row['id'] = (int)$row['id'];
            $row['created_by'] = (int)$row['created_by'];
            $row['member_count'] = (int)$row['member_count'];
            $row['document_count'] = (int)$row['document_count'];
        }
        rvu_club_json(['data' => $rows, 'total' => $total]);
    }

    if ($method === 'POST') {
        $input = rvu_club_input();
        $name = rvu_club_clean_text($input['name'] ?? '', 180);
        $acronym = rvu_club_clean_text($input['acronym'] ?? '', 40);
        $category = rvu_club_clean_text($input['category'] ?? 'Other', 100);
        $purpose = rvu_club_clean_text($input['purpose'] ?? '', 3000);
        $description = rvu_club_clean_text($input['description'] ?? '', 8000);
        $patron = rvu_club_clean_text($input['patron_name'] ?? '', 180);
        $email = rvu_club_clean_text($input['contact_email'] ?? '', 180);
        $phone = rvu_club_clean_text($input['contact_phone'] ?? '', 80);
        $schedule = rvu_club_clean_text($input['meeting_schedule'] ?? '', 220);
        $venue = rvu_club_clean_text($input['meeting_venue'] ?? '', 220);

        if ($name === '') rvu_club_json(['detail' => 'Club name is required.'], 422);
        if ($purpose === '') rvu_club_json(['detail' => 'State the purpose of the club.'], 422);

        if ($isAdmin) {
            $campus = rvu_club_clean_text($input['campus'] ?? ($user['campus'] ?? ''), 180);
        } else {
            $campus = trim((string)($user['campus'] ?? ''));
        }
        if ($campus === '') {
            rvu_club_json(['detail' => 'A campus is required. Staff campus is taken from the signed-in account.'], 422);
        }

        $dup = $pdo->prepare("SELECT id FROM campus_clubs WHERE LOWER(name) = LOWER(?) AND LOWER(campus) = LOWER(?) AND status <> 'rejected' LIMIT 1");
        $dup->execute([$name, $campus]);
        if ($dup->fetchColumn()) {
            rvu_club_json(['detail' => 'A club with this name already exists at this campus.'], 409);
        }

        $status = $isAdmin ? 'active' : 'pending';
        $approvedBy = $isAdmin ? (int)$user['id'] : null;
        $approvedAt = $isAdmin ? date('Y-m-d H:i:sP') : null;

        $stmt = $pdo->prepare("INSERT INTO campus_clubs (
            created_by, name, acronym, category, purpose, description, campus,
            patron_name, contact_email, contact_phone, meeting_schedule, meeting_venue,
            status, approved_by, approved_at
          ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id");
        $stmt->execute([
            (int)$user['id'], $name, $acronym, $category, $purpose, $description, $campus,
            $patron, $email, $phone, $schedule, $venue, $status, $approvedBy, $approvedAt
        ]);
        $newId = (int)$stmt->fetchColumn();
        $club = rvu_club_fetch($pdo, $newId);
        rvu_club_json(['message' => $isAdmin ? 'Club created and activated.' : 'Club submitted for administration approval.', 'data' => $club], 201);
    }

    if ($method === 'PUT' && $clubId !== null) {
        $club = rvu_club_require_manage($user, rvu_club_fetch($pdo, $clubId));
        $input = rvu_club_input();

        $fields = [];
        $params = [];
        $allowed = [
            'name' => 180,
            'acronym' => 40,
            'category' => 100,
            'purpose' => 3000,
            'description' => 8000,
            'patron_name' => 180,
            'contact_email' => 180,
            'contact_phone' => 80,
            'meeting_schedule' => 220,
            'meeting_venue' => 220,
        ];
        foreach ($allowed as $field => $max) {
            if (array_key_exists($field, $input)) {
                $value = rvu_club_clean_text($input[$field], $max);
                if ($field === 'name' && $value === '') rvu_club_json(['detail' => 'Club name cannot be empty.'], 422);
                if ($field === 'purpose' && $value === '') rvu_club_json(['detail' => 'Club purpose cannot be empty.'], 422);
                $fields[] = "$field = ?";
                $params[] = $value;
            }
        }
        if ($isAdmin && array_key_exists('campus', $input)) {
            $newCampus = rvu_club_clean_text($input['campus'], 180);
            if ($newCampus === '') rvu_club_json(['detail' => 'Campus cannot be empty.'], 422);
            $fields[] = 'campus = ?';
            $params[] = $newCampus;
        }
        if (!$fields) rvu_club_json(['detail' => 'No editable fields were provided.'], 422);
        $fields[] = 'updated_at = CURRENT_TIMESTAMP';
        $params[] = $clubId;
        $pdo->prepare('UPDATE campus_clubs SET ' . implode(', ', $fields) . ' WHERE id = ?')->execute($params);
        rvu_club_json(['message' => 'Club updated.', 'data' => rvu_club_fetch($pdo, $clubId)]);
    }

    if ($method === 'PATCH' && $clubId !== null) {
        if (!$isAdmin) rvu_club_json(['detail' => 'Administrator access is required for club approvals.'], 403);
        $club = rvu_club_fetch($pdo, $clubId);
        if (!$club) rvu_club_json(['detail' => 'Club not found.'], 404);
        $input = rvu_club_input();
        $action = strtolower(trim((string)($input['action'] ?? '')));
        $reason = rvu_club_clean_text($input['reason'] ?? '', 2000);

        if ($action === 'approve' || $action === 'activate') {
            $stmt = $pdo->prepare("UPDATE campus_clubs SET status = 'active', rejection_reason = NULL, approved_by = ?, approved_at = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
            $stmt->execute([(int)$user['id'], $clubId]);
        } elseif ($action === 'reject') {
            if ($reason === '') rvu_club_json(['detail' => 'Provide a reason for rejecting the club registration.'], 422);
            $stmt = $pdo->prepare("UPDATE campus_clubs SET status = 'rejected', rejection_reason = ?, approved_by = ?, approved_at = NULL, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
            $stmt->execute([$reason, (int)$user['id'], $clubId]);
        } elseif ($action === 'deactivate') {
            $stmt = $pdo->prepare("UPDATE campus_clubs SET status = 'inactive', updated_at = CURRENT_TIMESTAMP WHERE id = ?");
            $stmt->execute([$clubId]);
        } else {
            rvu_club_json(['detail' => 'Unsupported moderation action.'], 422);
        }
        rvu_club_json(['message' => 'Club status updated.', 'data' => rvu_club_fetch($pdo, $clubId)]);
    }

    if ($method === 'DELETE' && $clubId !== null) {
        $club = rvu_club_require_manage($user, rvu_club_fetch($pdo, $clubId));
        $docStmt = $pdo->prepare('SELECT file_path FROM campus_club_documents WHERE club_id = ?');
        $docStmt->execute([$clubId]);
        $paths = $docStmt->fetchAll(PDO::FETCH_COLUMN);
        $pdo->prepare('DELETE FROM campus_clubs WHERE id = ?')->execute([$clubId]);
        foreach ($paths as $path) rvu_club_remove_file((string)$path);
        rvu_club_json(['message' => 'Club deleted.']);
    }

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