<?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 d.*, c.customer_name, c.email, c.phone,
                        c.shipping_address, c.billing_address, c.city, c.state, c.pincode,
                        q.quotation_no, q.grand_total, q.id as q_id
                        FROM delivery_notes d
                        JOIN sale_vendors c ON c.id=d.customer_id
                        JOIN quotations q ON q.id=d.quotation_id
                        WHERE d.id=?");
$stmt->execute([$id]);
$d = $stmt->fetch();
if (!$d) { echo "Delivery note not found."; exit; }

$stmt = $pdo->prepare("SELECT dni.*, i.item_name, i.item_code, i.unit,
                        qi.unit_price, qi.cgst_percent, qi.sgst_percent,
                        qi.line_subtotal, qi.line_cgst, qi.line_sgst,
                        qi.line_total_before_discount, qi.line_discount_amount, qi.line_final_amount
                        FROM delivery_note_items dni
                        JOIN items i ON i.id=dni.item_id
                        LEFT JOIN quotation_items qi ON qi.quotation_id=:qid AND qi.item_id=dni.item_id
                        WHERE dni.delivery_note_id=:did");
$stmt->execute(['qid' => $d['q_id'], 'did' => $id]);
$lineItems = $stmt->fetchAll();

$dnSubtotal = 0; $dnCgst = 0; $dnSgst = 0; $dnTotal = 0;
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'] ?? 0) * $ratio, 2);
    $finalCgst = round(($li['line_cgst'] ?? 0) * $ratio, 2);
    $finalSgst = round(($li['line_sgst'] ?? 0) * $ratio, 2);
    $dnSubtotal += $finalBase;
    $dnCgst += $finalCgst;
    $dnSgst += $finalSgst;
    $dnTotal += $finalBase + $finalCgst + $finalSgst;
}

$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();

$deliveredInfo = '';
if ($d['status'] === 'delivered' && $d['delivered_datetime']) {
    $deliveredInfo = 'Delivered: ' . date('d-M-Y h:i A', strtotime($d['delivered_datetime']));
}

// 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: 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; }
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; }
.sig-row { display: table; width: 100%; margin-top: 48px; }
.sig-cell { display: table-cell; width: 50%; font-size: 10px; color: #666; }
.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">DELIVERY NOTE</div>
    <div class="doc-no">' . htmlspecialchars($d['delivery_no']) . '</div>
    <div class="doc-meta">
      Date: ' . date('d-M-Y', strtotime($d['delivery_date'])) . '<br>
      Ref: ' . htmlspecialchars($d['quotation_no']) . '<br>
      Status: ' . strtoupper($d['status']) . '
      ' . ($deliveredInfo ? '<br>' . $deliveredInfo : '') . '
    </div>
  </div>
</div>

<hr>

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

<hr>

<table>
  <thead>
    <tr>
      <th style="width:28px">#</th>
      <th>Item Description</th>
      <th>Code</th>
      <th class="num">Qty</th>
      <th class="num">Unit</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) {
    $originalTotal = $li['line_total_before_discount'] ?: 0;
    $ratio = $originalTotal > 0 ? $li['line_final_amount'] / $originalTotal : 1;
    $finalBase = round(($li['line_subtotal'] ?? 0) * $ratio, 2);
    $finalCgst = round(($li['line_cgst'] ?? 0) * $ratio, 2);
    $finalSgst = round(($li['line_sgst'] ?? 0) * $ratio, 2);
    $lineTotal = $finalBase + $finalCgst + $finalSgst;
    $unitRate  = $li['qty'] > 0 ? $finalBase / $li['qty'] : 0;

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

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

<table class="totals-table">
  <tr><td class="lbl">Subtotal</td><td class="val">' . $rupee . number_format($dnSubtotal, 2) . '</td></tr>
  <tr><td class="lbl">CGST</td><td class="val">' . $rupee . number_format($dnCgst, 2) . '</td></tr>
  <tr><td class="lbl">SGST</td><td class="val">' . $rupee . number_format($dnSgst, 2) . '</td></tr>
  <tr class="grand-row"><td class="lbl">Total Amount</td><td class="val">' . $rupee . number_format($dnTotal, 2) . '</td></tr>
</table>';

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

$html .= '
<div class="sig-row">
  <div class="sig-cell">Received by: _________________________</div>
  <div class="sig-cell" style="text-align:right;">Authorised Signature: _________________________</div>
</div>
<div class="footer-note">Please verify quantities upon receipt. Tax Invoice will follow separately.</div>
</body>
</html>';

PdfHelper::output($html, 'DeliveryNote_' . $d['delivery_no'] . '.pdf', true);
?>