<?php
declare(strict_types=1);

namespace App\Controllers;

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

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

final class SubmissionsController extends Controller
{
    private function cols(string $table): array
    {
        $db = Database::getInstance();
        $st = $db->prepare("SELECT column_name FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name=:t");
        $st->execute([':t'=>$table, ':org_id' => $orgId]);
        return array_map(fn($r)=>$r['column_name'], $st->fetchAll() ?: []);
    }

    private function pick(array $cols, array $cands, ?string $fallback=null): string
    {
        $set = array_flip($cols);
        foreach ($cands as $c) if (isset($set[$c])) return $c;
        return $fallback ?: $cols[0] ?? 'id';
    }

    public function index(): void
    {
        require_login();
        $orgId = (int) current_org_id();

        $db = Database::getInstance();

        $scols = $this->cols('submissions');
        $titleEn = $this->pick($scols, ['title_en','paper_title_en','title','paper_title','name','subject'], 'id');
        $titleAr = $this->pick($scols, ['title_ar','paper_title_ar','name_ar','subject_ar',$titleEn], $titleEn);
        $status  = $this->pick($scols, ['status'], 'id');
        $created = $this->pick($scols, ['created_at'], 'id');
        $confId  = $this->pick($scols, ['conference_id'], null);

        $sql = "
          SELECT s.id,
                 s.$titleEn AS title_en,
                 s.$titleAr AS title_ar,
                 s.$status  AS status,
                 s.$created AS created_at,
                 c.title_en AS conf_title_en,
                 c.title_ar AS conf_title_ar
          FROM submissions s
          LEFT JOIN conferences c ON c.id = s.$confId
          WHERE conference_id IN (SELECT id FROM conferences WHERE org_id=".(int)$orgId.")  ORDER BY s.id DESC
          LIMIT 500
        ";
        $rows = $db->query($sql)->fetchAll();

        $this->view('author/index', ['rows'=>$rows, 'filesMap'=>[]]);
    }
}
