<?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 PublicCertificatePdfController extends Controller
{
    private function fetchCert(string $code): array
    {
        $db = Database::getInstance();
        $st = $db->prepare("
          SELECT cert.*, u.first_name,u.last_name,u.email,u.preferred_lang,
                 c.title_en,c.title_ar, c.logo_path
          FROM certificates cert
          INNER JOIN users u ON u.id=cert.user_id
          INNER JOIN conferences c ON c.id=cert.conference_id
          WHERE cert.cert_code=:code
          LIMIT 1
        ");
        $st->execute([':code'=>$code]);
        $row = $st->fetch();
        if (!$row) { http_response_code(404); exit('Not found'); }
        return $row;
    }

    private function inlineLogo(array $row): string
    {
        if (empty($row['logo_path'])) return '';
        $abs = BASE_PATH . '/storage/' . (string)$row['logo_path'];
        if (!is_file($abs)) return '';
        $ext = strtolower(pathinfo($abs, PATHINFO_EXTENSION));
        $mime = ($ext==='png')?'image/png':(($ext==='jpg'||$ext==='jpeg')?'image/jpeg':(($ext==='webp')?'image/webp':''));
        if (!$mime) return '';
        $data = base64_encode((string)file_get_contents($abs));
        return "data:{$mime};base64,{$data}";
    }

    private function html(array $row): string
    {
        $lang = function_exists('current_lang') ? current_lang() : ((string)($row['preferred_lang'] ?? 'en'));
        $name = trim((string)$row['first_name'].' '.(string)$row['last_name']);
        $title = ($lang==='ar') ? (string)($row['title_ar'] ?? '') : (string)($row['title_en'] ?? '');
        $type = (string)($row['cert_type'] ?? 'reviewer');
        $issued = (string)($row['issued_at'] ?? '');
        $code = (string)($row['cert_code'] ?? '');
        $logo = $this->inlineLogo($row);

        $rtl = ($lang==='ar')?'rtl':'ltr';
        $align = ($lang==='ar')?'right':'left';

        return "<!doctype html>
<html lang=\"{$lang}\" dir=\"{$rtl}\">
<head>
<meta charset=\"utf-8\">
<title>Certificate</title>
<style>
  body{font-family:Arial,Tahoma,sans-serif;background:#f5f8ff;margin:0;padding:24px}
  .page{max-width:900px;margin:0 auto;background:#fff;border:1px solid #e6eefc;border-radius:18px;overflow:hidden}
  .top{background:linear-gradient(135deg,#0b2a6f,#1146b3);color:#fff;padding:18px 22px;display:flex;gap:14px;align-items:center}
  .top img{max-height:58px;background:#fff;border-radius:12px;padding:6px}
  .content{padding:26px}
  .title{font-size:26px;font-weight:900;color:#0b2a6f;text-align:center}
  .subtitle{text-align:center;color:#567;margin-top:6px}
  .box{margin-top:18px;border:1px solid #e6eefc;border-radius:18px;padding:22px;background:linear-gradient(135deg,#f7fbff,#ffffff)}
  .name{font-size:30px;font-weight:900;color:#0b2a6f;text-align:center;margin-top:8px}
  .line{text-align:center;color:#334;margin-top:6px;font-size:16px}
  .foot{display:flex;justify-content:space-between;margin-top:18px;color:#667;font-size:12px;direction:ltr}
  .print{margin-top:12px;text-align:{$align}}
  @media print{ body{background:#fff;padding:0} .print{display:none} .page{border:0} }
</style>
</head>
<body>
  <div class=\"page\">
    <div class=\"top\">".($logo ? "<img src=\"{$logo}\">" : "")."
      <div>
        <div style=\"font-weight:900\">{$title}</div>
        <div style=\"opacity:.9;font-size:12px\">Certificate • {$type}</div>
      </div>
    </div>
    <div class=\"content\">
      <div class=\"title\">".(($lang==='ar')?'شهادة':'Certificate')."</div>
      <div class=\"subtitle\">{$title}</div>

      <div class=\"box\">
        <div class=\"line\">".(($lang==='ar')?'تشهد اللجنة المنظمة بأن':'This is to certify that')."</div>
        <div class=\"name\">{$name}</div>
        <div class=\"line\">".(($lang==='ar')?'قد شارك بصفته:':'has served as:')." <b>{$type}</b></div>

        <div class=\"foot\">
          <div>Issued: {$issued}</div>
          <div>Verification: {$code}</div>
        </div>
      </div>

      <div class=\"print\">
        <button onclick=\"window.print()\">Print</button>
      </div>
    </div>
  </div>
</body>
</html>";
    }

    public function pdf(): void
    {
        $code = trim((string)($_GET['code'] ?? ''));
        if ($code === '') { http_response_code(400); exit('Missing code'); }

        $row = $this->fetchCert($code);

        $pdfDir = BASE_PATH . '/storage/certificates/pdf';
        @mkdir($pdfDir, 0775, true);

        $safe = preg_replace('/[^a-zA-Z0-9_\-]/', '_', $code);
        $pdfPath = $pdfDir . '/' . $safe . '.pdf';

        // If cached, serve
        if (is_file($pdfPath)) {
            header('Content-Type: application/pdf');
            header('Content-Disposition: inline; filename="certificate_'.$safe.'.pdf"');
            readfile($pdfPath);
            exit;
        }

        $html = $this->html($row);

        // wkhtmltopdf if available
        $wk = trim((string)shell_exec('command -v wkhtmltopdf 2>/dev/null'));
        if ($wk !== '') {
            $tmpHtml = tempnam(sys_get_temp_dir(), 'cert_') . '.html';
            file_put_contents($tmpHtml, $html);

            $cmd = escapeshellcmd($wk) . ' ' . escapeshellarg($tmpHtml) . ' ' . escapeshellarg($pdfPath) . ' 2>/dev/null';
            @shell_exec($cmd);
            @unlink($tmpHtml);

            if (is_file($pdfPath)) {
                header('Content-Type: application/pdf');
                header('Content-Disposition: inline; filename="certificate_'.$safe.'.pdf"');
                readfile($pdfPath);
                exit;
            }
        }

        // Fallback: print-friendly HTML
        header('Content-Type: text/html; charset=utf-8');
        echo $html;
        exit;
    }
}
