<?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 AdminConferencesTenantController extends Controller
{
    private function slugify(string $txt): string {
        $txt = trim(mb_strtolower($txt));
        $txt = preg_replace('/[\s\_]+/u','-',$txt);
        $txt = preg_replace('/[^\p{L}\p{N}\-]+/u','',$txt);
        $txt = preg_replace('/\-+/','-',$txt);
        $txt = trim($txt,'-');
        return $txt !== '' ? $txt : ('conf-'.date('YmdHis'));
    }

    private function confOr404($db, int $orgId, int $id): array {
        $st=$db->prepare("SELECT * FROM conferences WHERE id=:id AND org_id=:o LIMIT 1");
        $st->execute([':id'=>$id,':o'=>$orgId]);
        $row=$st->fetch();
        if(!$row){ http_response_code(404); echo "Not found"; exit; }
        return $row;
    }

    public function index(): void {
        require_admin_or_chair(); require_org_context();
        $db=Database::getInstance(); $orgId=(int)current_org_id();
        $q=trim((string)($_GET['q']??''));
        $params=[':o'=>$orgId];
        $where="WHERE org_id=:o";
        if($q!==''){
          $where.=" AND (title_en LIKE :q OR title_ar LIKE :q OR slug LIKE :q OR short_name LIKE :q)";
          $params[':q']='%'.$q.'%';
        }
        $st=$db->prepare("SELECT * FROM conferences $where ORDER BY id DESC");
        $st->execute($params);
        $rows=$st->fetchAll()?:[];
        $this->view('admin/conferences/index',['rows'=>$rows,'q'=>$q]);
    }

    public function create(): void {
        require_admin_or_chair(); require_org_context();
        $this->view('admin/conferences/form',['row'=>null]);
    }

    public function edit(): void {
        require_admin_or_chair(); require_org_context();
        $db=Database::getInstance(); $orgId=(int)current_org_id();
        $id=(int)($_GET['id']??0);
        $row=$this->confOr404($db,$orgId,$id);
        $this->view('admin/conferences/form',['row'=>$row]);
    }

    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();
        $id=(int)($_POST['id']??0);

        $titleEn=trim((string)($_POST['title_en']??''));
        $titleAr=trim((string)($_POST['title_ar']??''));
        $baseTitle=$titleEn!==''?$titleEn:$titleAr;
        if($baseTitle===''){
          if(function_exists('flash_set')) flash_set('danger','Title required');
          header('Location: '.base_path('admin/conferences')); exit;
        }

        // Required by schema: slug + short_name (NOT NULL) :contentReference[oaicite:1]{index=1}
        $slug=trim((string)($_POST['slug']??''));
        if($slug==='') $slug=$this->slugify($baseTitle);

        $short=trim((string)($_POST['short_name']??''));
        if($short==='') {
          $short=$this->slugify($baseTitle);
          if(mb_strlen($short)>100) $short=mb_substr($short,0,100);
        }

        // ensure unique slug within org
        $try=0;
        while($try<30){
          $st=$db->prepare("SELECT COUNT(*) FROM conferences WHERE org_id=:o AND slug=:s".($id>0?" AND id<>:id":""));
          $p=[':o'=>$orgId,':s'=>$slug];
          if($id>0) $p[':id']=$id;
          $st->execute($p);
          if((int)$st->fetchColumn()===0) break;
          $try++; $slug=$slug.'-'.($try+1);
        }

        // optional fields that DO exist in your schema :contentReference[oaicite:2]{index=2}
        $locationEn=trim((string)($_POST['location_en']??''));
        $locationAr=trim((string)($_POST['location_ar']??''));
        $venueEn=trim((string)($_POST['venue_en']??''));
        $venueAr=trim((string)($_POST['venue_ar']??''));
        $website=trim((string)($_POST['website_url']??''));
        $briefEn=(string)($_POST['brief_en']??'');
        $briefAr=(string)($_POST['brief_ar']??'');
        $themeEn=(string)($_POST['theme_en']??'');
        $themeAr=(string)($_POST['theme_ar']??'');
        $cfpEn=(string)($_POST['cfp_en']??'');
        $cfpAr=(string)($_POST['cfp_ar']??'');
        $status=trim((string)($_POST['status']??'draft'));
        $isActive=(int)($_POST['is_active']??1)?1:0;
        $showHome=(int)($_POST['show_on_homepage']??1)?1:0;

        $date = fn($k)=>(($v=trim((string)($_POST[$k]??'')))!==''?$v:null);

        if($id>0){
          $this->confOr404($db,$orgId,$id);
          $db->prepare("
            UPDATE conferences SET
              slug=:slug, short_name=:short,
              title_en=:te, title_ar=:ta,
              brief_en=:be, brief_ar=:ba,
              theme_en=:thE, theme_ar=:thA,
              cfp_en=:cfE, cfp_ar=:cfA,
              location_en=:locE, location_ar=:locA,
              venue_en=:venE, venue_ar=:venA,
              website_url=:web,
              start_date=:sd, end_date=:ed,
              submission_open_date=:sod, submission_deadline=:sdl,
              review_deadline=:rdl, camera_ready_deadline=:crd,
              status=:st, is_active=:ia, show_on_homepage=:sh
            WHERE id=:id AND org_id=:o
          ")->execute([
            ':slug'=>$slug,':short'=>$short,
            ':te'=>$titleEn,':ta'=>$titleAr,
            ':be'=>$briefEn,':ba'=>$briefAr,
            ':thE'=>$themeEn,':thA'=>$themeAr,
            ':cfE'=>$cfpEn,':cfA'=>$cfpAr,
            ':locE'=>$locationEn,':locA'=>$locationAr,
            ':venE'=>$venueEn,':venA'=>$venueAr,
            ':web'=>$website,
            ':sd'=>$date('start_date'),':ed'=>$date('end_date'),
            ':sod'=>$date('submission_open_date'),':sdl'=>$date('submission_deadline'),
            ':rdl'=>$date('review_deadline'),':crd'=>$date('camera_ready_deadline'),
            ':st'=>$status,':ia'=>$isActive,':sh'=>$showHome,
            ':id'=>$id,':o'=>$orgId
          ]);
        } else {
          $db->prepare("
            INSERT INTO conferences
              (org_id, slug, title_ar, title_en, short_name,
               brief_en, brief_ar, theme_en, theme_ar,
               review_instructions_en, review_instructions_ar,
               description_ar, description_en, cfp_ar, cfp_en,
               location_ar, location_en, venue_en, venue_ar,
               start_date, end_date, submission_open_date, submission_deadline,
               review_deadline, camera_ready_deadline, website_url,
               status, is_active, show_on_homepage)
            VALUES
              (:o,:slug,:ta,:te,:short,
               :be,:ba,:thE,:thA,
               NULL,NULL,
               NULL,NULL,:cfA,:cfE,
               :locA,:locE,:venE,:venA,
               :sd,:ed,:sod,:sdl,
               :rdl,:crd,:web,
               :st,:ia,:sh)
          ")->execute([
            ':o'=>$orgId,':slug'=>$slug,':ta'=>$titleAr,':te'=>$titleEn,':short'=>$short,
            ':be'=>$briefEn,':ba'=>$briefAr,':thE'=>$themeEn,':thA'=>$themeAr,
            ':cfA'=>$cfpAr,':cfE'=>$cfpEn,
            ':locA'=>$locationAr,':locE'=>$locationEn,':venE'=>$venueEn,':venA'=>$venueAr,
            ':sd'=>$date('start_date'),':ed'=>$date('end_date'),
            ':sod'=>$date('submission_open_date'),':sdl'=>$date('submission_deadline'),
            ':rdl'=>$date('review_deadline'),':crd'=>$date('camera_ready_deadline'),
            ':web'=>$website,
            ':st'=>$status,':ia'=>$isActive,':sh'=>$showHome
          ]);
        }

        if(function_exists('flash_set')) flash_set('success','Saved');
        header('Location: '.base_path('admin/conferences')); exit;
    }

    public function toggle(): void {
        require_admin_or_chair(); require_org_context();
        $db=Database::getInstance(); $orgId=(int)current_org_id();
        $id=(int)($_GET['id']??0);
        $this->confOr404($db,$orgId,$id);
        $db->prepare("UPDATE conferences SET is_active=IF(is_active=1,0,1) WHERE id=:id AND org_id=:o")
           ->execute([':id'=>$id,':o'=>$orgId]);
        header('Location: '.base_path('admin/conferences')); exit;
    }
}
