<?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 AdminHomepageBlocksTenantController extends Controller
{
    private function blocksTable($db): string {
        foreach (['conference_homepage_blocks','conference_blocks','homepage_blocks'] as $t) {
            $st=$db->prepare("SELECT COUNT(*) FROM information_schema.TABLES WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=:t");
            $st->execute([':t'=>$t]);
            if((int)$st->fetchColumn()>0) return $t;
        }
        return 'conference_homepage_blocks';
    }

    private function confOrFail($db, int $orgId, int $confId): void {
        $st=$db->prepare("SELECT id FROM conferences WHERE id=:id AND org_id=:o LIMIT 1");
        $st->execute([':id'=>$confId, ':o'=>$orgId]);
        if(!(int)$st->fetchColumn()){ http_response_code(404); echo "Conference not found"; exit; }
    }

    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();
        $tbl=$this->blocksTable($db);

        $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));
        if($confId>0) $this->confOrFail($db,$orgId,$confId);

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

        $this->view('admin/homepage_blocks/index', compact('confs','confId','blocks','tbl'));
    }

    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();
        $tbl=$this->blocksTable($db);

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

        $id=(int)($_POST['id'] ?? 0);

        $type = (string)($_POST['block_type'] ?? 'panel');
        $key  = trim((string)($_POST['block_key'] ?? '')) ?: null;
        $titleEn = trim((string)($_POST['title_en'] ?? '')) ?: null;
        $titleAr = trim((string)($_POST['title_ar'] ?? '')) ?: null;
        $bodyEn  = (string)($_POST['body_en'] ?? '');
        $bodyAr  = (string)($_POST['body_ar'] ?? '');
        $linkUrl = trim((string)($_POST['link_url'] ?? '')) ?: null;
        $sort    = (int)($_POST['sort_order'] ?? 0);
        $active  = ((int)($_POST['is_active'] ?? 1)) ? 1 : 0;

        // image upload
        $imagePath = (string)($_POST['image_path_existing'] ?? '');
        if (!empty($_FILES['image']['tmp_name']) && is_uploaded_file($_FILES['image']['tmp_name'])) {
            $dir = BASE_PATH . '/public/assets/uploads/org_' . $orgId . '/homepage_blocks/' . $confId;
            if (!is_dir($dir)) @mkdir($dir, 0775, true);

            $ext = strtolower(pathinfo($_FILES['image']['name'] ?? '', PATHINFO_EXTENSION));
            if (!in_array($ext, ['jpg','jpeg','png','webp'], true)) $ext = 'jpg';
            $fn = 'block_' . date('Ymd_His') . '_' . mt_rand(100,999) . '.' . $ext;

            $dst = $dir . '/' . $fn;
            if (@move_uploaded_file($_FILES['image']['tmp_name'], $dst)) {
                $imagePath = 'assets/uploads/org_' . $orgId . '/homepage_blocks/' . $confId . '/' . $fn;
            }
        }
        $imagePath = $imagePath ?: null;

        if ($id > 0) {
            $st=$db->prepare("SELECT b.id FROM `$tbl` b JOIN conferences c ON c.id=b.conference_id WHERE b.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 `$tbl` SET
                org_id=:org_id,
                conference_id=:conference_id,
                block_type=:block_type,
                block_key=:block_key,
                title_en=:title_en,
                title_ar=:title_ar,
                body_en=:body_en,
                body_ar=:body_ar,
                image_path=:image_path,
                link_url=:link_url,
                sort_order=:sort_order,
                is_active=:is_active
              WHERE id=:id
            ")->execute([
              ':id'=>$id,
              ':org_id'=>$orgId,
              ':conference_id'=>$confId,
              ':block_type'=>$type,
              ':block_key'=>$key,
              ':title_en'=>$titleEn,
              ':title_ar'=>$titleAr,
              ':body_en'=>$bodyEn,
              ':body_ar'=>$bodyAr,
              ':image_path'=>$imagePath,
              ':link_url'=>$linkUrl,
              ':sort_order'=>$sort,
              ':is_active'=>$active,
            ]);
        } else {
            $db->prepare("
              INSERT INTO `$tbl`(
                org_id,conference_id,block_type,block_key,title_en,title_ar,body_en,body_ar,image_path,link_url,sort_order,is_active
              ) VALUES (
                :org_id,:conference_id,:block_type,:block_key,:title_en,:title_ar,:body_en,:body_ar,:image_path,:link_url,:sort_order,:is_active
              )
            ")->execute([
              ':org_id'=>$orgId,
              ':conference_id'=>$confId,
              ':block_type'=>$type,
              ':block_key'=>$key,
              ':title_en'=>$titleEn,
              ':title_ar'=>$titleAr,
              ':body_en'=>$bodyEn,
              ':body_ar'=>$bodyAr,
              ':image_path'=>$imagePath,
              ':link_url'=>$linkUrl,
              ':sort_order'=>$sort,
              ':is_active'=>$active,
            ]);
        }

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

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

        $db=Database::getInstance();
        $orgId=(int) current_org_id();
        $tbl=$this->blocksTable($db);

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

        $db->prepare("DELETE FROM `$tbl` WHERE id=:id")->execute([':id'=>$id]);

        if(function_exists('flash_set')) flash_set('success','Deleted');
        header('Location: '.base_path('admin/homepage-blocks?conference_id='.(int)$row['conference_id'])); exit;
    }
}
