<?php
// api/club_documents.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'] ?? ''), '/');
    $documentId = ctype_digit($path) ? (int)$path : null;

    if ($method === 'GET') {
        $clubId = (int)($_GET['club_id'] ?? 0);
        if ($clubId <= 0) rvu_club_json(['detail' => 'A valid club_id is required.'], 422);
        rvu_club_require_view($user, rvu_club_fetch($pdo, $clubId));
        $stmt = $pdo->prepare("SELECT d.*, u.full_name AS uploaded_by_name
                              FROM campus_club_documents d
                              LEFT JOIN users u ON u.id = d.uploaded_by
                              WHERE d.club_id = ?
                              ORDER BY d.created_at DESC, d.id DESC");
        $stmt->execute([$clubId]);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        foreach ($rows as &$row) {
            $row['id'] = (int)$row['id'];
            $row['club_id'] = (int)$row['club_id'];
            $row['file_size'] = (int)$row['file_size'];
            unset($row['stored_name'], $row['file_path']);
        }
        rvu_club_json(['data' => $rows]);
    }

    if ($method === 'POST') {
        $clubId = (int)($_POST['club_id'] ?? 0);
        $documentType = rvu_club_clean_text($_POST['document_type'] ?? 'Club Document', 100);
        if ($clubId <= 0) rvu_club_json(['detail' => 'A valid club is required.'], 422);
        rvu_club_require_manage($user, rvu_club_fetch($pdo, $clubId));
        if (!isset($_FILES['documents'])) rvu_club_json(['detail' => 'No documents were selected.'], 422);

        $files = $_FILES['documents'];
        $names = is_array($files['name']) ? $files['name'] : [$files['name']];
        $tmpNames = is_array($files['tmp_name']) ? $files['tmp_name'] : [$files['tmp_name']];
        $errors = is_array($files['error']) ? $files['error'] : [$files['error']];
        $sizes = is_array($files['size']) ? $files['size'] : [$files['size']];
        if (count($names) > 5) rvu_club_json(['detail' => 'Upload at most 5 documents at a time.'], 422);

        $countStmt = $pdo->prepare('SELECT COUNT(*) FROM campus_club_documents WHERE club_id = ?');
        $countStmt->execute([$clubId]);
        $existing = (int)$countStmt->fetchColumn();
        if ($existing + count($names) > 25) {
            rvu_club_json(['detail' => 'A club can store a maximum of 25 documents.'], 422);
        }

        $uploadDir = __DIR__ . '/../uploads/clubs/documents';
        if (!is_dir($uploadDir) && !mkdir($uploadDir, 0775, true) && !is_dir($uploadDir)) {
            throw new RuntimeException('Unable to create the club documents directory.');
        }

        $allowed = [
            'application/pdf' => 'pdf',
            'text/plain' => 'txt',
            'application/msword' => 'doc',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx',
            'application/vnd.ms-excel' => 'xls',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'xlsx',
        ];
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $saved = [];

        for ($i = 0; $i < count($names); $i++) {
            if ((int)$errors[$i] !== UPLOAD_ERR_OK) {
                throw new RuntimeException('One of the selected club documents could not be uploaded.');
            }
            $size = (int)$sizes[$i];
            if ($size <= 0 || $size > 10 * 1024 * 1024) {
                throw new RuntimeException('Each club document must be 10 MB or smaller.');
            }
            $mime = (string)$finfo->file($tmpNames[$i]);
            $ext = $allowed[$mime] ?? null;
            if (!$ext) {
                $originalExt = strtolower(pathinfo((string)$names[$i], PATHINFO_EXTENSION));
                if (in_array($mime, ['application/zip', 'application/octet-stream'], true)
                    && in_array($originalExt, ['docx', 'xlsx'], true)) {
                    $ext = $originalExt;
                    $mime = $originalExt === 'docx'
                        ? 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
                        : 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
                } elseif ($mime === 'application/octet-stream'
                    && in_array($originalExt, ['doc', 'xls'], true)) {
                    $ext = $originalExt;
                    $mime = $originalExt === 'doc' ? 'application/msword' : 'application/vnd.ms-excel';
                }
            }
            if (!$ext) {
                throw new RuntimeException('Only PDF, TXT, DOC, DOCX, XLS and XLSX club documents are allowed.');
            }
            $stored = 'club_' . $clubId . '_' . bin2hex(random_bytes(12)) . '.' . $ext;
            $full = $uploadDir . DIRECTORY_SEPARATOR . $stored;
            if (!move_uploaded_file($tmpNames[$i], $full)) {
                throw new RuntimeException('Unable to save one of the selected club documents.');
            }
            $original = basename((string)$names[$i]);
            $relative = 'uploads/clubs/documents/' . $stored;
            $stmt = $pdo->prepare("INSERT INTO campus_club_documents (
                club_id, uploaded_by, document_type, original_name, stored_name, file_path, mime_type, file_size
              ) VALUES (?, ?, ?, ?, ?, ?, ?, ?) RETURNING id, created_at");
            $stmt->execute([$clubId, (int)$user['id'], $documentType, $original, $stored, $relative, $mime, $size]);
            $created = $stmt->fetch(PDO::FETCH_ASSOC);
            $saved[] = [
                'id' => (int)$created['id'],
                'club_id' => $clubId,
                'document_type' => $documentType,
                'original_name' => $original,
                'mime_type' => $mime,
                'file_size' => $size,
                'uploaded_by_name' => $user['full_name'] ?? 'Rockview Staff',
                'created_at' => $created['created_at'],
            ];
        }
        rvu_club_json(['message' => 'Club documents uploaded.', 'data' => $saved], 201);
    }

    if ($method === 'DELETE' && $documentId !== null) {
        $stmt = $pdo->prepare("SELECT d.*, c.created_by, c.campus, c.status
                              FROM campus_club_documents d
                              INNER JOIN campus_clubs c ON c.id = d.club_id
                              WHERE d.id = ?");
        $stmt->execute([$documentId]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$row) rvu_club_json(['detail' => 'Club document not found.'], 404);
        rvu_club_require_manage($user, $row);
        $pdo->prepare('DELETE FROM campus_club_documents WHERE id = ?')->execute([$documentId]);
        rvu_club_remove_file((string)$row['file_path']);
        rvu_club_json(['message' => 'Club document removed.']);
    }

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