<?php

/**
 * FileAccessController
 *
 * Handles admin management of TFE file access requests.
 * - List pending/approved/rejected requests
 * - Approve/reject individual requests
 * - Send notification emails on approval
 */
class FileAccessController
{
    private Database $db;

    public function __construct(Database $db)
    {
        $this->db = $db;
    }

    public static function create(): self
    {
        require_once APP_ROOT . '/src/Database.php';
        return new self(Database::getInstance());
    }

    /**
     * Main admin page handler - lists access requests
     */
    public function handle(): array
    {
        // Get filter parameter
        $status = $_GET['status'] ?? 'pending';
        $page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
        $perPage = 20;
        $offset = ($page - 1) * $perPage;

        // Fetch requests based on filter
        if ($status === 'approved') {
            $requests = $this->getApprovedRequests($perPage, $offset);
            $totalCount = $this->countApprovedRequests();
        } elseif ($status === 'rejected') {
            $requests = $this->getRejectedRequests($perPage, $offset);
            $totalCount = $this->countRejectedRequests();
        } else {
            $requests = $this->db->getPendingAccessRequests($perPage, $offset);
            $totalCount = $this->db->countPendingAccessRequests();
        }

        $totalPages = max(1, ceil($totalCount / $perPage));

        return [
            'requests' => $requests,
            'status' => $status,
            'page' => $page,
            'totalPages' => $totalPages,
            'totalCount' => $totalCount,
            'pendingCount' => $this->db->countPendingAccessRequests(),
            'approvedCount' => $this->countApprovedRequests(),
            'rejectedCount' => $this->countRejectedRequests(),
            'currentPage' => 'file-access',
        ];
    }

    private function getApprovedRequests(int $limit, int $offset): array
    {
        $sql = "
            SELECT
                far.id,
                far.email,
                far.justification,
                far.created_at,
                far.approved_at,
                t.id as thesis_id,
                t.title,
                t.subtitle,
                a.name as authors,
                t.year
            FROM file_access_requests far
            JOIN theses t ON far.thesis_id = t.id
            LEFT JOIN thesis_authors ta ON t.id = ta.thesis_id
            LEFT JOIN authors a ON ta.author_id = a.id AND ta.author_order = 1
            WHERE far.status = 'approved'
            ORDER BY far.approved_at DESC
            LIMIT ? OFFSET ?
        ";

        $stmt = $this->db->getPDO()->prepare($sql);
        $stmt->execute([$limit, $offset]);
        return $stmt->fetchAll();
    }

    private function countApprovedRequests(): int
    {
        $stmt = $this->db->getPDO()->query(
            "SELECT COUNT(*) as count FROM file_access_requests WHERE status = 'approved'"
        );
        $result = $stmt->fetch();
        return (int)$result['count'];
    }

    private function getRejectedRequests(int $limit, int $offset): array
    {
        $sql = "
            SELECT
                far.id,
                far.email,
                far.justification,
                far.admin_notes,
                far.created_at,
                far.approved_at,
                t.id as thesis_id,
                t.title,
                t.subtitle,
                a.name as authors,
                t.year
            FROM file_access_requests far
            JOIN theses t ON far.thesis_id = t.id
            LEFT JOIN thesis_authors ta ON t.id = ta.thesis_id
            LEFT JOIN authors a ON ta.author_id = a.id AND ta.author_order = 1
            WHERE far.status = 'rejected'
            ORDER BY far.approved_at DESC
            LIMIT ? OFFSET ?
        ";

        $stmt = $this->db->getPDO()->prepare($sql);
        $stmt->execute([$limit, $offset]);
        return $stmt->fetchAll();
    }

    private function countRejectedRequests(): int
    {
        $stmt = $this->db->getPDO()->query(
            "SELECT COUNT(*) as count FROM file_access_requests WHERE status = 'rejected'"
        );
        $result = $stmt->fetch();
        return (int)$result['count'];
    }
}
