<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Database;
use PDO;

final class AdminGalleyTenantController extends Controller
{
    private function requireTenant(): array {
        require_admin_or_chair_tenant();
        require_org_context();
        $db=Database::getInstance();
        $orgId=(int)current_org_id();
        return [$db,$orgId];
    }

    public function index(): void
    {
        [$db,$orgId]=$this->requireTenant();

        $st=$db->prepare("SELECT id,title_en,title_ar FROM conferences WHERE org_id=:o ORDER BY id DESC");
        $st->execute([':o'=>$orgId]);
        $confs=$st->fetchAll(PDO::FETCH_ASSOC)?:[];
        $confId=(int)($_GET['conference_id'] ?? ($confs[0]['id'] ?? 0));

        // show camera-ready / galley files from submission_files if exists, else only list submissions
        $filesExist = false;
        $st=$db->prepare("SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='submission_files'");
        $st->execute();
        $filesExist = ((int)$st->fetchColumn()>0);

        $files=[];
        if($filesExist && $confId>0){
            $st=$db->prepare("
              SELECT f.*, s.id AS submission_id
              FROM submission_files f
              JOIN submissions s ON s.id=f.submission_id
              JOIN conferences c ON c.id=s.conference_id
              WHERE c.org_id=:o AND s.conference_id=:c
              ORDER BY f.id DESC
              LIMIT 500
            ");
            $st->execute([':o'=>$orgId,':c'=>$confId]);
            $files=$st->fetchAll(PDO::FETCH_ASSOC)?:[];
        }

        $this->view('admin/galley/index', compact('confs','confId','files','filesExist'));
    }
}
