<?php
namespace App\Controllers;

use App\Core\Database;

class AdminOrganizationController
{
    private function requireAccess(): void
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        if (empty($_SESSION['user_id'])) {
            header("Location: /easychair/login");
            exit;
        }

        $role = $_SESSION['role'] ?? $_SESSION['user_role'] ?? '';

        if (!in_array($role, ['super_admin','org_admin'], true)) {
            http_response_code(403);
            exit("Access denied.");
        }
    }

    public function index()
    {
        $this->requireAccess();

        $db = Database::getInstance();

        $role = $_SESSION['role'] ?? '';
        $orgId = (int)($_SESSION['org_id'] ?? 0);

        if ($role === 'super_admin') {
            $stmt = $db->query("
                SELECT 
                    o.*,
                    COUNT(DISTINCT c.id) AS conferences_count,
                    COUNT(DISTINCT u.id) AS users_count,
                    MAX(p.conference_id) AS current_conference_id
                FROM organizations o
                LEFT JOIN conferences c ON c.org_id = o.id
                LEFT JOIN users u ON u.org_id = o.id
                LEFT JOIN org_conference_policy p ON p.org_id = o.id
                GROUP BY o.id
                ORDER BY o.id DESC
            ");
            $organizations = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        } else {
            $stmt = $db->prepare("
                SELECT 
                    o.*,
                    COUNT(DISTINCT c.id) AS conferences_count,
                    COUNT(DISTINCT u.id) AS users_count,
                    MAX(p.conference_id) AS current_conference_id
                FROM organizations o
                LEFT JOIN conferences c ON c.org_id = o.id
                LEFT JOIN users u ON u.org_id = o.id
                LEFT JOIN org_conference_policy p ON p.org_id = o.id
                WHERE o.id = ?
                GROUP BY o.id
            ");
            $stmt->execute([$orgId]);
            $organizations = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        }

        ob_start();
        require BASE_PATH . '/app/views/admin/organizations/index.php';
        $content = ob_get_clean();

        require BASE_PATH . '/app/views/layouts/admin_layout.php';
    }
}
