<?php
declare(strict_types=1);

namespace App\Controllers;

require_once BASE_PATH . '/app/helpers/conference_scope.php';

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

final class AdminConferenceLogoController extends Controller
{
    public function form(): 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/logo', ['row'=>$row, 'err'=>null]);
    }

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

        $db = Database::getInstance();
        $id = (int)($_POST['id'] ?? 0);
        if ($id <= 0) { header('Location: '.base_path('admin/conferences')); exit; }

        if (!isset($_FILES['logo']) || ($_FILES['logo']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
            header('Location: '.base_path('admin/conferences/edit?id='.$id)); exit;
        }

        $tmp = (string)$_FILES['logo']['tmp_name'];
        $orig = (string)$_FILES['logo']['name'];
        $ext = strtolower(pathinfo($orig, PATHINFO_EXTENSION));
        if (!in_array($ext, ['png','jpg','jpeg','webp','svg'], true)) {
            header('Location: '.base_path('admin/conferences/edit?id='.$id)); exit;
        }

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

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

        if (!move_uploaded_file($tmp, $dest)) {
            header('Location: '.base_path('admin/conferences/edit?id='.$id)); exit;
        }

        $rel = 'assets/uploads/conferences/' . $id . '/' . $fname;
        $db->prepare("UPDATE conferences SET logo_path=:p WHERE id=:id")->execute([':p'=>$rel, ':id'=>$id]);

        header('Location: '.base_path('admin/conferences/edit?id='.$id));
        exit;
    }
}
