<?php
if (ob_get_level()) ob_end_clean();
ob_start();
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/PdfHelper.php';
requireLogin();

$id = (int)($_GET['id'] ?? 0);

$stmt = $pdo->prepare("SELECT q.*, c.customer_name, c.email, c.phone, c.billing_address, c.shipping_address, c.gst_number as customer_gst, c.city, c.state, c.pincode
                        FROM quotations q JOIN sale_vendors c ON c.id=q.customer_id WHERE q.id=?");
$stmt->execute([$id]);
$q = $stmt->fetch();
if (!$q) { echo "Quotation not found."; exit; }

$stmt = $pdo->prepare("SELECT qi.*, i.item_name, i.item_code, i.hsn_code, i.unit
                        FROM quotation_items qi JOIN items i ON i.id=qi.item_id WHERE qi.quotation_id=?");
$stmt->execute([$id]);
$lineItems = $stmt->fetchAll();

$qSubtotalFinal = 0; $qCgstFinal = 0; $qSgstFinal = 0;
foreach ($lineItems as $li) {
    $originalTotal = $li['line_total_before_discount'] ?: 0;
    $ratio = $originalTotal > 0 ? $li['line_final_amount'] / $originalTotal : 1;
    $qSubtotalFinal += round($li['line_subtotal'] * $ratio, 2);
    $qCgstFinal     += round($li['line_cgst'] * $ratio, 2);
    $qSgstFinal     += round($li['line_sgst'] * $ratio, 2);
}

$companyName    = getSetting('company_name', 'Your Company');
$companyAddress = getSetting('company_address', '');
$companyGst     = getSetting('company_gst', '');
$companyPhone   = getSetting('company_phone', '');
$companyEmail   = getSetting('company_email', '');

ob_end_clean();

// Use a simpler approach for the rupee symbol - use HTML entity as fallback
$rupee = '₹'; // Or use '&#8377;' if the character doesn't work

$html = '<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
* { margin:0; padding:0; box-sizing:border-box; }
body { 
    font-family: "DejaVu Sans", "Helvetica", Arial, sans-serif; 
    font-size: 11px; 
    color: #222; 
    padding: 24px; 
}
.header { display: table; width: 100%; margin-bottom: 16px; }
.header-left { display: table-cell; vertical-align: top; width: 60%; }
.header-right { display: table-cell; vertical-align: top; text-align: right; width: 40%; }
.company-name { font-size: 20px; font-weight: bold; color: #1D4E4A; margin-bottom: 4px; }
.company-info { font-size: 10px; color: #555; line-height: 1.6; }
.doc-title { font-size: 22px; font-weight: bold; color: #1D4E4A; letter-spacing: 2px; }
.doc-no { font-size: 13px; font-weight: bold; color: #333; margin-top: 4px; }
.doc-meta { font-size: 10px; color: #555; margin-top: 3px; line-height: 1.6; }
.divider { border: none; border-top: 1.5px solid #1D4E4A; margin: 12px 0; }
.divider-light { border: none; border-top: 1px solid #ddd; margin: 10px 0; }
.to-section { margin-bottom: 14px; }
.to-label { font-size: 9px; font-weight: bold; text-transform: uppercase; letter-spacing: 1px; color: #888; margin-bottom: 4px; }
.to-name { font-size: 13px; font-weight: bold; color: #1D4E4A; }
.to-info { font-size: 10px; color: #444; line-height: 1.6; margin-top: 2px; }
table { width: 100%; border-collapse: collapse; margin-bottom: 16px; }
thead tr { background-color: #1D4E4A; color: #fff; }
th { padding: 7px 6px; text-align: left; font-size: 10px; font-weight: bold; white-space: nowrap; }
th.num { text-align: right; }
td { padding: 6px 6px; font-size: 10px; border-bottom: 1px solid #E8E4DC; vertical-align: top; }
td.num { text-align: right; white-space: nowrap; }
tr:nth-child(even) td { background: #F9F7F2; }
.totals-table { width: 260px; margin-left: auto; border-collapse: collapse; }
.totals-table td { padding: 4px 6px; font-size: 11px; border: none; }
.totals-table .lbl { color: #666; }
.totals-table .val { text-align: right; font-weight: bold; }
.grand-row td { font-size: 14px; font-weight: bold; color: #1D4E4A; border-top: 2px solid #1D4E4A; padding-top: 7px; }
.notes { font-size: 10px; color: #555; margin-top: 12px; line-height: 1.5; }
.footer-note { font-size: 9px; color: #999; margin-top: 14px; border-top: 1px solid #eee; padding-top: 8px; text-align: center; }
</style>
</head>
<body>

<div class="header">
  <div class="header-left">
    <div class="company-name">' . htmlspecialchars($companyName) . '</div>
    <div class="company-info">
      ' . nl2br(htmlspecialchars($companyAddress)) . '<br>
      ' . ($companyGst ? 'GSTIN: ' . htmlspecialchars($companyGst) . '<br>' : '') . '
      ' . ($companyPhone ? 'Phone: ' . htmlspecialchars($companyPhone) : '') . '
      ' . ($companyEmail ? ' | Email: ' . htmlspecialchars($companyEmail) : '') . '
    </div>
  </div>
  <div class="header-right">
    <div class="doc-title">QUOTATION</div>
    <div class="doc-no">' . htmlspecialchars($q['quotation_no']) . '</div>
    <div class="doc-meta">
      Date: ' . date('d-M-Y', strtotime($q['quotation_date'])) . '<br>
      Valid Until: ' . ($q['valid_until'] ? date('d-M-Y', strtotime($q['valid_until'])) : 'N/A') . '<br>
      Status: ' . strtoupper($q['status']) . '
    </div>
  </div>
</div>

<hr class="divider">

<div class="to-section">
  <div class="to-label">Bill To</div>
  <div class="to-name">' . htmlspecialchars($q['customer_name']) . '</div>
  <div class="to-info">
    ' . nl2br(htmlspecialchars($q['shipping_address'] ?: $q['billing_address'])) . '<br>
    ' . htmlspecialchars($q['city']) . ($q['city'] && $q['state'] ? ', ' : '') . htmlspecialchars($q['state']) . ' ' . htmlspecialchars($q['pincode']) . '<br>
    ' . ($q['customer_gst'] ? 'GSTIN: ' . htmlspecialchars($q['customer_gst']) . '<br>' : '') . '
    Phone: ' . htmlspecialchars($q['phone']) . '
  </div>
</div>

<hr class="divider">

<table>
  <thead>
    <tr>
      <th style="width:28px">#</th>
      <th>Item Description</th>
      <th>HSN</th>
      <th class="num">Qty</th>
      <th class="num">Unit</th>
      <th class="num">Rate (excl. GST)</th>
      <th class="num">CGST</th>
      <th class="num">SGST</th>
      <th class="num">Amount</th>
    </tr>
  </thead>
  <tbody>';

$sno = 1;
foreach ($lineItems as $li) {
    $originalTotal = $li['line_total_before_discount'] ?: 0;
    $ratio = $originalTotal > 0 ? $li['line_final_amount'] / $originalTotal : 1;
    $finalBase = round($li['line_subtotal'] * $ratio, 2);
    $finalCgst = round($li['line_cgst'] * $ratio, 2);
    $finalSgst = round($li['line_sgst'] * $ratio, 2);
    $effectiveRate = $li['qty'] > 0 ? $finalBase / $li['qty'] : 0;

    $html .= '<tr>
      <td>' . $sno++ . '</td>
      <td>' . htmlspecialchars($li['item_name']) . '</td>
      <td>' . htmlspecialchars($li['hsn_code'] ?: '-') . '</td>
      <td class="num">' . $li['qty'] . '</td>
      <td class="num">' . htmlspecialchars($li['unit']) . '</td>
      <td class="num">' . $rupee . number_format($effectiveRate, 2) . '</td>
      <td class="num">' . $rupee . number_format($finalCgst, 2) . '<br><span style="color:#999;font-size:9px;">(' . number_format($li['cgst_percent'], 1) . '%)</span></td>
      <td class="num">' . $rupee . number_format($finalSgst, 2) . '<br><span style="color:#999;font-size:9px;">(' . number_format($li['sgst_percent'], 1) . '%)</span></td>
      <td class="num"><strong>' . $rupee . number_format($li['line_final_amount'], 2) . '</strong></td>
    </tr>';
}

$html .= '
  </tbody>
</table>

<table class="totals-table">
  <tr><td class="lbl">Subtotal</td><td class="val">' . $rupee . number_format($qSubtotalFinal, 2) . '</td></tr>
  <tr><td class="lbl">CGST</td><td class="val">' . $rupee . number_format($qCgstFinal, 2) . '</td></tr>
  <tr><td class="lbl">SGST</td><td class="val">' . $rupee . number_format($qSgstFinal, 2) . '</td></tr>
  <tr class="grand-row"><td class="lbl">Grand Total</td><td class="val">' . $rupee . number_format($q['grand_total'], 2) . '</td></tr>
</table>';

if ($q['notes']) {
    $html .= '<div class="notes"><strong>Notes:</strong> ' . nl2br(htmlspecialchars($q['notes'])) . '</div>';
}

$html .= '
<div class="footer-note">This is a system-generated quotation. Prices are inclusive of applicable taxes.</div>
</body></html>';

// Debug: Check if DOMPDF is available
error_log('DOMPDF Available: ' . (class_exists('Dompdf\Dompdf') ? 'Yes' : 'No'));

PdfHelper::output($html, 'Quotation_' . $q['quotation_no'] . '.pdf', true);
?>