<?php
declare(strict_types=1);

namespace App\Controllers;

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

final class AdminHomepageBlocksController extends Controller
{
    private function ensureTable($db): void
    {
        // homepage_blocks should exist already in your DB; this is just a safety check
        $st = $db->query("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name='homepage_blocks'");
        if ((int)$st->fetchColumn() <= 0) {
            throw new \RuntimeException("homepage_blocks table missing");
        }
    }

    public function index(): void
    {
        require_admin_area();
        $db = Database::getInstance();
        $this->ensureTable($db);

        $conf = (int)($_GET['conference_id'] ?? 0);
        if ($conf <= 0 && function_exists('default_conference_id')) $conf = (int)default_conference_id();

        $st = $db->prepare("SELECT * FROM homepage_blocks WHERE conference_id=:c ORDER BY sort_order ASC, id ASC");
        $st->execute([':c'=>$conf]);
        $rows = $st->fetchAll() ?: [];

        $edit = null;
        $eid = (int)($_GET['edit'] ?? 0);
        if ($eid > 0) {
            $st = $db->prepare("SELECT * FROM homepage_blocks WHERE id=:id LIMIT 1");
            $st->execute([':id'=>$eid]);
            $edit = $st->fetch() ?: null;
        }

        $this->view('admin/homepage_blocks/index', compact('rows','conf','edit'));
    }

    public function save(): void
    {
        require_admin_area();
        $db = Database::getInstance();
        $this->ensureTable($db);

        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { http_response_code(405); return; }

        $id = (int)($_POST['id'] ?? 0);
        $conf = (int)($_POST['conference_id'] ?? 0);
        $block_type = trim((string)($_POST['block_type'] ?? 'panel'));
        $block_key = trim((string)($_POST['block_key'] ?? ''));
        $title_en = trim((string)($_POST['title_en'] ?? ''));
        $title_ar = trim((string)($_POST['title_ar'] ?? ''));
        $body_en  = trim((string)($_POST['body_en'] ?? ''));
        $body_ar  = trim((string)($_POST['body_ar'] ?? ''));
        $link_url = trim((string)($_POST['link_url'] ?? ''));
        $sort = (int)($_POST['sort_order'] ?? 0);
        $is_active = (int)($_POST['is_active'] ?? 1);

        if ($conf <= 0) {
            if(function_exists('flash_set')) flash_set('danger','Missing conference_id');
            header('Location: '.base_path('admin/homepage-blocks'));
            exit;
        }

        // keep existing image if not uploading new
        $image_path = null;
        if ($id > 0) {
            $st = $db->prepare("SELECT image_path FROM homepage_blocks WHERE id=:id LIMIT 1");
            $st->execute([':id'=>$id]);
            $image_path = (string)($st->fetchColumn() ?: '');
        }

        // upload image if provided
        if (!empty($_FILES['image']['name'] ?? '')) {
            $image_path = $this->handleUpload($_FILES['image'], $conf);
        }

        if ($id > 0) {
            $db->prepare("
                UPDATE homepage_blocks
                SET block_type=:bt, block_key=:bk, title_en=:te, title_ar=:ta,
                    body_en=:be, body_ar=:ba, image_path=:ip, link_url=:lu,
                    sort_order=:so, is_active=:ia
                WHERE id=:id
            ")->execute([
                ':bt'=>$block_type,
                ':bk'=>($block_key!==''?$block_key:null),
                ':te'=>($title_en!==''?$title_en:null),
                ':ta'=>($title_ar!==''?$title_ar:null),
                ':be'=>($body_en!==''?$body_en:null),
                ':ba'=>($body_ar!==''?$body_ar:null),
                ':ip'=>($image_path!==''?$image_path:null),
                ':lu'=>($link_url!==''?$link_url:null),
                ':so'=>$sort,
                ':ia'=>$is_active?1:0,
                ':id'=>$id,
            ]);
            if(function_exists('flash_set')) flash_set('success','Block updated');
        } else {
            $db->prepare("
                INSERT INTO homepage_blocks(
                    conference_id, block_type, block_key,
                    title_en, title_ar, body_en, body_ar,
                    image_path, link_url, sort_order, is_active
                ) VALUES(
                    :c, :bt, :bk, :te, :ta, :be, :ba, :ip, :lu, :so, :ia
                )
            ")->execute([
                ':c'=>$conf,
                ':bt'=>$block_type,
                ':bk'=>($block_key!==''?$block_key:null),
                ':te'=>($title_en!==''?$title_en:null),
                ':ta'=>($title_ar!==''?$title_ar:null),
                ':be'=>($body_en!==''?$body_en:null),
                ':ba'=>($body_ar!==''?$body_ar:null),
                ':ip'=>($image_path!==''?$image_path:null),
                ':lu'=>($link_url!==''?$link_url:null),
                ':so'=>$sort,
                ':ia'=>$is_active?1:0,
            ]);
            if(function_exists('flash_set')) flash_set('success','Block added');
        }

        header('Location: '.base_path('admin/homepage-blocks?conference_id='.$conf));
        exit;
    }

    public function toggle(): void
    {
        require_admin_area();
        $db = Database::getInstance();
        $this->ensureTable($db);

        $id = (int)($_GET['id'] ?? 0);
        $conf = (int)($_GET['conference_id'] ?? 0);
        if ($id <= 0) { header('Location: '.base_path('admin/homepage-blocks?conference_id='.$conf)); exit; }

        $st = $db->prepare("UPDATE homepage_blocks SET is_active = IF(is_active=1,0,1) WHERE id=:id");
        $st->execute([':id'=>$id]);
        if(function_exists('flash_set')) flash_set('success','Toggled');
        header('Location: '.base_path('admin/homepage-blocks?conference_id='.$conf));
        exit;
    }

    public function delete(): void
    {
        require_admin_area();
        $db = Database::getInstance();
        $this->ensureTable($db);

        $id = (int)($_GET['id'] ?? 0);
        $conf = (int)($_GET['conference_id'] ?? 0);
        if ($id > 0) {
            $db->prepare("DELETE FROM homepage_blocks WHERE id=:id")->execute([':id'=>$id]);
            if(function_exists('flash_set')) flash_set('success','Deleted');
        }
        header('Location: '.base_path('admin/homepage-blocks?conference_id='.$conf));
        exit;
    }

    private function handleUpload(array $f, int $conf): string
    {
        if (($f['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) return '';
        $tmp = (string)($f['tmp_name'] ?? '');
        if ($tmp === '' || !is_uploaded_file($tmp)) return '';

        $name = (string)($f['name'] ?? 'image');
        $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
        if (!in_array($ext, ['png','jpg','jpeg','webp'], true)) $ext = 'png';

        $dir = BASE_PATH . '/public/assets/uploads/homepage';
        if (!is_dir($dir)) @mkdir($dir, 0775, true);

        $fname = 'conf'.$conf.'_'.date('Ymd_His').'_' . bin2hex(random_bytes(4)) . '.' . $ext;
        $dst = $dir . '/' . $fname;

        if (!@move_uploaded_file($tmp, $dst)) return '';
        @chmod($dst, 0664);

        return base_path('assets/uploads/homepage/'.$fname);
    }
}
