<?php
declare(strict_types=1);

namespace App\Controllers;

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

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

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

        // Pack205.10F POST->save
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
            $this->save();
            return;
        }

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

        $st=$db->prepare("SELECT id,title_en,title_ar,is_active,show_on_homepage 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 ? $this->confOrFail($db,$orgId,$confId) : null;

        $this->view('admin/homepage/index', compact('confs','confId','conf'));
    }

    public function save(): void
    {
        require_admin_or_chair_tenant();
        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);
        $conf=$this->confOrFail($db,$orgId,$confId);

        $data=[
          ':id'=>$confId,
          ':brief_en'=> (string)($_POST['brief_en'] ?? ''),
          ':brief_ar'=> (string)($_POST['brief_ar'] ?? ''),
          ':theme_en'=> (string)($_POST['theme_en'] ?? ''),
          ':theme_ar'=> (string)($_POST['theme_ar'] ?? ''),
          ':cfp_en'=> (string)($_POST['cfp_en'] ?? ''),
          ':cfp_ar'=> (string)($_POST['cfp_ar'] ?? ''),
          ':location_en'=> (string)($_POST['location_en'] ?? ''),
          ':location_ar'=> (string)($_POST['location_ar'] ?? ''),
          ':venue_en'=> (string)($_POST['venue_en'] ?? ''),
          ':venue_ar'=> (string)($_POST['venue_ar'] ?? ''),
          ':website_url'=> (string)($_POST['website_url'] ?? ''),
          ':show_on_homepage'=> ((int)($_POST['show_on_homepage'] ?? 1)) ? 1 : 0,
        ];

        // featured image upload (optional)
        $featured = $conf['featured_image'] ?? null;
        if (!empty($_FILES['featured_image']['tmp_name']) && is_uploaded_file($_FILES['featured_image']['tmp_name'])) {
            $dir = BASE_PATH . '/public/assets/uploads/org_' . $orgId . '/conferences/' . $confId;
            if (!is_dir($dir)) @mkdir($dir, 0775, true);

            $ext = strtolower(pathinfo($_FILES['featured_image']['name'] ?? '', PATHINFO_EXTENSION));
            if (!in_array($ext, ['jpg','jpeg','png','webp'], true)) $ext = 'jpg';
            $fn = 'featured_' . date('Ymd_His') . '.' . $ext;

            $dst = $dir . '/' . $fn;
            if (@move_uploaded_file($_FILES['featured_image']['tmp_name'], $dst)) {
                $featured = 'assets/uploads/org_' . $orgId . '/conferences/' . $confId . '/' . $fn;
            }
        }
        $data[':featured_image'] = $featured;

        $db->prepare("
          UPDATE conferences SET
            brief_en=:brief_en,
            brief_ar=:brief_ar,
            theme_en=:theme_en,
            theme_ar=:theme_ar,
            cfp_en=:cfp_en,
            cfp_ar=:cfp_ar,
            location_en=IF(:location_en='',NULL,:location_en),
            location_ar=IF(:location_ar='',NULL,:location_ar),
            venue_en=IF(:venue_en='',NULL,:venue_en),
            venue_ar=IF(:venue_ar='',NULL,:venue_ar),
            website_url=IF(:website_url='',NULL,:website_url),
            featured_image=:featured_image,
            show_on_homepage=:show_on_homepage
          WHERE id=:id
        ")->execute($data);

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