<?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 AdminTracksController extends Controller
{
    
private function firstActiveConferenceId($db): int
{
    try {

        return (int)(
            $db->query("
                SELECT id
                FROM conferences
                WHERE is_active = 1
                ORDER BY id DESC
                LIMIT 1
            ")->fetchColumn()

            ?: 0
        );

    } catch (\Throwable $e) {

        return 0;
    }
}

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

        if (!can_admin() && !can_chair()) { http_response_code(403); echo "Forbidden"; return; }

        $db = Database::getInstance();
        $cid = (int)($_GET['conference_id'] ?? 0);
        if ($cid <= 0 && function_exists('default_conference_id')) $cid = (int)default_conference_id();
        if ($cid <= 0) $cid = $this->firstActiveConferenceId($db);

        $confs = $db->query("SELECT id,title_en,title_ar,is_active FROM conferences WHERE org_id=".(int)$orgId."  ORDER BY id DESC")->fetchAll();

        $rows = [];
        if ($cid > 0) {
           // $st = $db->prepare("SELECT * FROM tracks WHERE conference_id=:c AND  AND org_id = :org_id ".org_conf_in_sql("conference_id")." AND conference_id IN (SELECT id FROM conferences WHERE org_id=".(int)$orgId.")  ORDER BY id DESC");

$st = $db->prepare("
    SELECT *
    FROM tracks
    WHERE conference_id = :c
    ORDER BY
        is_active DESC,
        id DESC
");            

$st->execute([':c'=>$cid, ':org_id' => $orgId]);
            $rows = $st->fetchAll();
        }

        $this->view('admin/tracks/index', ['rows'=>$rows, 'conference_id'=>$cid, 'confs'=>$confs]);
    }

    public function store(): void
    {
        require_login();
        if (!can_admin() && !can_chair()) { http_response_code(403); echo "Forbidden"; return; }
        csrf_check();

        $db = Database::getInstance();
        $cid = (int)($_POST['conference_id'] ?? 0);
        $en = trim((string)($_POST['name_en'] ?? ''));
        $ar = trim((string)($_POST['name_ar'] ?? ''));
        $code = trim((string)($_POST['code'] ?? ''));

        if ($cid<=0 || $en==='' || $ar==='') {
            header('Location: '.base_path('admin/tracks?conference_id='.$cid)); exit;
        }

        $db->prepare("INSERT INTO tracks(conference_id,name_en,name_ar,code,is_active) VALUES(:c,:en,:ar,:code,1)")
           ->execute([':c'=>$cid, ':en'=>$en, ':ar'=>$ar, ':code'=>($code?:null)]);

        header('Location: '.base_path('admin/tracks?conference_id='.$cid)); exit;
    }

    public function toggle(): void
    {
        require_login();
        if (!can_admin() && !can_chair()) { http_response_code(403); echo "Forbidden"; return; }
        csrf_check();

        $db = Database::getInstance();
        $id  = (int)($_POST['id'] ?? 0);
        $cid = (int)($_POST['conference_id'] ?? 0);

        $st = $db->prepare("SELECT is_active FROM tracks WHERE id=:id AND conference_id IN (SELECT id FROM conferences WHERE org_id=".(int)$orgId.")  LIMIT 1");
        $st->execute([':id'=>$id, ':org_id' => $orgId]);
        $cur = (int)($st->fetchColumn() ?? 1);

        $db->prepare("UPDATE tracks SET is_active=:v WHERE id=:id")->execute([':v'=>($cur?0:1), ':id'=>$id]);
        header('Location: '.base_path('admin/tracks?conference_id='.$cid)); exit;
    }
}
