<?php
declare(strict_types=1);

namespace App\Controllers;

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

final class AdminTracksTenantController extends Controller
{
    private function confOr404($db, int $orgId, int $confId): array {
        $st=$db->prepare("SELECT id,title_en,title_ar FROM conferences WHERE id=:id AND org_id=:o LIMIT 1");
        $st->execute([':id'=>$confId,':o'=>$orgId]);
        $r=$st->fetch();
        if(!$r){ http_response_code(404); echo "Conference not found"; exit; }
        return $r;
    }

    public function index(): void
    {
        require_admin_or_chair();
        require_org_context();

        $db=Database::getInstance();
        $orgId=(int)current_org_id();

        $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()?:[];

        $confId=(int)($_GET['conference_id']??($confs[0]['id']??0));
        $conf = $confId>0 ? $this->confOr404($db,$orgId,$confId) : null;

        $st=$db->prepare("SELECT * FROM tracks WHERE conference_id=:c AND (org_id=:o OR org_id IS NULL) ORDER BY id DESC");
        $st->execute([':c'=>$confId,':o'=>$orgId]);
        $rows=$st->fetchAll()?:[];

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

    public function save(): void
    {
        require_admin_or_chair();
        require_org_context();
        if(($_SERVER['REQUEST_METHOD']??'GET')!=='POST'){ http_response_code(405); return; }

        $db=Database::getInstance();
        $orgId=(int)current_org_id();

        $confId=(int)($_POST['conference_id']??0);
        $this->confOr404($db,$orgId,$confId);

        $id=(int)($_POST['id']??0);
        $nameAr=trim((string)($_POST['name_ar']??''));
        $nameEn=trim((string)($_POST['name_en']??''));
        if($nameAr==='' || $nameEn===''){
            if(function_exists('flash_set')) flash_set('danger','Track name AR/EN required');
            header('Location: '.base_path('admin/tracks?conference_id='.$confId)); exit;
        }

        $descAr=(string)($_POST['description_ar']??'');
        $descEn=(string)($_POST['description_en']??'');
        $minR=(int)($_POST['min_reviewers']??2);
        $maxR=(int)($_POST['max_reviewers']??3);
        if($minR<1) $minR=1;
        if($maxR<$minR) $maxR=$minR;

        $chairId=(int)($_POST['chair_user_id']??0);
        $active=(int)($_POST['is_active']??1)?1:0;

        if($id>0){
            // ensure ownership by org via conference join
            $st=$db->prepare("
              SELECT t.id FROM tracks t
              JOIN conferences c ON c.id=t.conference_id
              WHERE t.id=:id AND c.org_id=:o
              LIMIT 1
            ");
            $st->execute([':id'=>$id,':o'=>$orgId]);
            if(!(int)$st->fetchColumn()){ http_response_code(404); echo "Not found"; exit; }

            $db->prepare("
              UPDATE tracks
              SET chair_user_id=:ch, name_ar=:na, name_en=:ne,
                  description_ar=:da, description_en=:de,
                  min_reviewers=:minr, max_reviewers=:maxr,
                  is_active=:ia, org_id=:org
              WHERE id=:id
            ")->execute([
              ':ch'=>($chairId>0?$chairId:null),
              ':na'=>$nameAr,':ne'=>$nameEn,
              ':da'=>($descAr!==''?$descAr:null),
              ':de'=>($descEn!==''?$descEn:null),
              ':minr'=>$minR,':maxr'=>$maxR,':ia'=>$active,
              ':org'=>$orgId,':id'=>$id
            ]);
        } else {
            $db->prepare("
              INSERT INTO tracks (conference_id, chair_user_id, name_ar, name_en, description_ar, description_en, max_reviewers, min_reviewers, is_active, org_id)
              VALUES (:c,:ch,:na,:ne,:da,:de,:maxr,:minr,:ia,:org)
            ")->execute([
              ':c'=>$confId,
              ':ch'=>($chairId>0?$chairId:null),
              ':na'=>$nameAr,':ne'=>$nameEn,
              ':da'=>($descAr!==''?$descAr:null),
              ':de'=>($descEn!==''?$descEn:null),
              ':maxr'=>$maxR,':minr'=>$minR,':ia'=>$active,
              ':org'=>$orgId
            ]);
        }

        if(function_exists('flash_set')) flash_set('success','Saved');
        header('Location: '.base_path('admin/tracks?conference_id='.$confId)); exit;
    }

    public function delete(): void
    {
        require_admin_or_chair();
        require_org_context();
        $db=Database::getInstance();
        $orgId=(int)current_org_id();

        $id=(int)($_GET['id']??0);
        $st=$db->prepare("
          SELECT t.id,t.conference_id,c.org_id
          FROM tracks t
          JOIN conferences c ON c.id=t.conference_id
          WHERE t.id=:id LIMIT 1
        ");
        $st->execute([':id'=>$id]);
        $r=$st->fetch();
        if(!$r || (int)$r['org_id']!==$orgId){ http_response_code(404); echo "Not found"; exit; }

        $db->prepare("DELETE FROM tracks WHERE id=:id")->execute([':id'=>$id]);
        header('Location: '.base_path('admin/tracks?conference_id='.(int)$r['conference_id'])); exit;
    }
}
