<?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 AdminCertificatesController extends Controller
{
    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 certificate_logs ORDER BY id DESC LIMIT 300")->fetchAll();
        $this->view('admin/certificates/index', ['rows'=>$rows]);
    }

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

        $db = Database::getInstance();
        $cid = function_exists('default_conference_id') ? (int)default_conference_id() : 0;
        if ($cid<=0) { header('Location: '.base_path('admin/certificates')); exit; }

        $uid = (int)($_POST['user_id'] ?? 0);
        if ($uid<=0) { header('Location: '.base_path('admin/certificates')); exit; }

        $st = $db->prepare("SELECT email,first_name,last_name FROM users WHERE id=:id LIMIT 1");
        $st->execute([':id'=>$uid]);
        $u = $st->fetch();
        if (!$u) { header('Location: '.base_path('admin/certificates')); exit; }

        $name = trim((string)($u['first_name']??'').' '.(string)($u['last_name']??''));
        if ($name==='') $name = (string)$u['email'];

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

        $fname = 'cert_demo_'.$uid.'_'.date('Ymd_His').'.pdf';
        $path = $dir.'/'.$fname;
        $rel  = 'assets/uploads/certificates/'.$cid.'/'.$fname;

        // Simple PDF placeholder content
        $html = "<h1>Certificate</h1><p>This certifies that <b>".htmlspecialchars($name)."</b> is recognized.</p><p>Conference ID: ".$cid."</p><p>Date: ".date('Y-m-d')."</p>";
        file_put_contents($path, $html);

        $db->prepare("INSERT INTO certificate_logs(user_id,conference_id,cert_type,file_path,status) VALUES(:u,:c,'demo',:p,'generated')")
           ->execute([':u'=>$uid,':c'=>$cid,':p'=>$rel]);

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