<?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 i.*, 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 invoices i
                        JOIN sale_vendors c ON c.id=i.customer_id
                        WHERE i.id=?");
$stmt->execute([$id]);
$inv = $stmt->fetch();
if (!$inv) { echo "Invoice not found."; exit; }

$stmt = $pdo->prepare("SELECT * FROM invoice_items WHERE invoice_id=?");
$stmt->execute([$id]);
$lineItems = $stmt->fetchAll();

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

$balance = $inv['grand_total'] - $inv['paid_amount'] - ($inv['tds_amount'] ?? 0);
$isManual = $inv['invoice_type'] === 'manual';
$docTitle = $isManual ? 'SERVICE BILL' : 'TAX INVOICE';

ob_end_clean();

// Use rupee symbol directly
$rupee = '₹';

$html = '<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
* { margin:0; padding:0; box-sizing:border-box; }
body { 
    font-family: "DejaVu Sans", Arial, Helvetica, 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: 20px; 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; }
hr { border: none; border-top: 1.5px solid #1D4E4A; margin: 12px 0; }
.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: 14px 0; }
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; }
.status-box { display: inline-block; padding: 3px 10px; border-radius: 4px; font-size: 10px; font-weight: bold; }
.paid { background: #D4EDDA; color: #155724; }
.partial { background: #FFF3CD; color: #856404; }
.pending { background: #F8D7DA; color: #721C24; }
.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">' . $docTitle . '</div>
    <div class="doc-no">' . htmlspecialchars($inv['invoice_no']) . '</div>
    <div class="doc-meta">
      Date: ' . date('d-M-Y', strtotime($inv['invoice_date'])) . '<br>
      Payment: <span class="status-box ' . $inv['payment_status'] . '">' . strtoupper($inv['payment_status']) . '</span>
    </div>
  </div>
</div>

<hr>

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

<hr>

<table>
  <thead>
    <tr>
      <th style="width:28px">#</th>
      <th>Description</th>
      <th class="num">Qty</th>
      <th class="num">Rate</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) {
    $html .= '<tr>
      <td>' . $sno++ . '</td>
      <td>' . htmlspecialchars($li['description'] ?: 'Item') . '</td>
      <td class="num">' . rtrim(rtrim(number_format($li['qty'], 2), '0'), '.') . '</td>
      <td class="num">' . $rupee . number_format($li['unit_price'], 2) . '</td>
      <td class="num">' . $rupee . number_format($li['line_cgst'], 2) . '<br><span style="color:#999;font-size:9px;">(' . number_format($li['cgst_percent'], 1) . '%)</span></td>
      <td class="num">' . $rupee . number_format($li['line_sgst'], 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_total'], 2) . '</strong></td>
    </tr>';
}

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

<table class="totals-table">
  <tr><td class="lbl">Subtotal</td><td class="val">' . $rupee . number_format($inv['subtotal'], 2) . '</td></tr>
  <tr><td class="lbl">CGST</td><td class="val">' . $rupee . number_format($inv['cgst_amount'], 2) . '</td></tr>
  <tr><td class="lbl">SGST</td><td class="val">' . $rupee . number_format($inv['sgst_amount'], 2) . '</td></tr>';

if (!empty($inv['discount_amount']) && $inv['discount_amount'] > 0) {
    $html .= '<tr><td class="lbl">Discount</td><td class="val" style="color:#A32D2D;">- ' . $rupee . number_format($inv['discount_amount'], 2) . '</td></tr>';
}

$html .= '<tr class="grand-row"><td class="lbl">Grand Total</td><td class="val">' . $rupee . number_format($inv['grand_total'], 2) . '</td></tr>';

if ($inv['paid_amount'] > 0) {
    $html .= '<tr><td class="lbl" style="color:#3B6D11;">Paid</td><td class="val" style="color:#3B6D11;">' . $rupee . number_format($inv['paid_amount'], 2) . '</td></tr>';
}
if (!empty($inv['tds_amount']) && $inv['tds_amount'] > 0) {
    $html .= '<tr><td class="lbl">TDS</td><td class="val">' . $rupee . number_format($inv['tds_amount'], 2) . '</td></tr>';
}
if ($balance > 0.01) {
    $html .= '<tr><td class="lbl" style="color:#A32D2D;">Balance Due</td><td class="val" style="color:#A32D2D;">' . $rupee . number_format($balance, 2) . '</td></tr>';
}

$html .= '
</table>';

if ($inv['notes']) {
    $html .= '<p style="font-size:10px;color:#555;margin-top:12px;"><strong>Notes:</strong> ' . nl2br(htmlspecialchars($inv['notes'])) . '</p>';
}

$html .= '
<div class="footer-note">This is a system-generated ' . ($isManual ? 'service bill' : 'tax invoice') . '. Thank you for your business.</div>
</body>
</html>';

PdfHelper::output($html, 'Invoice_' . $inv['invoice_no'] . '.pdf', true);
?>