<?php
require_once __DIR__ . '/../../../inc/bootstrap.php';
require_once ADMIN_ROOT . '/inc/init.php';
require_once ADMIN_ROOT . '/inc/func.php';

// ---------- helpers ----------
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
function money_i($n){ return number_format((float)$n, 2, '.', ''); }

/**
 * Very simple number-to-words (for INR-style amounts).
 * Used for "TOTAL AMOUNT IN WORDS" (based on total including GST in INR).
 */
function number_to_words($number)
{
    $number = round($number);

    $hyphen      = '-';
    $conjunction = ' and ';
    $separator   = ', ';
    $negative    = 'minus ';
    $dictionary  = [
        0         => 'zero',
        1         => 'one',
        2         => 'two',
        3         => 'three',
        4         => 'four',
        5         => 'five',
        6         => 'six',
        7         => 'seven',
        8         => 'eight',
        9         => 'nine',
        10        => 'ten',
        11        => 'eleven',
        12        => 'twelve',
        13        => 'thirteen',
        14        => 'fourteen',
        15        => 'fifteen',
        16        => 'sixteen',
        17        => 'seventeen',
        18        => 'eighteen',
        19        => 'nineteen',
        20        => 'twenty',
        30        => 'thirty',
        40        => 'forty',
        50        => 'fifty',
        60        => 'sixty',
        70        => 'seventy',
        80        => 'eighty',
        90        => 'ninety',
        100       => 'hundred',
        1000      => 'thousand',
        100000    => 'lakh',
        10000000  => 'crore'
    ];

    if (!is_numeric($number)) return '';

    if ($number < 0) return $negative . number_to_words(abs($number));

    $string = '';

    switch (true) {
        case $number < 21:
            $string = $dictionary[$number];
            break;

        case $number < 100:
            $tens   = ((int) ($number / 10)) * 10;
            $units  = $number % 10;
            $string = $dictionary[$tens];
            if ($units) $string .= $hyphen . $dictionary[$units];
            break;

        case $number < 1000:
            $hundreds  = (int)($number / 100);
            $remainder = $number % 100;
            $string = $dictionary[$hundreds] . ' ' . $dictionary[100];
            if ($remainder) $string .= $conjunction . number_to_words($remainder);
            break;

        case $number < 100000:
            $thousands = (int)($number / 1000);
            $remainder = $number % 1000;
            $string = number_to_words($thousands) . ' ' . $dictionary[1000];
            if ($remainder) $string .= $separator . number_to_words($remainder);
            break;

        case $number < 10000000:
            $lakhs     = (int)($number / 100000);
            $remainder = $number % 100000;
            $string = number_to_words($lakhs) . ' ' . $dictionary[100000];
            if ($remainder) $string .= $separator . number_to_words($remainder);
            break;

        default:
            $crores    = (int)($number / 10000000);
            $remainder = $number % 10000000;
            $string = number_to_words($crores) . ' ' . $dictionary[10000000];
            if ($remainder) $string .= $separator . number_to_words($remainder);
            break;
    }

    return ucfirst($string);
}

$comp_id = (int)($company['id'] ?? $compID ?? 1);

// ---------- mPDF bootstrap ----------
$mpdf_loaded = false;
if (file_exists(ADMIN_ROOT . '/vendor/autoload.php')) {
    require_once ADMIN_ROOT . '/vendor/autoload.php';
    $mpdf_loaded = class_exists('\Mpdf\Mpdf');
} elseif (file_exists(ADMIN_ROOT . '/mpdf/autoload.php')) {
    require_once ADMIN_ROOT . '/mpdf/autoload.php';
    $mpdf_loaded = class_exists('\Mpdf\Mpdf');
}
if (!$mpdf_loaded) {
    die('mPDF not found. Place it under ADMIN_ROOT/vendor/ or ADMIN_ROOT/mpdf/');
}

// ---------- get invoice id from MD5 ----------
$hash           = trim($_GET['id'] ?? '');
$force_download = (int)($_GET['dl'] ?? 0);
$invoice_id     = 0;

if ($hash !== '') {
    $st = $db->prepare("SELECT id FROM agent_invoice WHERE MD5(id)=? LIMIT 1");
    $st->bind_param('s', $hash);
    $st->execute();
    $st->bind_result($rid);
    if ($st->fetch()) $invoice_id = (int)$rid;
    $st->close();
}
if ($invoice_id <= 0) {
    http_response_code(404);
    die('Invalid invoice');
}

// ---------- fetch invoice + agent ----------
$sql = "SELECT ai.*,
               a.agent_code, a.name AS agent_name, a.phone_number, a.email_address, a.address AS agent_address,
               a.gst_number, a.bank_name, a.acc_name, a.acc_no, a.acc_ifsc, a.upi_id, a.logo, a.pay_qr
        FROM agent_invoice ai
        JOIN agents a ON a.id = ai.agent_id
        WHERE ai.comp_id=? AND ai.id=? LIMIT 1";
$st  = $db->prepare($sql);
$st->bind_param('ii', $comp_id, $invoice_id);
$st->execute();
$inv = $st->get_result()->fetch_assoc();
$st->close();
if (!$inv) {
    http_response_code(404);
    die('Invoice not found');
}

// ---------- items ----------
$items = [];
$qi    = $db->prepare("SELECT serail_no, item_name, description, price
                       FROM agent_invoice_items
                       WHERE comp_id=? AND invoice_id=?
                       ORDER BY serail_no ASC, id ASC");
$qi->bind_param('ii', $comp_id, $invoice_id);
$qi->execute();
$rs = $qi->get_result();
while ($r = $rs->fetch_assoc()) $items[] = $r;
$qi->close();

// ---------- media (logo/qr) ----------
$defaultLogo = 'https://cdn-icons-png.flaticon.com/512/847/847969.png';
$defaultQR   = 'https://cdn-icons-png.flaticon.com/512/882/882747.png';

//$logoSrc = url('assets/logo.png');

// Point directly to the file on disk (inside admin)
$logoPath = realpath(ADMIN_ROOT . '/assets/logo.png');  // e.g. /home/…/public_html/admin/assets/logo.png

// Safety: if realpath fails, fall back to empty string
$logoSrc  = $logoPath ?: ADMIN_ROOT . '/assets/logo.png';

// ---------- basics ----------
$invNo   = $inv['invoice_no'];
$invDate = $inv['invoice_date'] ? date('d M Y', strtotime($inv['invoice_date'])) : '-';
$total   = (float)$inv['invoice_total'];
$brand   = $brandName ?: 'Invoice';
$invDesc = nl2br(h($inv['invoice_txt']));

// currency from table
$currency       = strtoupper(trim($inv['currency_code'] ?? 'INR'));
$currencySymbol = '₹';

// load symbol from currencies table if present
$stmtCur = $db->prepare("SELECT symbol FROM currencies WHERE code=? AND active='y' LIMIT 1");
$stmtCur->bind_param('s', $currency);
$stmtCur->execute();
$resCur = $stmtCur->get_result();
if ($rowCur = $resCur->fetch_assoc()) {
    $currencySymbol = $rowCur['symbol'];
}
$stmtCur->close();

$roeText = trim($inv['roe'] ?? '');
$roeHtml = $roeText !== '' ? 'ROE (Rate of Exchange) : ' . h($roeText) : '';

// totals in INR from DB
$invoice_subtotal_inr       = isset($inv['invoice_subtotal_inr']) ? (float)$inv['invoice_subtotal_inr'] : 0.0;
$invoice_gst_inr            = isset($inv['invoice_gst_inr']) ? (float)$inv['invoice_gst_inr'] : 0.0;
$invoice_total_with_gst_inr = isset($inv['invoice_total_with_gst_inr']) ? (float)$inv['invoice_total_with_gst_inr'] : 0.0;

// total amount in words (based on total including GST in INR)
$amount_words = '';
if ($invoice_total_with_gst_inr > 0) {
    $amount_words = number_to_words($invoice_total_with_gst_inr) . ' only';
}

// formatted strings
$fmtTotal       = money_i($total);
$fmtSubtotalInr = money_i($invoice_subtotal_inr);
$fmtGstInr      = money_i($invoice_gst_inr);
$fmtTotalGstInr = money_i($invoice_total_with_gst_inr);
$amountWordsHtml = h(ucwords($amount_words));

// safe filename
$agentNameForFile = preg_replace('/[^A-Za-z0-9_\-]+/', '_', (string)$inv['agent_name']);
$filename         = preg_replace('/[^A-Za-z0-9_\-]/', '_', (string)$invNo) . '-' . $agentNameForFile . '.pdf';

// address with line breaks
$companyAddrHtml = nl2br(h($companyaddr));
$agentAddrHtml   = nl2br(h($inv['agent_address']));

// ---------- CSS ----------
$css = <<<CSS
body {
  font-family: DejaVu Sans, Arial, Helvetica, sans-serif;
  font-size: 12.5px;
  line-height: 1.5;
  color: #333;
  background-color: #fdf7ec;
}
.wrapper {
  background: #fff9ef;
  padding: 26px 26px 40px 26px;
  border-radius: 12px;
}
.header-table {
  width: 100%;
}
.header-table td {
  vertical-align: top;
}
.logo-img {
  max-width: 100px;
}
.top-right {
  text-align: right;
  font-size: 12px;
}
.invoice-title {
  text-align: center;
  font-size: 22px;
  font-weight: bold;
  letter-spacing: 1px;
}
.info-label {
  font-weight: bold;
}
.hr-line {
  border-top: 1px solid #444;
  margin: 10px 0 14px 0;
}
.block-title {
  font-weight: bold;
  font-size: 13px;
  margin-bottom: 4px;
}
.section-table {
  width: 100%;
}
.section-table td {
  vertical-align: top;
  padding: 4px 0;
}
.invoice-desc {
  margin-top: 4px;
}

/* ===== ITEMS TABLE (sample-style) ===== */
.items-table {
  width: 100%;
  border-collapse: separate;   /* important for rounded corners */
  border-spacing: 0;           /* so it still looks tight */
  margin-top: 16px;
  background: #ffffff;
}

.items-table thead th {
  padding: 8px 10px;
  font-size: 11.5px;
  font-weight: bold;
}

/* outer white + dark pill header */
.items-header-row th {
  border-top: 1px solid #2f3d40;
  border-bottom: 1px solid #2f3d40;
  border-left: 1px solid #2f3d40;
  border-right: none;
  background: #ffffff;              /* default left side = white */
}

.items-header-row th:last-child {
  border-right: 1px solid #2f3d40;  /* close the right side */
}

/* rounded left side: S. NO. + ITEM share same white pill */
.items-header-row th:first-child {
  border-radius: 24px 0 0 24px;
}
.items-header-row th:nth-child(2) {
  border-radius: 0;                 /* middle white cell */
}

/* 3) dark right side: DESCRIPTIONS + PRICE share dark pill */
.items-header-row th:nth-child(3),
.items-header-row th:nth-child(4) {
  background: #2f3d40;
  color: #ffffff;
  border-color: #2f3d40;
}

.items-header-row th:nth-child(4) {
  border-radius: 0 24px 24px 0;     /* rounded right edge */
}

/* body rows – only light horizontal lines */
.items-table tbody td {
  padding: 9px 9px;
  font-size: 12px;
  border-bottom: 1px solid #e0dfdf;
  border-left: none;
  border-right: none;
  background: #ffffff;
}

/* center S. NO., right-align price */
.text-center { text-align: center; }
.text-right  { text-align: right;  }
.text-left  { text-align: left;  }        

/* ITEM column bold like sample */
.items-table tbody td:nth-child(2) {
  font-weight: bold;
}


.pill-sno,
.pill-dark {
  display: block;
  padding: 7px 10px;
  font-size: 11.5px;
  font-weight: bold;
}

/* left "S. NO." bubble – light with border */
.pill-sno {
  background: #fff9ef;
  border: 1px solid #2f3d40;
  border-radius: 18px 0 0 18px;
  text-align: center;
}

/* dark header bubbles */
.pill-dark {
  background: #2f3d40;
  color: #fff;
  border-top: 1px solid #2f3d40;
  border-bottom: 1px solid #2f3d40;
}

.pill-dark-left {
  border-radius: 18px 0 0 18px;
  margin-left: -2px;   /* visually attach to S.NO. pill */
}

.pill-dark-middle {
  margin-left: -2px;
}

.pill-dark-right {
  border-radius: 0 18px 18px 0;
  margin-left: -2px;
}

/* make item (2nd column) stand out, like sample */
.items-table tbody td:nth-child(2) {
  font-weight: bold;
}

/* center S.NO and align price right */
.text-right { text-align: right; }
.text-center { text-align: center; }

.account-totals-row {
  margin-top: 20px;
}
.account-box {
  padding: 10px 12px;
  border-radius: 12px;
}
.account-title {
  font-weight: bold;
  margin-bottom: 6px;
}
.total-box {
  padding: 10px 12px;
  border-radius: 12px;
}
.total-table {
  width: 100%;
  font-size: 12px;
}
.total-table td {
  padding: 4px 0;
}
.total-table td:first-child {
  text-align: left;
}
.total-table td:last-child {
  text-align: right;
}
.total-amount-words {
  margin-top: 10px;
  padding: 8px 10px;
  border-radius: 10px;
}
.total-amount-words-title {
  font-weight: bold;
  color: #0b477d;
  margin-bottom: 3px;
}
.small-grey {
  color: #777;
  font-size: 10.5px;
}

/* sticky footer at bottom of page */
.footer-fixed {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0px;
  text-align: center;
}
.footer-note {
  font-weight: bold;
  font-size: 12.5px;
}
CSS;

// ---------- build items rows ----------
$rowsHtml = '';
if (!empty($items)) {
    foreach ($items as $it) {
        $rowsHtml .= '<tr>
          <td class="text-center">'.(int)$it['serail_no'].'</td>
          <td>'.h($it['item_name']).'</td>
          <td>'.nl2br(h($it['description'])).'</td>
          <td class="text-right">'.money_i($it['price']).'</td>
        </tr>';
    }
} else {
    $rowsHtml = '<tr><td colspan="4" class="text-center small-grey">No items</td></tr>';
}

if(!empty($companygst_no)){
    $gstHTML = '<div><strong>GST:</strong>'.$companygst_no.'</div>';
} else {
    $gstHTML = "";
}

// ---------- main HTML ----------
$html = <<<HTML
<div class="wrapper">
  <table class="header-table">
    <tr>
      <td style="width:25%;"></td>
      <td style="width:50%;" class="invoice-title">INVOICE</td>
      <td style="width:25%;" class="top-right"></td>
    </tr>
  </table>
  <table class="header-table">
    <tr>
      <td style="width:30%;">
        <img src="{$logoSrc}" class="logo-img">
      </td>
      <td style="width:20%;"></td>
      <td style="width:50%;" class="top-right">
        <span class="info-label">Invoice No. :</span> {$invNo}<br><br>
        <span class="info-label">Invoice Date :</span> {$invDate}<br><br>
        <span class="info-label">Currency :</span> {$currency}<br><br>
        {$roeHtml}
      </td>
    </tr>
  </table>

  <div class="hr-line"></div>

  <table class="section-table">
    <tr>
      <td style="width:50%; padding-right:12px; font-size: 14px;">
        <div class="block-title">Invoice to:</div><br>
        <div><strong>{$inv['agent_name']}</strong></div>
        <div>{$agentAddrHtml}</div>
        <div><strong>Phone:</strong> {$inv['phone_number']}</div>
        <div><strong>Email:</strong> {$inv['email_address']}</div>
        <div><strong>GST:</strong> {$inv['gst_number']}</div>
      </td>
      <td style="width:50%; padding-left:12px; font-size: 14px;">
        <div class="block-title">Invoice from:</div><br>
        <div><strong>{$companyName}</strong></div>
        <div>{$companyAddrHtml}</div>
        <div><strong>Phone:</strong> {$companyphone}</div>
        <div><strong>Email:</strong> {$companyemail}</div>
        {$gstHTML}
      </td>
    </tr>
  </table>

  <div style="margin-top:12px;">
    <div class="block-title">Invoice Description:</div>
    <div class="invoice-desc">{$invDesc}</div>
  </div>

  <table class="items-table">
    <thead>
      <tr class="items-header-row">
        <th style="width:50px;" class="text-center">S. NO.</th>
        <th class="text-left">ITEM</th>
        <th class="text-left">DESCRIPTIONS</th>
        <th style="width:90px;" class="text-right">PRICE</th>
      </tr>
    </thead>
    <tbody>
      {$rowsHtml}
    </tbody>
  </table>

  <table class="section-table account-totals-row">
    <tr>
      <td style="width:55%; padding-right:10px; font-size: 14px;">
        <div class="account-box">
          <div class="account-title">Account Details</div><br>
          <div><strong>{$companybank_name}</strong></div>
          <div>Company name: {$companyacc_name}</div>
          <div>Account number: {$companyacc_no}</div>
          <div>IFSC: {$companyacc_ifsc}</div>
          <div>SWIFT: {$companyswift_id}</div>
          <div>Branch: {$companybranch}</div>
        </div><br>
        <div class="account-box">
          <div><strong>{$companybank_2_name}</strong></div>
          <div>Company name: {$companybank_2_acc_name}</div>
          <div>Account number: {$companybank_2_acc_no}</div>
          <div>IFSC: {$companybank_2_ifsc}</div>
          <div>Branch: {$companybank_2_branch}</div>
        </div>  
      </td>
      <td style="width:45%; padding-left:10px; font-size: 14px;">
        <div class="total-box">
          <table class="total-table">
            <tr>
              <td><strong>TOTAL</strong></td>
              <td><strong>{$currencySymbol} {$fmtTotal}</strong></td>
            </tr>
            <tr>
              <td>SUBTOTAL IN INR</td>
              <td>₹ {$fmtSubtotalInr}</td>
            </tr>
            <tr>
              <td>GST (5%)</td>
              <td>₹ {$fmtGstInr}</td>
            </tr>
            <tr>
              <td><strong>TOTAL INCLUDING GST (INR)</strong></td>
              <td><strong>₹ {$fmtTotalGstInr}</strong></td>
            </tr>
          </table>
        </div><br>
        <div class="total-amount-words" style="font-size: 14px;">
          <div class="total-amount-words-title">TOTAL AMOUNT IN WORDS</div>
          <div>{$amountWordsHtml}</div>
        </div>
      </td>
    </tr>
  </table>
</div>

<div class="footer-fixed">
  <div class="footer-note">
    THANK YOU FOR YOUR BUSINESS
  </div>
  <div class="small-grey">
    This is a system-generated invoice.
  </div>
</div>
HTML;

// ---------- render ----------
$mpdf = new \Mpdf\Mpdf([
    'format'       => 'A4',
    'margin_left'  => 10,
    'margin_right' => 10,
    'margin_top'   => 5,
    'margin_bottom'=> 5,
]);

$mpdf->SetTitle($brand . ' - ' . $invNo);
$mpdf->WriteHTML($css, \Mpdf\HTMLParserMode::HEADER_CSS);
$mpdf->WriteHTML($html, \Mpdf\HTMLParserMode::HTML_BODY);

$mpdf->Output(
    $filename,
    $force_download ? \Mpdf\Output\Destination::DOWNLOAD : \Mpdf\Output\Destination::INLINE
);
exit;
