<?php
// public/invoice-pdf.php
// Generates a branded PDF invoice and either streams for download or sends via email.

require_once __DIR__ . '/../includes/bootstrap.php';

$user = requireAuth();

// ── Guards ─────────────────────────────────────────────────────────────────────
$vendorPath = __DIR__ . '/../vendor/autoload.php';
if (!file_exists($vendorPath)) {
    http_response_code(500);
    die('<pre>mPDF not installed.

Run this command in your debrieft/ directory:
  composer install

Or if Composer is not available globally:
  php composer.phar install

Get Composer at https://getcomposer.org</pre>');
}

$invoiceId = (int)($_GET['invoice_id'] ?? 0);
$action    = $_GET['action'] ?? 'download'; // download | email
if (!$invoiceId) { flash('error', 'Invalid invoice.'); redirect(APP_URL . '/projects.php'); }

// ── Fetch data ─────────────────────────────────────────────────────────────────
$invoice = fetchOne("SELECT * FROM invoices WHERE id = ? AND user_id = ?", [$invoiceId, $user['id']]);
if (!$invoice) { http_response_code(404); die('Invoice not found.'); }

$proj    = getProject($invoice['project_id'], $user['id']);
if (!$proj) { http_response_code(404); die('Project not found.'); }

$client  = fetchOne("SELECT * FROM clients WHERE id = ?", [$proj['client_id']]);
$quote   = $invoice['quote_id']
    ? fetchOne("SELECT * FROM quotes WHERE id = ?", [$invoice['quote_id']])
    : null;
$qItems  = $quote
    ? fetchAll("SELECT * FROM quote_items WHERE quote_id = ? ORDER BY id", [$quote['id']])
    : [];
$intake  = fetchOne("SELECT website_url FROM intake_forms WHERE project_id = ?", [$proj['id']]);
$studio  = getStudioSettings($user['id']);

// Fill studio blanks from user account
if (!$studio['owner_name']) $studio['owner_name'] = $user['name'];
if (!$studio['email'])      $studio['email']      = $user['email'];
if (!$studio['studio_name'] && ($user['company'] ?? ''))
    $studio['studio_name'] = $user['company'];

// ── Currency & numbers ─────────────────────────────────────────────────────────
$currency = $invoice['currency'] ?? $client['currency'] ?? $studio['default_currency'] ?? 'USD';
$sym      = currencySymbol($currency);
$accent   = preg_match('/^#[0-9a-fA-F]{6}$/', $studio['accent_color'] ?? '') ? $studio['accent_color'] : '#5b5ef4';

// Lighten accent for subtle backgrounds (hardcoded lighter tint)
$accentLight = $accent . '18'; // Note: not used directly in mPDF (no rgba support), use fixed light

$sub  = array_sum(array_map(fn($i) => $i['quantity'] * $i['unit_price'], $qItems));
$disc = (float)($quote['discount']    ?? 0);
$taxP = (float)($quote['tax_percent'] ?? 0);
$tax  = ($sub - $disc) * ($taxP / 100);
$tot  = $sub - $disc + $tax;

// ── Logo ───────────────────────────────────────────────────────────────────────
$logoUrl  = $studio['logo_url'] ?: 'https://rakibhasaan.com/wp-content/uploads/2024/09/Rakib-hasan-logo-e1726952149161.webp';
$logoData = fetchLogoBase64($logoUrl);
$logoHtml = $logoData
    ? '<img src="' . $logoData . '" style="max-height:54px;max-width:180px;">'
    : '<div style="font-size:22px;font-weight:bold;color:' . htmlspecialchars($accent) . ';">'
      . htmlspecialchars($studio['studio_name'] ?: 'Studio') . '</div>';

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

// ── Line items ─────────────────────────────────────────────────────────────────
$lineItemsHtml = '';
if ($qItems) {
    foreach ($qItems as $idx => $item) {
        $bg        = ($idx % 2 === 0) ? '#ffffff' : '#f5f6fc';
        $lineTotal = $item['quantity'] * $item['unit_price'];
        $lineItemsHtml .= '<tr style="background:' . $bg . ';">'
            . '<td style="padding:9px 12px;border-bottom:1px solid #eaecf0;font-size:10.5px;">' . hs($item['description']) . '</td>'
            . '<td style="padding:9px 8px;border-bottom:1px solid #eaecf0;text-align:center;font-size:10.5px;color:#555;">'
              . rtrim(rtrim(number_format($item['quantity'], 2), '0'), '.') . '</td>'
            . '<td style="padding:9px 12px;border-bottom:1px solid #eaecf0;text-align:right;font-size:10.5px;color:#555;">'
              . $sym . number_format($item['unit_price'], 2) . '</td>'
            . '<td style="padding:9px 12px;border-bottom:1px solid #eaecf0;text-align:right;font-size:10.5px;font-weight:bold;color:#1a1a2e;">'
              . $sym . number_format($lineTotal, 2) . '</td>'
            . '</tr>';
    }
} else {
    $lineItemsHtml = '<tr><td colspan="4" style="padding:18px;text-align:center;color:#aaa;font-size:10px;">No line items</td></tr>';
}

// ── Totals ─────────────────────────────────────────────────────────────────────
$totalsHtml = '';
$totalsHtml .= '<tr><td style="padding:5px 12px 5px 0;font-size:10px;color:#666;text-align:right;">Subtotal</td>'
             . '<td style="padding:5px 0 5px 20px;font-size:10px;color:#333;text-align:right;white-space:nowrap;">' . $sym . number_format($sub, 2) . '</td></tr>';
if ($disc > 0) {
    $totalsHtml .= '<tr><td style="padding:5px 12px 5px 0;font-size:10px;color:#666;text-align:right;">Discount</td>'
                 . '<td style="padding:5px 0 5px 20px;font-size:10px;color:#d94f4f;text-align:right;white-space:nowrap;">- ' . $sym . number_format($disc, 2) . '</td></tr>';
}
if ($taxP > 0) {
    $totalsHtml .= '<tr><td style="padding:5px 12px 5px 0;font-size:10px;color:#666;text-align:right;">Tax (' . $taxP . '%)</td>'
                 . '<td style="padding:5px 0 5px 20px;font-size:10px;color:#333;text-align:right;white-space:nowrap;">' . $sym . number_format($tax, 2) . '</td></tr>';
}
$totalsHtml .= '<tr><td colspan="2" style="padding:2px 0;"><hr style="border:none;border-top:1px solid #ddd;margin:0;"></td></tr>';
$totalsHtml .= '<tr style="background:' . $accent . ';">'
             . '<td style="padding:10px 14px;font-size:11px;font-weight:bold;color:#fff;text-align:right;border-radius:4px 0 0 4px;">Total (' . hs($currency) . ')</td>'
             . '<td style="padding:10px 12px;font-size:14px;font-weight:bold;color:#fff;text-align:right;white-space:nowrap;border-radius:0 4px 4px 0;">' . $sym . number_format($tot, 2) . '</td></tr>';

// ── Bank details ───────────────────────────────────────────────────────────────
$bankHtml = '';
if ($studio['bank_details']) {
    $lines = array_filter(array_map('trim', explode("\n", $studio['bank_details'])));
    foreach ($lines as $line) {
        $bankHtml .= '<div style="font-size:10px;color:#444;margin-bottom:3px;">' . hs($line) . '</div>';
    }
}

// ── Notes ──────────────────────────────────────────────────────────────────────
$notesHtml = '';
if (trim($invoice['notes'] ?? '')) {
    $notesHtml = '<div style="margin-bottom:20px;padding:12px 16px;background:#fffdf0;border-left:3px solid #f59e0b;">'
        . '<div style="font-size:9px;font-weight:bold;text-transform:uppercase;letter-spacing:1px;color:#d97706;margin-bottom:6px;">Notes &amp; Payment Terms</div>'
        . '<div style="font-size:10px;color:#555;line-height:1.6;">' . nl2br(hs($invoice['notes'])) . '</div>'
        . '</div>';
}

// ── Formatted fields ───────────────────────────────────────────────────────────
$issuedDate  = date('d M Y', strtotime($invoice['issued_at']));
$dueDateHtml = $invoice['due_date']
    ? '<div style="font-size:10px;color:#666;margin-top:2px;">Due: <strong>' . date('d M Y', strtotime($invoice['due_date'])) . '</strong></div>'
    : '';

$studioWebsite  = $studio['website'] ? hs($studio['website']) : '';
$studioSepChar  = ($studio['email'] && $studio['website']) ? ' &nbsp;|&nbsp; ' : '';
$taxIdLine      = $studio['tax_id'] ? '<div style="font-size:9.5px;color:#777;margin-top:1px;">Tax ID: ' . hs($studio['tax_id']) . '</div>' : '';
$footerText     = hs($studio['invoice_footer'] ?: 'Thank you for your business!');
$projectWebsite = $intake['website_url'] ?? '';
$invoiceNum     = hs($invoice['invoice_number']);

$contactLine = trim(implode(' &nbsp;|&nbsp; ', array_filter([
    hs($studio['owner_name']),
    hs($studio['phone']),
    hs($studio['email']),
])));

// ── Build HTML ─────────────────────────────────────────────────────────────────
ob_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
  * { margin: 0; padding: 0; box-sizing: border-box; }
  body {
    font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
    font-size: 11px;
    color: #1a1a2e;
    line-height: 1.5;
    background: #fff;
  }
  table { border-collapse: collapse; width: 100%; }
  .section-label {
    font-size: 8.5px;
    font-weight: bold;
    text-transform: uppercase;
    letter-spacing: 1.5px;
    color: <?= $accent ?>;
    margin-bottom: 7px;
    padding-bottom: 4px;
    border-bottom: 1px solid #eaecf0;
  }
</style>
</head>
<body>

<!-- ═══════════════════════════════ HEADER ═══════════════════════════════ -->
<table style="margin-bottom:22px;padding-bottom:18px;border-bottom:3px solid <?= $accent ?>;">
  <tr>
    <!-- Studio info (left) -->
    <td style="vertical-align:top;width:55%;padding-right:20px;">
      <div style="margin-bottom:10px;"><?= $logoHtml ?></div>
      <?php if ($studio['studio_name']): ?>
      <div style="font-size:15px;font-weight:bold;color:#1a1a2e;margin-bottom:1px;"><?= hs($studio['studio_name']) ?></div>
      <?php endif; ?>
      <?php if ($studio['owner_name']): ?>
      <div style="font-size:10px;color:#555;margin-bottom:3px;"><?= hs($studio['owner_name']) ?></div>
      <?php endif; ?>
      <?php if ($studio['address']): ?>
      <div style="font-size:9.5px;color:#777;margin-bottom:2px;white-space:pre-wrap;"><?= hs($studio['address']) ?></div>
      <?php endif; ?>
      <?= $taxIdLine ?>
      <?php if ($studio['phone']): ?>
      <div style="font-size:9.5px;color:#777;margin-top:1px;"><?= hs($studio['phone']) ?></div>
      <?php endif; ?>
      <?php if ($studio['email'] || $studio['website']): ?>
      <div style="font-size:9.5px;color:#777;"><?= hs($studio['email']) ?><?= $studioSepChar ?><?= $studioWebsite ?></div>
      <?php endif; ?>
    </td>

    <!-- Invoice badge (right) -->
    <td style="vertical-align:top;text-align:right;">
      <div style="font-size:34px;font-weight:bold;color:<?= $accent ?>;letter-spacing:-1px;text-transform:uppercase;line-height:1;">INVOICE</div>
      <div style="font-size:15px;font-weight:bold;color:#1a1a2e;margin-top:5px;">#<?= $invoiceNum ?></div>
      <div style="font-size:10px;color:#777;margin-top:4px;">Issued: <?= $issuedDate ?></div>
      <?= $dueDateHtml ?>
      <div style="margin-top:8px;">
        <span style="display:inline-block;padding:3px 10px;border-radius:20px;font-size:9px;font-weight:bold;text-transform:uppercase;letter-spacing:0.5px;
          background:<?= $invoice['status'] === 'paid' ? '#e6faf3' : ($invoice['status'] === 'sent' ? '#e8f0fe' : '#f0f0f0') ?>;
          color:<?= $invoice['status'] === 'paid' ? '#0a8a5c' : ($invoice['status'] === 'sent' ? '#3c5fcc' : '#888') ?>;">
          <?= strtoupper(hs($invoice['status'])) ?>
        </span>
      </div>
    </td>
  </tr>
</table>

<!-- ═══════════════════════════ BILL TO / FOR ════════════════════════════ -->
<table style="margin-bottom:24px;">
  <tr>
    <!-- Bill to -->
    <td style="vertical-align:top;width:48%;padding-right:20px;border-right:1px solid #eaecf0;">
      <div class="section-label">Bill To</div>
      <div style="font-size:13px;font-weight:bold;color:#1a1a2e;margin-bottom:2px;"><?= hs($client['name']) ?></div>
      <?php if ($client['company']): ?>
      <div style="font-size:10px;color:#555;margin-bottom:2px;"><?= hs($client['company']) ?></div>
      <?php endif; ?>
      <?php if ($client['address']): ?>
      <div style="font-size:9.5px;color:#777;margin-bottom:2px;white-space:pre-wrap;"><?= hs($client['address']) ?></div>
      <?php endif; ?>
      <?php if ($client['phone']): ?>
      <div style="font-size:9.5px;color:#777;"><?= hs($client['phone']) ?></div>
      <?php endif; ?>
      <?php if ($client['email']): ?>
      <div style="font-size:9.5px;color:#777;"><?= hs($client['email']) ?></div>
      <?php endif; ?>
    </td>
    <!-- For / project -->
    <td style="vertical-align:top;padding-left:20px;">
      <div class="section-label">For</div>
      <div style="font-size:13px;font-weight:bold;color:#1a1a2e;margin-bottom:4px;"><?= hs($proj['title']) ?></div>
      <?php if ($projectWebsite): ?>
      <div style="font-size:9.5px;color:#777;"><?= hs($projectWebsite) ?></div>
      <?php endif; ?>
      <?php if ($quote['quote_number'] ?? ''): ?>
      <div style="font-size:9.5px;color:#aaa;margin-top:8px;">Ref: Quote <?= hs($quote['quote_number']) ?></div>
      <?php endif; ?>
    </td>
  </tr>
</table>

<!-- ═══════════════════════════ LINE ITEMS ═══════════════════════════════ -->
<table style="margin-bottom:18px;">
  <thead>
    <tr style="background:<?= $accent ?>;">
      <th style="padding:10px 12px;text-align:left;color:#fff;font-size:9.5px;font-weight:bold;text-transform:uppercase;letter-spacing:0.5px;width:48%;">Description</th>
      <th style="padding:10px 8px;text-align:center;color:#fff;font-size:9.5px;font-weight:bold;text-transform:uppercase;letter-spacing:0.5px;width:10%;">Qty</th>
      <th style="padding:10px 12px;text-align:right;color:#fff;font-size:9.5px;font-weight:bold;text-transform:uppercase;letter-spacing:0.5px;width:21%;">Unit Price (<?= hs($currency) ?>)</th>
      <th style="padding:10px 12px;text-align:right;color:#fff;font-size:9.5px;font-weight:bold;text-transform:uppercase;letter-spacing:0.5px;width:21%;">Total (<?= hs($currency) ?>)</th>
    </tr>
  </thead>
  <tbody>
    <?= $lineItemsHtml ?>
  </tbody>
</table>

<!-- ═══════════════════════════════ TOTALS ═══════════════════════════════ -->
<table style="width:280px;margin-left:auto;margin-bottom:24px;border-collapse:collapse;">
  <?= $totalsHtml ?>
</table>

<!-- ═══════════════════════════ BANK DETAILS ════════════════════════════ -->
<?php if ($bankHtml): ?>
<div style="margin-bottom:20px;padding:14px 18px;background:#f7f8ff;border-left:3px solid <?= $accent ?>;">
  <div style="font-size:9px;font-weight:bold;text-transform:uppercase;letter-spacing:1px;color:<?= $accent ?>;margin-bottom:9px;">Payment Details</div>
  <?= $bankHtml ?>
</div>
<?php endif; ?>

<!-- ═══════════════════════════════ NOTES ════════════════════════════════ -->
<?= $notesHtml ?>

<!-- ═══════════════════════════════ FOOTER ═══════════════════════════════ -->
<div style="text-align:center;padding-top:18px;border-top:1px solid #eaecf0;margin-top:8px;">
  <div style="font-size:13px;font-weight:bold;color:<?= $accent ?>;margin-bottom:4px;"><?= $footerText ?></div>
  <div style="font-size:9.5px;color:#aaa;">Questions? &nbsp;<?= $contactLine ?></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'   => 14,
    'margin_right'  => 14,
    'margin_top'    => 14,
    'margin_bottom' => 14,
    'tempDir'       => sys_get_temp_dir(),
    'allow_charset_conversion' => true,
]);

$mpdf->SetTitle('Invoice ' . $invoice['invoice_number']);
$mpdf->SetAuthor($studio['studio_name'] ?: $user['name']);
$mpdf->WriteHTML($html);

$filename = 'Invoice-' . preg_replace('/[^a-zA-Z0-9_\-]/', '', $invoice['invoice_number']) . '.pdf';

if ($action === 'email') {
    // Mark as sent
    update('invoices', ['status' => 'sent'], 'id = ?', [$invoiceId]);

    $pdfContent = $mpdf->Output('', 'S');
    $ok = sendInvoiceEmail($invoice, $client, $user, $studio, $pdfContent, $filename);

    $projId = $invoice['project_id'];
    flash($ok ? 'success' : 'error',
        $ok ? 'Invoice emailed to ' . $client['email'] . '.' : 'Email failed — check SMTP settings in Studio Admin.');
    redirect(APP_URL . '/project.php?id=' . $projId . '&tab=invoice');
}

// Default: download
$mpdf->Output($filename, 'D');
