<?php
// public/website-spec-pdf.php — Branded Website Specification PDF
require_once __DIR__ . '/../includes/bootstrap.php';

$user = requireAuth();
$id   = (int)($_GET['id'] ?? 0);
$proj = getProject($id, $user['id']);
if (!$proj) { http_response_code(404); die('Project not found.'); }

$vendorPath = __DIR__ . '/../vendor/autoload.php';
if (!file_exists($vendorPath)) {
    http_response_code(500);
    die('<pre>mPDF not installed. Run: composer install</pre>');
}

$spec   = fetchOne("SELECT * FROM website_specs WHERE project_id = ? AND user_id = ?", [$id, $user['id']]);
if (!$spec) { http_response_code(404); die('No specification found for this project. Complete the form first.'); }

$studio   = getStudioSettings($user['id']);
$client   = fetchOne("SELECT * FROM clients WHERE id = ?", [$proj['client_id']]);
$pages    = json_decode($spec['pages']    ?? '[]', true) ?: [];
$services = json_decode($spec['services'] ?? '[]', true) ?: [];

// Studio fallbacks
$studioName = $studio['studio_name'] ?: ($user['company'] ?? $user['name']);
$accent     = preg_match('/^#[0-9a-fA-F]{6}$/', $studio['accent_color'] ?? '') ? $studio['accent_color'] : '#5b5ef4';

// Spec colors
$primaryColor   = $spec['primary_color']   ?: '#1a1a2e';
$secondaryColor = $spec['secondary_color'] ?: '#f5f6fc';
$specAccent     = $spec['accent_color']    ?: $accent;

// Logo
$logoUrl  = $spec['logo_url'] ?: $studio['logo_url'] ?: '';
$logoData = $logoUrl ? fetchLogoBase64($logoUrl) : null;
$logoHtml = $logoData
    ? '<img src="' . $logoData . '" style="max-height:70px;max-width:220px;">'
    : '<div style="font-size:28px;font-weight:900;color:#fff;letter-spacing:-1px;">' . htmlspecialchars($spec['business_name'] ?: $studioName) . '</div>';

// Helpers
function hs(mixed $v): string { return htmlspecialchars((string)($v ?? ''), ENT_QUOTES, 'UTF-8'); }

// ── Color swatch helper ─────────────────────────────────────────────────────────
function colorSwatch(string $hex, string $label): string {
    $hex = preg_match('/^#[0-9a-fA-F]{6}$/', $hex) ? $hex : '#cccccc';
    // Determine text color (dark or light based on luminance)
    $r = hexdec(substr($hex,1,2)); $g = hexdec(substr($hex,3,2)); $b = hexdec(substr($hex,5,2));
    $lum = (0.299*$r + 0.587*$g + 0.114*$b) / 255;
    $txt = $lum > 0.5 ? '#1a1a2e' : '#ffffff';
    return '<div style="display:inline-block;width:90px;text-align:center;margin-right:10px;vertical-align:top;">'
         . '<div style="width:90px;height:56px;background:' . $hex . ';border-radius:8px;margin-bottom:6px;"></div>'
         . '<div style="font-size:10px;font-weight:bold;color:#333;">' . hs($label) . '</div>'
         . '<div style="font-size:9px;color:#888;font-family:monospace;">' . strtoupper($hex) . '</div>'
         . '</div>';
}

// ── AI Spec → HTML ──────────────────────────────────────────────────────────────
$specHtml = $spec['ai_spec'] ? markdownToHtml($spec['ai_spec']) : '<p style="color:#888;font-style:italic;">No AI specification generated yet. Complete Step 7 of the Website Spec form.</p>';

$generatedDate = date('d M Y');
$issueDate     = $spec['generated_at'] ? date('d M Y', strtotime($spec['generated_at'])) : $generatedDate;
$businessName  = hs($spec['business_name'] ?: $client['name']);
$tagline       = $spec['tagline'] ? hs($spec['tagline']) : '';
$industry      = $spec['industry'] ? hs($spec['industry']) : '';
$headingFont   = $spec['heading_font'] ?: 'Arial';
$bodyFont      = $spec['body_font']    ?: 'Arial';

// ── Build cover page ─────────────────────────────────────────────────────────────
ob_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
* { margin:0; padding:0; box-sizing:border-box; }
body { font-family: Arial, Helvetica, sans-serif; color: #1a1a2e; font-size:11px; line-height:1.6; background:#fff; }
h1 { font-size:24px; font-weight:900; color:<?= $accent ?>; margin-bottom:10px; }
h2 { font-size:16px; font-weight:700; color:<?= $accent ?>; border-bottom:2px solid <?= $accent ?>; padding-bottom:8px; margin:28px 0 14px; }
h3 { font-size:13px; font-weight:700; color:#1a1a2e; margin:18px 0 8px; }
p  { font-size:11px; color:#444; margin-bottom:10px; line-height:1.7; }
ul { margin:0 0 12px 0; padding-left:18px; }
li { font-size:11px; color:#444; margin-bottom:4px; line-height:1.6; }
strong { color:#1a1a2e; }
table { border-collapse:collapse; width:100%; margin-bottom:14px; }
th { background:<?= $accent ?>; color:#fff; padding:8px 10px; font-size:10px; text-align:left; }
td { padding:7px 10px; font-size:10px; border-bottom:1px solid #eaecf0; }
tr:nth-child(even) td { background:#f7f8ff; }
.section { page-break-inside:avoid; margin-bottom:28px; }
.tag { display:inline-block; background:<?= $specAccent ?>22; color:<?= $specAccent ?>; padding:3px 10px; border-radius:20px; font-size:9px; font-weight:700; margin-right:4px; }
</style>
</head>
<body>

<!-- ══════════════ COVER PAGE ══════════════ -->
<div style="background:<?= $primaryColor ?>;min-height:280mm;display:flex;flex-direction:column;padding:0;">

  <!-- Top accent strip -->
  <div style="height:8px;background:<?= $specAccent ?>;width:100%;"></div>

  <!-- Logo area -->
  <div style="padding:40px 50px 30px;">
    <?= $logoHtml ?>
  </div>

  <!-- Center content -->
  <div style="flex:1;padding:20px 50px 40px;display:flex;flex-direction:column;justify-content:center;">
    <div style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:3px;color:<?= $specAccent ?>;margin-bottom:16px;">
      Website Specification Document
    </div>
    <div style="font-size:44px;font-weight:900;color:#ffffff;line-height:1.1;margin-bottom:16px;letter-spacing:-1px;">
      <?= $businessName ?>
    </div>
    <?php if ($tagline): ?>
    <div style="font-size:16px;color:rgba(255,255,255,0.65);margin-bottom:28px;font-style:italic;">"<?= $tagline ?>"</div>
    <?php endif; ?>

    <!-- Meta pills -->
    <div style="display:flex;gap:12px;flex-wrap:wrap;">
      <?php if ($industry): ?>
      <div style="background:rgba(255,255,255,0.12);border:1px solid rgba(255,255,255,0.2);border-radius:20px;padding:6px 16px;font-size:10px;color:#fff;"><?= $industry ?></div>
      <?php endif; ?>
      <?php if (count($pages)): ?>
      <div style="background:rgba(255,255,255,0.12);border:1px solid rgba(255,255,255,0.2);border-radius:20px;padding:6px 16px;font-size:10px;color:#fff;"><?= count($pages) ?> Pages</div>
      <?php endif; ?>
      <?php if (count($services)): ?>
      <div style="background:rgba(255,255,255,0.12);border:1px solid rgba(255,255,255,0.2);border-radius:20px;padding:6px 16px;font-size:10px;color:#fff;"><?= count($services) ?> Services</div>
      <?php endif; ?>
    </div>
  </div>

  <!-- Footer info bar -->
  <div style="background:rgba(0,0,0,0.25);padding:16px 50px;display:flex;justify-content:space-between;align-items:center;">
    <div style="font-size:10px;color:rgba(255,255,255,0.6);">Prepared by <strong style="color:#fff;"><?= hs($studioName) ?></strong></div>
    <div style="font-size:10px;color:rgba(255,255,255,0.6);">Issued: <?= $issueDate ?></div>
  </div>

  <!-- Bottom accent strip -->
  <div style="height:8px;background:<?= $specAccent ?>;width:100%;"></div>
</div>

<!-- ══════════════ PAGE 2+ CONTENT ══════════════ -->
<div style="padding:36px 44px;">

  <!-- ── Brand Color Palette ── -->
  <div class="section">
    <h2>Brand Color Palette</h2>
    <div style="margin-bottom:16px;">
      <?= colorSwatch($spec['primary_color']   ?: '#1a1a2e', 'Primary') ?>
      <?= colorSwatch($spec['secondary_color'] ?: '#f5f6fc', 'Secondary') ?>
      <?= colorSwatch($spec['accent_color']    ?: $accent,   'Accent / CTA') ?>
    </div>
    <?php if ($spec['color_mood'] || $spec['color_notes']): ?>
    <p style="font-size:10.5px;color:#555;margin-top:10px;">
      <strong>Mood:</strong> <?= hs($spec['color_mood']) ?><?= ($spec['color_notes'] ? ' &nbsp;·&nbsp; ' . hs($spec['color_notes']) : '') ?>
    </p>
    <?php endif; ?>
  </div>

  <!-- ── Typography ── -->
  <?php if ($spec['heading_font'] || $spec['body_font']): ?>
  <div class="section">
    <h2>Typography</h2>
    <table style="width:auto;min-width:340px;">
      <tr>
        <th style="width:100px;">Role</th>
        <th>Font Family</th>
        <th>Usage</th>
      </tr>
      <?php if ($spec['heading_font']): ?>
      <tr><td><strong>Heading</strong></td><td><?= hs($spec['heading_font']) ?></td><td>H1, H2, H3, navigation labels</td></tr>
      <?php endif; ?>
      <?php if ($spec['body_font']): ?>
      <tr><td><strong>Body</strong></td><td><?= hs($spec['body_font']) ?></td><td>Paragraphs, captions, form labels</td></tr>
      <?php endif; ?>
    </table>
    <?php if ($spec['brand_style']): ?>
    <p><strong>Design Style:</strong> <?= hs($spec['brand_style']) ?></p>
    <?php endif; ?>
    <?php if ($spec['brand_personality']): ?>
    <p><strong>Brand Voice &amp; Personality:</strong> <?= hs($spec['brand_personality']) ?></p>
    <?php endif; ?>
  </div>
  <?php endif; ?>

  <!-- ── Pages / Sitemap ── -->
  <?php if ($pages): ?>
  <div class="section">
    <h2>Sitemap &amp; Page Overview</h2>
    <table>
      <tr><th style="width:160px;">Page</th><th>Purpose &amp; Key Content</th></tr>
      <?php foreach ($pages as $page): ?>
      <tr>
        <td><strong><?= hs($page['name']) ?></strong></td>
        <td style="color:#555;"><?= hs($page['desc'] ?: '—') ?></td>
      </tr>
      <?php endforeach; ?>
    </table>
  </div>
  <?php endif; ?>

  <!-- ── Services ── -->
  <?php if ($services): ?>
  <div class="section">
    <h2>Services &amp; Offerings</h2>
    <table>
      <tr><th style="width:160px;">Service</th><th>Description</th><th style="width:90px;text-align:right;">Price</th></tr>
      <?php foreach ($services as $svc): ?>
      <tr>
        <td><strong><?= hs($svc['name']) ?></strong></td>
        <td style="color:#555;"><?= hs($svc['desc'] ?: '—') ?></td>
        <td style="text-align:right;color:<?= $accent ?>;"><?= hs($svc['price'] ?: '—') ?></td>
      </tr>
      <?php endforeach; ?>
    </table>
  </div>
  <?php endif; ?>

  <!-- ── AI Generated Specification ── -->
  <div class="section">
    <h2>Full Website Specification</h2>
    <div style="font-size:10.5px;line-height:1.75;color:#333;">
      <?= $specHtml ?>
    </div>
  </div>

  <!-- ── Footer ── -->
  <div style="margin-top:40px;padding-top:16px;border-top:2px solid <?= $accent ?>;display:flex;justify-content:space-between;align-items:center;">
    <div style="font-size:9.5px;color:#aaa;">Prepared by <strong style="color:#555;"><?= hs($studioName) ?></strong><?= $studio['email'] ? ' &nbsp;·&nbsp; ' . hs($studio['email']) : '' ?></div>
    <div style="font-size:9.5px;color:#aaa;"><?= hs($spec['business_name']) ?> Website Specification &nbsp;·&nbsp; <?= $issueDate ?></div>
  </div>

</div>
</body>
</html>
<?php
$html = ob_get_clean();

// ── Generate PDF ────────────────────────────────────────────────────────────────
require_once $vendorPath;

$mpdf = new \Mpdf\Mpdf([
    'mode'          => 'utf-8',
    'format'        => 'A4',
    'margin_left'   => 0,
    'margin_right'  => 0,
    'margin_top'    => 0,
    'margin_bottom' => 0,
    'tempDir'       => sys_get_temp_dir(),
]);

$mpdf->SetTitle($spec['business_name'] . ' — Website Specification');
$mpdf->SetAuthor($studioName);
$mpdf->AddPageByArray(['margin-left' => 0, 'margin-right' => 0, 'margin-top' => 0, 'margin-bottom' => 0]);
$mpdf->WriteHTML($html);

$filename = 'WebSpec-' . preg_replace('/[^a-zA-Z0-9_\-]/', '-', $spec['business_name'] ?: 'spec') . '.pdf';
$mpdf->Output($filename, 'D');
