<?php
declare(strict_types=1);

namespace App\Controllers;

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

final class AdminConferencesController extends Controller
{
    /** @return array<string,int> */
    private function cols($db): array
    {
        $cols = (string)$db->query("
          SELECT GROUP_CONCAT(column_name)
          FROM information_schema.columns
          WHERE table_schema=DATABASE() AND table_name='conferences'
        ")->fetchColumn();

        return array_flip(array_filter(array_map('trim', explode(',', $cols))));
    }

    private function has(array $set, string $c): bool { return isset($set[$c]); }

    public function index(): void
    {
        require_login();
        if (!can_admin() && !can_chair()) { http_response_code(403); echo "Forbidden"; return; }
        $db = Database::getInstance();
        $rows = $db->query("SELECT * FROM conferences ORDER BY id DESC")->fetchAll();
        $this->view('admin/conferences/index', ['rows'=>$rows]);
    }

    public function create(): void
    {
        require_login();
        if (!can_admin()) { http_response_code(403); echo "Forbidden"; return; }
        $this->view('admin/conferences/form', ['mode'=>'create','row'=>[],'err'=>null]);
    }

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

        $db = Database::getInstance();
        $set = $this->cols($db);

        $data = [
          'title_en'=>trim((string)($_POST['title_en']??'')),
          'title_ar'=>trim((string)($_POST['title_ar']??'')),
          'brief_en'=>trim((string)($_POST['brief_en']??'')),
          'brief_ar'=>trim((string)($_POST['brief_ar']??'')),
          'cfp_en'=>trim((string)($_POST['cfp_en']??'')),
          'cfp_ar'=>trim((string)($_POST['cfp_ar']??'')),
          'website'=>trim((string)($_POST['website']??'')),
          'location'=>trim((string)($_POST['location']??'')),
          'start_date'=>trim((string)($_POST['start_date']??'')),
          'end_date'=>trim((string)($_POST['end_date']??'')),
          'is_active'=>(int)($_POST['is_active']??1),
        ];

        $cols=[];$vals=[];$params=[];
        foreach($data as $k=>$v){
            if(!$this->has($set,$k)) continue;
            $cols[]=$k; $vals[]=':'.$k; $params[':'.$k]=$v;
        }
        if(!$cols){ http_response_code(500); echo "No writable columns"; return; }

        $db->prepare("INSERT INTO conferences(".implode(',',$cols).") VALUES(".implode(',',$vals).")")->execute($params);
        header('Location: '.base_path('admin/conferences')); exit;
    }

    public function edit(): void
    {
        require_login();
        if (!can_admin()) { http_response_code(403); echo "Forbidden"; return; }
        $db = Database::getInstance();
        $id = (int)($_GET['id']??0);

        $st = $db->prepare("SELECT * FROM conferences WHERE id=:id LIMIT 1");
        $st->execute([':id'=>$id]);
        $row = $st->fetch();
        if(!$row){ http_response_code(404); echo "Not found"; return; }

        $this->view('admin/conferences/form',['mode'=>'edit','row'=>$row,'err'=>null]);
    }

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

        $db = Database::getInstance();
        $set = $this->cols($db);
        $id = (int)($_POST['id']??0);

        $data = [
          'title_en'=>trim((string)($_POST['title_en']??'')),
          'title_ar'=>trim((string)($_POST['title_ar']??'')),
          'brief_en'=>trim((string)($_POST['brief_en']??'')),
          'brief_ar'=>trim((string)($_POST['brief_ar']??'')),
          'cfp_en'=>trim((string)($_POST['cfp_en']??'')),
          'cfp_ar'=>trim((string)($_POST['cfp_ar']??'')),
          'website'=>trim((string)($_POST['website']??'')),
          'location'=>trim((string)($_POST['location']??'')),
          'start_date'=>trim((string)($_POST['start_date']??'')),
          'end_date'=>trim((string)($_POST['end_date']??'')),
          'is_active'=>(int)($_POST['is_active']??1),
        ];

        $sets=[];$params=[':id'=>$id];
        foreach($data as $k=>$v){
            if(!$this->has($set,$k)) continue;
            $sets[]="$k=:$k"; $params[':'.$k]=$v;
        }

        if($sets){
            $db->prepare("UPDATE conferences SET ".implode(',',$sets)." WHERE id=:id")->execute($params);
        }

        header('Location: '.base_path('admin/conferences')); exit;
    }

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

        // tolerate CSRF edge cases -> redirect with flash
        try {
            if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') csrf_check();
        } catch (\Throwable $e) {
            if (session_status() !== PHP_SESSION_ACTIVE) session_start();
            $_SESSION['flash_error'] = 'CSRF failed. Retry.';
            header('Location: '.base_path('admin/conferences')); exit;
        }

        $db = Database::getInstance();
        $set = $this->cols($db);
        if(!$this->has($set,'is_active')){
            if (session_status() !== PHP_SESSION_ACTIVE) session_start();
            $_SESSION['flash_error'] = 'Missing is_active column.';
            header('Location: '.base_path('admin/conferences')); exit;
        }

        $id = (int)(($_POST['id'] ?? 0) ?: ($_GET['id'] ?? 0));
        if ($id <= 0) {
            if (session_status() !== PHP_SESSION_ACTIVE) session_start();
            $_SESSION['flash_error'] = 'Missing id.';
            header('Location: '.base_path('admin/conferences')); exit;
        }

        $st = $db->prepare("SELECT is_active FROM conferences WHERE id=:id LIMIT 1");
        $st->execute([':id'=>$id]);
        $cur = (int)($st->fetchColumn() ?? 1);

        $db->prepare("UPDATE conferences SET is_active=:v WHERE id=:id")->execute([':v'=>($cur?0:1), ':id'=>$id]);

        if (session_status() !== PHP_SESSION_ACTIVE) session_start();
        $_SESSION['flash_success'] = 'Conference toggled.';
        header('Location: '.base_path('admin/conferences')); exit;
    }
}
