<?php
declare(strict_types=1);

namespace App\Controllers;

require_once BASE_PATH . '/app/helpers/permissions.php';

require_once BASE_PATH . '/app/helpers/conference_scope.php';

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

final class AdminProductionTenantController extends Controller
{
    private function qcols(PDO $db, string $table): array {
        $st=$db->prepare("SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=:t");
        $st->execute([':t'=>$table]);
        return array_map(fn($r)=>$r['COLUMN_NAME'], $st->fetchAll(PDO::FETCH_ASSOC)?:[]);
    }

    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();

        // conferences for this org
        $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));

        // detect columns
        $scols=$this->qcols($db,'submissions');
        $statusCol = in_array('workflow_status',$scols,true) ? 'workflow_status' : (in_array('status',$scols,true) ? 'status' : null);
        $titleEnCol = in_array('title_en',$scols,true) ? 'title_en' : (in_array('title',$scols,true) ? 'title' : null);
        $titleArCol = in_array('title_ar',$scols,true) ? 'title_ar' : null;

        $where="c.org_id=:o";
        $bind=[':o'=>$orgId];

        if($confId>0){ $where.=" AND s.conference_id=:c"; $bind[':c']=$confId; }

        $q=trim((string)($_GET['q'] ?? ''));
        if($q!=='' && $titleEnCol){
            $where.=" AND (s.$titleEnCol LIKE :q".($titleArCol?" OR s.$titleArCol LIKE :q":"").")";
            $bind[':q']="%$q%";
        }

        $status=trim((string)($_GET['status'] ?? ''));
        if($status!=='' && $statusCol){
            $where.=" AND s.$statusCol=:st";
            $bind[':st']=$status;
        }

        $sql="
          SELECT s.*,
                 c.title_en AS conf_title_en, c.title_ar AS conf_title_ar
          FROM submissions s
          JOIN conferences c ON c.id=s.conference_id
          WHERE $where
          ORDER BY s.id DESC
          LIMIT 400
        ";

        $st=$db->prepare($sql);
        $st->execute($bind);
        $rows=$st->fetchAll(PDO::FETCH_ASSOC)?:[];

        $this->view('admin/production/index', [
          'confs'=>$confs,
          'confId'=>$confId,
          'rows'=>$rows,
          'statusCol'=>$statusCol,
          'titleEnCol'=>$titleEnCol,
          'titleArCol'=>$titleArCol,
          'q'=>$q,
          'status'=>$status,
        ]);
    }
}
