<?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;

final class AdminHomepageController extends Controller
{
    private function tableExists($db, string $t): bool {
        $st=$db->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name=:t");
        $st->execute([':t'=>$t]);
        return (int)$st->fetchColumn()>0;
    }

    private function ensureTables($db): void
    {
        if(!$this->tableExists($db,'conference_homepage_blocks')) throw new \RuntimeException("conference_homepage_blocks table missing");
        if(!$this->tableExists($db,'conferences')) throw new \RuntimeException("conferences table missing");
    }

    private function confLabelCol($db): string
    {
        $st=$db->query("SELECT column_name FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='conferences'");
        $cols=$st->fetchAll()?:[];
        $names=array_map(fn($r)=>(string)($r['column_name']??''),$cols);

        foreach(['name','title','title_en','conf_name','conference_name','code'] as $c){
            if(in_array($c,$names,true)) return $c;
        }
        return 'id';
    }

    private function confId(): int
    {
        if(function_exists('default_conference_id')){
            $d=(int)default_conference_id();
            if($d>0) return $d;
        }
        $q=(int)($_GET['conference_id']??0);
        return $q>0?$q:0;
    }

    public function index(): void
    {
        require_admin_area();
        $db=Database::getInstance();
        $this->ensureTables($db);

        $conference_id=$this->confId();
        if($conference_id<=0){
            $conference_id=(int)$db->query("SELECT id FROM conferences ORDER BY id DESC LIMIT 1")->fetchColumn();
        }

        $labelCol=$this->confLabelCol($db);
        $sql="SELECT id, ".$labelCol." AS label, is_active FROM conferences ORDER BY id DESC";
        $confs=$db->query($sql)->fetchAll()?:[];

        $st=$db->prepare("SELECT * FROM conference_homepage_blocks WHERE conference_id=:c ORDER BY sort_order ASC,id ASC");
        $st->execute([':c'=>$conference_id]);
        $rows=$st->fetchAll()?:[];

        $edit=null;
        $eid=(int)($_GET['edit']??0);
        if($eid>0){
            $st=$db->prepare("SELECT * FROM conference_homepage_blocks WHERE id=:id LIMIT 1");
            $st->execute([':id'=>$eid]);
            $edit=$st->fetch()?:null;
        }

        $this->view('admin/homepage/index', compact('conference_id','confs','rows','edit'));
    }
}
