<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title><?= isset($page_title) ? $page_title : 'Invoice'; ?> - Multi-Unit Format</title>
  <?php include "comman/code_css.php"; ?>
  <link rel="shortcut icon" href="<?= $theme_link; ?>images/favicon.ico"/>

  <style>
    /* ====== PAGE SETUP ====== */
    @page{ 
      size: A4; 
      margin: 6mm; /* Reduced margins */
    }
    
    * { 
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }
    
    body {
      font-family: Arial, Helvetica, sans-serif;
      font-size: 12pt; /* Reduced from 10pt */
      line-height: 1.2; /* Reduced from 1.3 */
      color: #000;
      background: #fff;
      padding: 0;
      margin: 0;
      width: 100%;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
    }

    /* ====== MAIN CONTAINER ====== */
    .invoice-wrapper {
      width: 100%;
      max-width: 194mm; /* A4 width (210mm) - margins (16mm) */
      margin: 0 auto;
      background: #fff;
      border: 1px solid #000;
      overflow: hidden;
      page-break-inside: avoid;
    }

    /* ====== HEADER ====== */
    .header-bar {
      background: #E67E22; /* Warm color: orange */
      color: #fff;
      text-align: center;
      padding: 10px 0; /* Reduced from 15px */
      font-size: 18px; /* Reduced from 22px */
      font-weight: bold;
      letter-spacing: 2px; /* Reduced from 3px */
      text-transform: uppercase;
    }

    /* ====== TOP SECTION ====== */
    table {
      width: 100%;
      border-collapse: collapse;
      table-layout: auto;
    }

    .main-table {
      border: none;
      width: 100%;
      max-width: 100%;
    }

    .company-row td {
      padding: 8px; /* Reduced from 15px */
      vertical-align: top;
      border-bottom: 1px solid #000;
    }

    .logo-company-col {
      width: 60%;
      border-right: 1px solid #000;
      vertical-align: top;
    }

    .company-info {
      width: 50%;
      border-right: 1px solid #000;
    }

    .company-info.no-logo {
      width: 60%;
      border-right: 1px solid #000;
    }

    .logo-meta {
      width: 40%;
      text-align: right;
      vertical-align: top;
    }

    .logo-meta.no-logo {
      width: 40%;
    }

    .company-label {
      font-weight: bold;
      margin-bottom: 5px;
    }

    .company-detail {
      margin: 2px 0; /* Reduced from 3px */
      font-size: 8pt; /* Reduced from 9pt */
    }

    .logo-container {
      width: auto;
      max-width: 100px; /* Reduced from 120px */
      height: auto;
      max-height: 100px; /* Reduced from 120px */
      border: none;
      margin: 0;
      display: inline-block;
      vertical-align: top;
      background: transparent;
      overflow: hidden;
      border-radius: 0;
    }

    .logo-company-wrapper {
      display: flex;
      align-items: flex-start;
      gap: 15px;
      flex-wrap: nowrap;
    }

    .logo-container img {
      width: 100%;
      height: 100%;
      object-fit: contain;
      display: block;
    }

    .meta-table {
      width: auto;
      border: 1px solid #000;
      background: #fff;
      margin-left: auto;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }

    .meta-table td {
      padding: 3px 5px; /* Reduced padding */
      border: 1px solid #000;
      font-size: 8pt; /* Reduced from 9pt */
    }

    .meta-label {
      font-weight: bold;
      width: 40%;
    }

    /* ====== ADDRESS SECTION ====== */
    .address-row td {
      padding: 6px; /* Reduced from 12px */
      vertical-align: top;
      border-bottom: 1px solid #000;
    }

    .billing-col {
      width: 50%;
      border-right: 1px solid #000;
    }

    .shipping-col {
      width: 50%;
    }

    .address-title {
      font-weight: bold;
      font-size: 9pt; /* Reduced from 10pt */
      margin-bottom: 5px; /* Reduced from 8px */
      text-transform: uppercase;
      border-bottom: 1px solid #ccc;
      padding-bottom: 2px; /* Reduced from 3px */
    }

    .address-line {
      margin: 2px 0; /* Reduced from 3px */
      font-size: 8pt; /* Reduced from 9pt */
    }

    .address-line strong {
      display: inline-block;
      min-width: 70px;
    }

    /* ====== ITEMS TABLE ====== */
    .items-table {
      width: 100%;
      max-width: 100%;
      border-collapse: collapse;
      table-layout: fixed;
      word-wrap: break-word;
    }

    .items-table thead th {
      background: #000;
      border: 1px solid #000;
      padding: 5px 3px; /* Reduced from 8px 4px */
      white-space: normal;
      overflow: hidden;
      word-wrap: break-word;
      line-height: 1.2; /* Reduced from 1.3 */
      font-weight: bold;
      text-align: center;
      font-size: 8pt; /* Reduced from 8.5pt */
      color: #fff;
      letter-spacing: 0.2px; /* Reduced from 0.3px */
      text-transform: uppercase;
    }

    .items-table tbody td {
      border: 1px solid #000;
      padding: 4px 3px; /* Reduced from 6px 4px */
      font-size: 8pt; /* Reduced from 8.5pt */
      word-wrap: break-word;
      overflow: hidden;
    }

    .items-table .text-center {
      text-align: center;
    }

    .items-table .text-right {
      text-align: right;
    }

    .items-table .text-left {
      text-align: left;
    }

    .item-desc {
      color: #555;
      font-size: 7pt; /* Reduced from 8pt */
      margin-top: 1px; /* Reduced from 2px */
      font-style: italic;
    }

    .unit-label {
      font-size: 6.5pt; /* Reduced from 7pt */
      color: #666;
      margin-left: 2px;
    }

    /* ====== FOOTER SECTION ====== */
    .footer-row td {
      padding: 6px; /* Reduced from 12px */
      vertical-align: top;
      border-top: 1px solid #000;
    }

    .terms-col {
      width: 55%;
      border-right: 1px solid #000;
    }

    .totals-col {
      width: 45%;
    }

    .terms-title {
      font-weight: bold;
      margin-bottom: 5px; /* Reduced from 8px */
      font-size: 9pt; /* Reduced from 10pt */
    }

    .terms-text {
      font-size: 7.5pt; /* Reduced from 8pt */
      line-height: 1.3; /* Reduced from 1.4 */
    }

    .totals-table {
      width: 100%;
    }

    .totals-table td {
      padding: 4px 6px; /* Reduced from 6px 10px */
      border-bottom: 1px solid #ccc;
      font-size: 8pt; /* Reduced from 9pt */
    }

    .totals-table .tot-label {
      text-align: right;
      font-weight: 600;
    }

    .totals-table .tot-value {
      text-align: right;
      width: 35%;
      font-weight: bold;
    }

    .totals-table .grand-row td {
      border-top: 1px solid #000; /* Reduced from 2px */
      border-bottom: 1px solid #000; /* Reduced from 2px */
      font-size: 9pt; /* Reduced from 11pt */
      font-weight: bold;
      padding: 5px 6px; /* Reduced from 8px 10px */
    }

    /* ====== BOTTOM SECTION ====== */
    .bottom-row td {
      padding: 6px; /* Reduced from 12px */
      vertical-align: top;
      border-top: 1px solid #000;
    }

    .words-col {
      width: 60%;
      border-right: 1px solid #000;
    }

    .signature-col {
      width: 40%;
      text-align: center;
    }

    .words-title {
      font-weight: bold;
      margin-bottom: 3px; /* Reduced from 5px */
      font-size: 8pt; /* Reduced from 9pt */
    }

    .words-text {
      font-size: 8pt; /* Reduced from 9pt */
      font-style: italic;
    }

    .sig-line {
      border-top: 1px solid #000;
      margin: 30px 10px 5px 10px; /* Reduced margins */
    }

    .sig-label {
      font-weight: bold;
      font-size: 8pt; /* Reduced from 9pt */
    }

    /* ====== TAX SUMMARY SECTION ====== */
    .tax-summary-section {
      margin-top: 8px; /* Reduced from 15px */
      padding: 6px; /* Reduced from 12px */
      border-top: 1px solid #000; /* Reduced from 2px */
    }

    .tax-summary-title {
      font-weight: bold;
      font-size: 9pt; /* Reduced from 11pt */
      text-align: center;
      margin-bottom: 6px; /* Reduced from 10px */
      text-transform: uppercase;
      color: #333;
      letter-spacing: 0.5px; /* Reduced from 1px */
    }

    .tax-summary-table {
      width: 100%;
      border-collapse: collapse;
      margin-top: 8px;
    }

    .tax-summary-table thead th {
      background: #000;
      border: 1px solid #000;
      padding: 5px 3px; /* Reduced from 8px 5px */
      font-weight: bold;
      text-align: center;
      font-size: 8pt; /* Reduced from 9pt */
      color: #fff;
    }

    .tax-summary-table tbody td {
      border: 1px solid #000;
      padding: 4px 3px; /* Reduced from 6px 5px */
      font-size: 8pt; /* Reduced from 9pt */
      text-align: center;
    }

    .tax-summary-table tbody td.text-right {
      text-align: right;
    }

    .tax-summary-table tbody tr.total-row {
      background: #f0f0f0;
      font-weight: bold;
    }

    .tax-summary-table tbody tr.total-row td {
      border-top: 1px solid #000; /* Reduced from 2px */
      border-bottom: 1px solid #000; /* Reduced from 2px */
      font-size: 8pt; /* Reduced from 10pt */
    }

    /* ====== PRINT STYLES ====== */
  @media print {
  /* ====== PAGE SETUP ====== */
  @page {
    size: A4;
    margin: 8mm;
  }

  /* ====== BODY & WRAPPER ====== */
  body, .invoice-wrapper {
    background: #fff !important;
    color: #000 !important;
    font-family: "Arial", "Helvetica", sans-serif;
    font-size: 13pt;       /* Main body text slightly larger */
    line-height: 1.0;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    font-weight: 500;      /* Darker and clearer text */
    padding: 0;
    margin: 0;
    width: 100%;
    -webkit-print-color-adjust: exact !important;
    print-color-adjust: exact !important;
  }

  /* ====== HEADER ====== */
  .header-bar {
    background: #fff !important;
    color: #000 !important;
    font-size: 17px;       /* Bigger, readable header */
    font-weight: bold;
    text-transform: uppercase;
    text-align: center;
    padding: 10px 0;
  }

  /* ====== MAIN TABLES ====== */
  table, th, td {
    background: #fff !important;
    color: #000 !important;
    font-weight: 500;
    font-size: 10pt;
    border-collapse: collapse;
    -webkit-print-color-adjust: exact !important;
    print-color-adjust: exact !important;
  }

  /* ====== ITEMS TABLE ====== */
  .items-table thead th {
    background: #000 !important;  /* Keep header black */
    color: #fff !important;
    font-size: 11pt;             /* Larger header font */
    font-weight: bold;
    text-align: center;
    line-height: 1.0;
  }

  .items-table tbody td {
    background: #fff !important;
    color: #000 !important;
    font-size: 10pt;             /* Slightly larger for readability */
    word-wrap: break-word;
  }

  /* ====== TOTALS TABLE ====== */
  .totals-table td,
  .totals-table .grand-row td {
    font-size: 11pt;             /* Bigger for emphasis */
    font-weight: bold;
    color: #000 !important;
    border-bottom: 1px solid #000 !important;
  }

  .totals-table .tot-label,
  .totals-table .tot-value {
    text-align: right;
    font-weight: bold;
    color: #000 !important;
  }

  /* ====== TAX SUMMARY TABLE ====== */
  .tax-summary-table thead th {
    background: #000 !important;
    color: #fff !important;
    font-size: 10pt;
    font-weight: bold;
    text-align: center;
  }

  .tax-summary-table tbody td {
    background: #fff !important;
    color: #000 !important;
    font-size: 9pt;
    text-align: center;
  }

  .tax-summary-table tbody tr.total-row {
    background: #fff !important;
    font-weight: bold;
    font-size: 10pt;
  }

  /* ====== ADDRESS, BILLING & SHIPPING ====== */
  .address-row td,
  .company-row td,
  .meta-table td {
    background: #fff !important;
    color: #000 !important;
    font-size: 10pt;
    font-weight: 500;
  }

  /* ====== FOOTER / TERMS ====== */
  .footer-row td,
  .terms-text,
  .words-text {
    font-size: 9pt;
    color: #000 !important;
    font-weight: 500;
  }

  .terms-title, .words-title {
    font-size: 10pt;
    font-weight: bold;
  }

  .sig-label {
    font-size: 10pt;
    font-weight: bold;
    color: #000 !important;
  }

  /* ====== PAGE BREAKS ====== */
  .items-table thead {
    display: table-header-group;
  }

  .items-table tbody tr {
    page-break-inside: avoid;
  }

  /* ====== ENSURE PRINT COLORS AND NO GREY ====== */
  * {
    background: #fff !important;
    color: #000 !important;
    -webkit-print-color-adjust: exact !important;
    print-color-adjust: exact !important;
  }
}
  </style>
</head>
<body>

<?php
  /* ==================== DATA FETCH ==================== */
  error_reporting(E_ALL); 
  ini_set('display_errors', 1);

  if(!isset($sales_id) || empty($sales_id)){
    echo "<div style='padding:20px;color:red;'>Error: Sales ID is missing.</div>"; 
    exit;
  }

  // Store Info
  $q1 = $this->db->query("SELECT * FROM db_store WHERE status=1 AND id=".get_current_store_id());
  if($q1->num_rows() == 0){ 
    echo "<div style='padding:20px;color:red;'>Error: Store not found</div>"; 
    exit; 
  }
  $res1 = $q1->row();
  $store_name = $res1->store_name ?? '';
  $company_mobile = $res1->mobile ?? '';
  $company_phone = $res1->phone ?? '';
  $company_email = $res1->email ?? '';
  $company_address = $res1->address ?? '';
  $company_gst_no = $res1->gst_no ?? '';
  $company_vat_no = isset($res1->vat_no) && !empty($res1->vat_no) ? trim($res1->vat_no) : '';
  $company_pan_no = isset($res1->pan_no) && !empty($res1->pan_no) ? trim($res1->pan_no) : '';
  $store_logo = !empty($res1->store_logo) ? $res1->store_logo : '';
  $show_logo_on_invoice = isset($res1->show_logo_on_invoice) ? $res1->show_logo_on_invoice : 1; // Default to 1 if not set

  // Sales Info
  $q3 = $this->db->query("SELECT b.due_date, a.customer_name, a.mobile, a.phone, a.gstin, a.tax_number, 
                          a.email, a.shippingaddress_id, a.country_id, a.state_id, a.created_by,
                          a.postcode, a.address, b.sales_date, b.created_time, b.reference_no,
                          b.sales_code, b.sales_note, b.invoice_terms,
                          COALESCE(b.grand_total,0) as grand_total,
                          COALESCE(b.subtotal,0) as subtotal,
                          COALESCE(b.paid_amount,0) as paid_amount,
                          COALESCE(b.other_charges_amt,0) as other_charges_amt,
                          b.discount_to_all_input, b.discount_to_all_type,
                          COALESCE(b.tot_discount_to_all_amt,0) as tot_discount_to_all_amt,
                          COALESCE(b.round_off,0) as round_off,
                          b.transaction_currency_id, c.symbol as currency_symbol, c.currency_code
                  FROM db_customers a, db_sales b
                  LEFT JOIN db_currency c ON b.transaction_currency_id = c.id
                  WHERE a.id = b.customer_id AND b.id = '$sales_id'");
  
  if($q3->num_rows() == 0){ 
    echo "<div style='padding:20px;color:red;'>Error: Sales record not found.</div>"; 
    exit; 
  }
  $res3 = $q3->row();
  
  // Determine currency symbol and code to use from transaction currency
  $currency_symbol = '$'; // Default to base currency
  $currency_code = 'USD'; // Default currency code
  
  if (!empty($res3->transaction_currency_id) && !empty($res3->currency_symbol)) {
      // Use transaction's currency
      $currency_symbol = $res3->currency_symbol;
      $currency_code = !empty($res3->currency_code) ? $res3->currency_code : 'USD';
  } else {
      // Fallback to base currency
      if (function_exists('get_base_currency')) {
          $base_currency = get_base_currency();
          $currency_symbol = $base_currency->symbol;
          $currency_code = !empty($base_currency->currency_code) ? $base_currency->currency_code : 'USD';
      } else {
          $currency_symbol = '$'; // Ultimate fallback
          $currency_code = 'USD';
      }
  }
  
  // Helper function to format currency with correct symbol
  function format_currency_with_symbol($amount, $symbol) {
      // Ensure amount is numeric and not truncated
      $amount = floatval($amount);
      // Use store_number_format for consistent formatting (respects decimals setting)
      return $symbol . ' ' . store_number_format($amount, true, true);
  }
  
  // Helper function to format quantity - only show decimals if applicable
  function format_qty_smart($value) {
      $value = floatval($value);
      // Check if it's a whole number
      if (floor($value) == $value) {
          // Whole number - return without decimals
          return number_format($value, 0, '.', '');
      } else {
          // Has decimals - format with appropriate precision (up to 4 decimal places)
          $value_str = (string) $value;
          $actual_decimals = 0;
          if (strpos($value_str, '.') !== false) {
              $decimal_part = rtrim(substr($value_str, strpos($value_str, '.') + 1), '0');
              $actual_decimals = strlen($decimal_part);
          }
          // Use actual decimals found, but cap at 4
          $decimals = min(4, max(1, $actual_decimals));
          return number_format($value, $decimals, '.', '');
      }
  }

  $customer_name = $res3->customer_name ?? '';
  $customer_mobile = $res3->mobile ?? '';
  $customer_email = $res3->email ?? '';
  $customer_address = $res3->address ?? '';
  $customer_gst_no = $res3->gstin ?? '';
  $customer_tax_number = $res3->tax_number ?? '';
  $sales_date = $res3->sales_date ?? date('Y-m-d');
  $due_date = $res3->due_date ?? '';
  $reference_no = $res3->reference_no ?? '';
  $sales_code = $res3->sales_code ?? '';
  $sales_note = $res3->sales_note ?? '';
  $invoice_terms = $res3->invoice_terms ?? '';
  $subtotal = $res3->subtotal ?? 0;
  $grand_total = $res3->grand_total ?? 0;
  $other_charges_amt = $res3->other_charges_amt ?? 0;
  $paid_amount = $res3->paid_amount ?? 0;
  $discount_to_all_input = $res3->discount_to_all_input ?? 0;
  $discount_to_all_type = ($res3->discount_to_all_type == 'in_percentage') ? '%' : 'Fixed';
  $tot_discount_to_all_amt = $res3->tot_discount_to_all_amt ?? 0;
  
  // Get payment method(s) from db_salespayments
  $payment_methods = array();
  $q_payments = $this->db->query("SELECT DISTINCT payment_type 
                                   FROM db_salespayments 
                                   WHERE sales_id = '$sales_id' AND status = 1 
                                   AND payment_type IS NOT NULL 
                                   AND payment_type != ''
                                   ORDER BY payment_date DESC, id DESC");
  if($q_payments->num_rows() > 0){
    foreach($q_payments->result() as $pay){
      if(!empty($pay->payment_type)){
        $payment_methods[] = trim($pay->payment_type);
      }
    }
  }
  // Remove duplicates and create display string
  $payment_methods = array_unique($payment_methods);
  $payment_method_display = !empty($payment_methods) ? implode(', ', $payment_methods) : (!empty($reference_no) ? $reference_no : '-');
  $round_off = $res3->round_off ?? 0;
  $created_by = $res3->created_by ?? '';

  $sales_person = '';
  if(!empty($created_by)){
    $q_sp = $this->db->query("SELECT username FROM db_users WHERE id='$created_by'");
    if($q_sp->num_rows() > 0) $sales_person = $q_sp->row()->username;
  }

  // Shipping Address
  $shipping_name = $customer_name;
  $shipping_address = $customer_address;
  $shipping_mobile = $customer_mobile;
  $shipping_email = $customer_email;
  
  if(!empty($res3->shippingaddress_id)){
    $Q2 = $this->db->select("a.address, c.country, s.state, a.city, a.postcode")
                   ->where("a.id", $res3->shippingaddress_id)
                   ->from("db_shippingaddress a")
                   ->join("db_country c", "c.id=a.country_id", 'left')
                   ->join("db_states s", "s.id=a.state_id", 'left')
                   ->get();
    if($Q2->num_rows() > 0){
      $shipping_address = $Q2->row()->address;
      if(!empty($Q2->row()->city)) $shipping_address .= ', '.$Q2->row()->city;
      if(!empty($Q2->row()->state)) $shipping_address .= ', '.$Q2->row()->state;
      if(!empty($Q2->row()->country)) $shipping_address .= ', '.$Q2->row()->country;
      if(!empty($Q2->row()->postcode)) $shipping_address .= ' - '.$Q2->row()->postcode;
    }
  }

  // Tax Total
  $tax_amt_total = 0;
  $q_tax = $this->db->query("SELECT SUM(tax_amt) as total_tax FROM db_salesitems WHERE sales_id='$sales_id'");
  if($q_tax->num_rows() > 0) $tax_amt_total = $q_tax->row()->total_tax ?? 0;

  // Build Tax Summary
  $tax_summary_data = array();
  $tax_q4 = $this->db->query("SELECT a.tax_type, b.tax as tax_rate, b.tax_name,
                              a.total_cost, a.tax_amt, a.price_per_unit, a.sales_qty, a.discount_amt
                              FROM db_salesitems a 
                              JOIN db_tax b ON b.id = a.tax_id 
                              WHERE a.sales_id = '$sales_id'");
  
  foreach($tax_q4->result() as $t4_item) {
    $tax_rate = floatval($t4_item->tax_rate);
    $tax_key = $tax_rate . '%';
    if ($tax_rate == 0) {
      $tax_key = (stripos($t4_item->tax_name, 'exempt') !== false) ? 'exempt' : '0%';
    }
    
    if (!isset($tax_summary_data[$tax_key])) {
      $tax_summary_data[$tax_key] = array(
        'rate' => $tax_rate,
        'name' => $t4_item->tax_name,
        'taxable' => 0,
        'tax' => 0,
        'total' => 0
      );
    }
    
    $item_total_cost = floatval($t4_item->total_cost);
    $item_tax_amt = floatval($t4_item->tax_amt);
    
    // If values are invalid, recalculate
    if ($item_total_cost <= 0 || $item_total_cost == 1) {
      $item_price = floatval($t4_item->price_per_unit);
      $item_qty = floatval($t4_item->sales_qty);
      $item_discount = floatval($t4_item->discount_amt);
      
      if ($item_price > 0 && $item_qty > 0) {
        $base_amount = ($item_price * $item_qty) - $item_discount;
        if ($t4_item->tax_type == 'Inclusive') {
          if ($tax_rate > 0) {
            $item_taxable_amt = $base_amount / (1 + ($tax_rate / 100));
            $item_tax_amt = $base_amount - $item_taxable_amt;
          } else {
            $item_taxable_amt = $base_amount;
            $item_tax_amt = 0;
          }
          $item_total_cost = $base_amount;
        } else {
          $item_taxable_amt = $base_amount;
          if ($tax_rate > 0) {
            $item_tax_amt = $base_amount * ($tax_rate / 100);
          } else {
            $item_tax_amt = 0;
          }
          $item_total_cost = $item_taxable_amt + $item_tax_amt;
        }
      } else {
        $item_taxable_amt = max(0, $item_total_cost - $item_tax_amt);
      }
    } else {
      // Calculate taxable amount correctly based on tax type
      if ($t4_item->tax_type == 'Inclusive') {
        if ($tax_rate > 0 && $item_total_cost > 0) {
          $item_taxable_amt = $item_total_cost / (1 + ($tax_rate / 100));
          $item_tax_amt = $item_total_cost - $item_taxable_amt;
        } else {
          $item_taxable_amt = max(0, $item_total_cost - $item_tax_amt);
        }
      } else {
        $item_taxable_amt = $item_total_cost - $item_tax_amt;
      }
      if ($item_taxable_amt < 0) {
        $item_taxable_amt = 0;
      }
    }
    
    $tax_summary_data[$tax_key]['taxable'] += $item_taxable_amt;
    $tax_summary_data[$tax_key]['tax'] += $item_tax_amt;
    $tax_summary_data[$tax_key]['total'] += $item_total_cost;
  }
  
  // Sort by tax rate descending
  krsort($tax_summary_data);

  // Check if any items have alternate units
  $has_alternate_units = false;
  $items_check_query = $this->db->query("SELECT c.alternate_unit_id, c.conversion_factor, 
                                        a.sales_qty_alternate, a.unit_type
                                        FROM db_salesitems a
                                        JOIN db_items c ON c.id = a.item_id
                                        WHERE a.sales_id = '$sales_id'
                                        LIMIT 1");
  if($items_check_query->num_rows() > 0){
    $this->db->select("c.alternate_unit_id, c.conversion_factor, a.sales_qty_alternate, a.unit_type");
    $this->db->from("db_salesitems a");
    $this->db->join("db_items c", "c.id = a.item_id", "left");
    $this->db->where("a.sales_id", $sales_id);
    $items_check = $this->db->get();
    
    foreach($items_check->result() as $item_check){
      $conv = !empty($item_check->conversion_factor) ? floatval($item_check->conversion_factor) : 1.0;
      if(!empty($item_check->alternate_unit_id) && $conv > 0 && $conv != 1.0){
        $has_alternate_units = true;
        break;
      }
      if(!empty($item_check->sales_qty_alternate) && floatval($item_check->sales_qty_alternate) > 0){
        $has_alternate_units = true;
        break;
      }
      if($item_check->unit_type == 'alternate'){
        $has_alternate_units = true;
        break;
      }
    }
  }

  // Check if any items have tax
  $has_tax = false;
  $tax_check = $this->db->query("SELECT COUNT(*) as tax_count FROM db_salesitems WHERE sales_id = '$sales_id' AND tax_amt > 0");
  if($tax_check->num_rows() > 0 && $tax_check->row()->tax_count > 0){
    $has_tax = true;
  }
?>

<div class="invoice-wrapper">
  
  <!-- HEADER -->
  <div class="header-bar">INVOICE</div>

  <!-- MAIN TABLE -->
  <table class="main-table">
    
    <!-- COMPANY & LOGO ROW -->
    <tr class="company-row">
      <?php if($show_logo_on_invoice == 1 && !empty($store_logo)): ?>
      <td class="logo-company-col">
        <div class="logo-company-wrapper">
          <div class="logo-container" style="flex-shrink:0;">
            <img src="<?= base_url($store_logo); ?>" alt="Logo" style="max-width:120px;max-height:120px;object-fit:contain;display:block;">
          </div>
          <div style="flex:1;padding-left:10px;vertical-align:top;">
            <div class="company-detail" style="font-weight:bold;font-size:11pt;margin-bottom:5px;margin-top:0;"><?= $store_name; ?></div>
            <?php if(!empty($company_address)): ?>
            <div class="company-detail" style="margin:2px 0;"><?= $company_address; ?></div>
            <?php endif; ?>
            <?php if(!empty($company_mobile) || !empty($company_phone)): ?>
            <div class="company-detail" style="margin:2px 0;"><?= $this->lang->line('phone'); ?>: <?= !empty($company_mobile) ? $company_mobile : '' ?><?= (!empty($company_mobile) && !empty($company_phone)) ? ', ' : '' ?><?= !empty($company_phone) ? $company_phone : '' ?></div>
            <?php endif; ?>
            <?php if(!empty($company_email)): ?>
            <div class="company-detail" style="margin:2px 0;"><?= $company_email; ?></div>
            <?php endif; ?>
            <?php if(!empty($company_pan_no)): ?>
            <div class="company-detail" style="margin:2px 0;"><strong>VAT No:</strong> <?= htmlspecialchars($company_pan_no); ?></div>
            <?php endif; ?>
            <?php if(!empty($company_gst_no)): ?>
            <div class="company-detail" style="margin:2px 0;"><strong>TAX No:</strong> <?= htmlspecialchars($company_gst_no); ?></div>
            <?php endif; ?>
            <?php if(!empty($company_vat_no) && $company_vat_no != $company_gst_no): ?>
            <div class="company-detail" style="margin:2px 0;"><strong>PIN No:</strong> <?= htmlspecialchars($company_vat_no); ?></div>
            <?php endif; ?>
          </div>
        </div>
      </td>
      <td class="logo-meta">
        <table class="meta-table">
          <tr>
            <td class="meta-label">Date:</td>
            <td><?= show_date($sales_date); ?></td>
          </tr>
          <tr>
            <td class="meta-label">Invoice No:</td>
            <td><?= $sales_code; ?></td>
          </tr>
          <tr>
            <td class="meta-label">Payment Mode:</td>
            <td><?= $payment_method_display; ?></td>
          </tr>
        </table>
      </td>
      <?php else: ?>
      <td class="company-info no-logo">
        <div class="company-detail" style="font-weight:bold;font-size:11pt;margin-bottom:5px;"><?= $store_name; ?></div>
        <?php if(!empty($company_address)): ?>
        <div class="company-detail"><?= $company_address; ?></div>
        <?php endif; ?>
        <?php if(!empty($company_mobile) || !empty($company_phone)): ?>
        <div class="company-detail"><?= $this->lang->line('phone'); ?>: <?= !empty($company_mobile) ? $company_mobile : '' ?><?= (!empty($company_mobile) && !empty($company_phone)) ? ', ' : '' ?><?= !empty($company_phone) ? $company_phone : '' ?></div>
        <?php endif; ?>
        <?php if(!empty($company_email)): ?>
        <div class="company-detail"><?= $company_email; ?></div>
        <?php endif; ?>
        <?php if(!empty($company_pan_no)): ?>
        <div class="company-detail"><strong>VAT No:</strong> <?= htmlspecialchars($company_pan_no); ?></div>
        <?php endif; ?>
        <?php if(!empty($company_gst_no)): ?>
        <div class="company-detail"><strong>TAX No:</strong> <?= htmlspecialchars($company_gst_no); ?></div>
        <?php endif; ?>
        <?php if(!empty($company_vat_no) && $company_vat_no != $company_gst_no): ?>
        <div class="company-detail"><strong>PIN No:</strong> <?= htmlspecialchars($company_vat_no); ?></div>
        <?php endif; ?>
      </td>
      <td class="logo-meta no-logo">
        <table class="meta-table">
          <tr>
            <td class="meta-label">Date:</td>
            <td><?= show_date($sales_date); ?></td>
          </tr>
          <tr>
            <td class="meta-label">Invoice No:</td>
            <td><?= $sales_code; ?></td>
          </tr>
          <tr>
            <td class="meta-label">Payment Mode:</td>
            <td><?= $payment_method_display; ?></td>
          </tr>
        </table>
      </td>
      <?php endif; ?>
    </tr>

    <!-- BILLING & SHIPPING ROW -->
    <tr class="address-row">
      <td class="billing-col">
        <div class="address-title">Billing To:</div>
        <div class="address-line"><strong>Name:</strong> <?= $customer_name; ?></div>
        <?php if(!empty($customer_gst_no)): ?>
        <div class="address-line"><strong>Tax number:</strong> <?= $customer_gst_no; ?></div>
        <?php elseif(!empty($customer_tax_number)): ?>
        <div class="address-line"><strong>Tax number:</strong> <?= $customer_tax_number; ?></div>
        <?php endif; ?>
        <?php if(!empty($customer_mobile)): ?>
        <div class="address-line"><strong>Phone:</strong> <?= $customer_mobile; ?></div>
        <?php endif; ?>
      </td>
      <td class="shipping-col">
        <div class="address-title">Shipping To:</div>
        <div class="address-line"><strong>Name:</strong> <?= $shipping_name; ?></div>
        <?php if(!empty($shipping_address)): ?>
        <div class="address-line"><strong>Address:</strong> <?= $shipping_address; ?></div>
        <?php endif; ?>
        <?php if(!empty($shipping_mobile)): ?>
        <div class="address-line"><strong>Phone:</strong> <?= $shipping_mobile; ?></div>
        <?php endif; ?>
        <?php if(!empty($shipping_email)): ?>
        <div class="address-line"><strong>Email:</strong> <?= $shipping_email; ?></div>
        <?php endif; ?>
      </td>
    </tr>

  </table>

  <!-- ITEMS TABLE -->
  <table class="items-table">
    <thead>
      <tr>
        <th style="width:<?= $has_alternate_units ? '3%' : '4%'; ?>">NO</th>
        <th style="width:<?= $has_alternate_units ? ($has_tax ? '24%' : '28%') : ($has_tax ? '30%' : '35%'); ?>">Description</th>
        <th style="width:<?= $has_alternate_units ? '6%' : '7%'; ?>">QTY</th>
        <th style="width:<?= $has_alternate_units ? '7%' : '8%'; ?>">Unit</th>
        <?php if($has_alternate_units): ?>
        <th style="width:7%;">Alt</th>
        <?php endif; ?>
        <th style="width:<?= $has_alternate_units ? ($has_tax ? '9%' : '11%') : ($has_tax ? '10%' : '12%'); ?>">Rate</th>
        <th style="width:<?= $has_alternate_units ? ($has_tax ? '9%' : '11%') : ($has_tax ? '10%' : '12%'); ?>">Disc.</th>
        <?php if($has_tax): ?>
        <th style="width:<?= $has_alternate_units ? '9%' : '10%'; ?>">Tax Amt</th>
        <?php endif; ?>
        <th style="width:<?= $has_alternate_units ? ($has_tax ? '18%' : '22%') : ($has_tax ? '20%' : '24%'); ?>">Amount</th>
      </tr>
    </thead>
    <tbody>
      <?php
        $i = 1;
        $tot_qty = 0;
        $tot_amount = 0;
        $tot_discount = 0;

        $this->db->select("a.description, c.item_name, a.sales_qty, a.sales_qty_main, a.sales_qty_alternate, a.unit_type, a.tax_type,
                          a.price_per_unit, b.tax, b.tax_name, a.tax_amt,
                          a.discount_input, a.discount_amt, a.unit_total_cost, a.total_cost, 
                          d.unit_name as main_unit_name, e.unit_name as alternate_unit_name,
                          c.conversion_factor, a.batch_number, a.expiry_date, c.batch_tracking_enabled");
        $this->db->from("db_salesitems a");
        $this->db->join("db_tax b", "b.id=a.tax_id", "left");
        $this->db->join("db_items c", "c.id=a.item_id", "left");
        $this->db->join("db_units d", "d.id=c.unit_id", "left");
        $this->db->join("db_units e", "e.id=c.alternate_unit_id", "left");
        $this->db->where("a.sales_id", $sales_id);
        $q2 = $this->db->get();

        foreach($q2->result() as $r):
          $discount_amt = (empty($r->discount_amt) || $r->discount_input == 0) ? 0 : $r->discount_amt;
          
          // Get original price_per_unit to preserve precision
          $ppu_original = $r->price_per_unit;
          $ppu = floatval($ppu_original);
          
          // For tax-inclusive items, calculate rate without tax for display
          if($r->tax_type == 'Inclusive' && floatval($r->sales_qty) > 0){
            $ppu = $ppu - ($r->tax_amt / $r->sales_qty);
          }

          $conversion = !empty($r->conversion_factor) ? floatval($r->conversion_factor) : 1.0;
          $qty_main = 0;
          $qty_alt = 0;
          
          // Determine quantities based on what was actually sold
          // Priority 1: Use sales_qty_main and sales_qty_alternate if both are set (most accurate)
          // Priority 2: Use sales_qty_main if set, calculate alternate
          // Priority 3: Use unit_type to determine which unit sales_qty is in, then convert
          
          if(!empty($r->sales_qty_main) && $r->sales_qty_main > 0){
            // sales_qty_main is set - use it for main unit
            $qty_main = floatval($r->sales_qty_main);
            
            // Check if sales_qty_alternate is also set (most accurate)
            if(!empty($r->sales_qty_alternate) && $r->sales_qty_alternate > 0){
              $qty_alt = floatval($r->sales_qty_alternate);
            } elseif($conversion > 0 && $conversion != 1.0){
              // Calculate alternate from main
              $qty_alt = $qty_main * $conversion;
            } else {
              $qty_alt = $qty_main;
            }
          } elseif($r->unit_type == 'alternate' && $conversion > 0 && $conversion != 1.0){
            // Sold in alternate unit - sales_qty is in alternate units (e.g., 25 kgs)
            $qty_alt = floatval($r->sales_qty); // This is what was actually sold (25 kgs)
            $qty_main = $qty_alt / $conversion; // Convert to main unit (25 / 50 = 0.5 bags)
          } else {
            // Sold in main unit - sales_qty is in main units
            $qty_main = floatval($r->sales_qty);
            if($conversion > 0 && $conversion != 1.0){
              $qty_alt = $qty_main * $conversion; // Convert to alternate unit
            } else {
              $qty_alt = $qty_main;
            }
          }
          
          // Round to 4 decimal places for accuracy
          $qty_main = round($qty_main, 4);
          $qty_alt = round($qty_alt, 4);

          $tot_qty += $r->sales_qty;
          $tot_amount += $r->total_cost;
          $tot_discount += $discount_amt;
      ?>
      <tr>
        <td class="text-center"><?= $i++; ?></td>
        <td class="text-left">
          <?= $r->item_name; ?>
          <?php if(!empty($r->description)): ?>
            <div class="item-desc"><?= $r->description; ?></div>
          <?php endif; ?>
          <?php if(false && $r->batch_tracking_enabled == 1): ?>
            <?php
            $batch_display = '';
            if(!empty($r->batch_number)){
              $batch_display = 'Batch: ' . $r->batch_number;
            }
            if(!empty($r->expiry_date) && $r->expiry_date != '0000-00-00'){
              $exp_date = date('jS-M-Y', strtotime($r->expiry_date));
              // Calculate days to expiry
              $today = new DateTime();
              $expiry_dt = new DateTime($r->expiry_date);
              $diff = $today->diff($expiry_dt);
              $days_remaining = $diff->invert ? -$diff->days : $diff->days;
              $days_style = '';
              $days_label = '';
              if($days_remaining < 0) {
                $days_style = 'color:#d9534f;';
                $days_label = 'Expired';
              } elseif($days_remaining <= 30) {
                $days_style = 'color:#f0ad4e;';
                $days_label = $days_remaining.'d';
              } else {
                $days_style = 'color:#5cb85c;';
                $days_label = $days_remaining.'d';
              }
              if(!empty($batch_display)){
                $batch_display .= ' | Expiry: ' . $exp_date . ' <span style="'.$days_style.'">('.$days_label.')</span>';
              } else {
                $batch_display = 'Expiry: ' . $exp_date . ' <span style="'.$days_style.'">('.$days_label.')</span>';
              }
            }
            if(!empty($batch_display)):
            ?>
            <div class="item-desc"><?= $batch_display; ?></div>
            <?php endif; ?>
          <?php endif; ?>
        </td>
        <td class="text-center">
          <?php 
            // Display the quantity in the unit that was actually sold
            // Use smart formatting - only show decimals if applicable
            if($r->unit_type == 'alternate' && !empty($r->alternate_unit_name)){
              // Sold in alternate unit - show alternate qty and unit
              echo format_qty_smart($qty_alt);
            } else {
              // Sold in main unit - show main qty
              echo format_qty_smart($r->sales_qty);
            }
          ?>
        </td>
        <td class="text-center">
          <?php 
            // Display the unit that was actually used for sale
            if($r->unit_type == 'alternate' && !empty($r->alternate_unit_name)){
              // Sold in alternate unit (e.g., KGS)
              echo ucfirst(strtolower($r->alternate_unit_name));
            } elseif(!empty($r->main_unit_name)){
              // Sold in main unit (e.g., BAGS, PCS)
              echo ucfirst(strtolower($r->main_unit_name));
            } else {
              echo '-';
            }
          ?>
        </td>
        <?php if($has_alternate_units): ?>
        <td class="text-center">
          <?php 
            $item_has_alt = (!empty($r->alternate_unit_id) && $conversion > 0 && $conversion != 1.0);
            if($item_has_alt && !empty($r->alternate_unit_name)):
          ?>
            <?= ucfirst(strtolower($r->alternate_unit_name)); ?>
          <?php else: ?>
            -
          <?php endif; ?>
        </td>
        <?php endif; ?>
        <td class="text-right"><?php
          // Format rate with proper decimals, removing unnecessary trailing zeros
          $rate_decimals = decimals();
          $rate_value = $ppu;
          
          // Get original price_per_unit as string to check precision
          $original_rate_str = (string)$ppu_original;
          
          // Check actual significant decimal places (excluding trailing zeros)
          $actual_decimals = 0;
          if (strpos($original_rate_str, '.') !== false) {
            $decimal_part = rtrim(substr($original_rate_str, strpos($original_rate_str, '.') + 1), '0');
            $actual_decimals = strlen($decimal_part);
          }
          
          // Use the greater of configured decimals or actual significant decimals (up to 6 for rates)
          $display_decimals = min(6, max($rate_decimals, $actual_decimals));
          
          // Format with proper decimals
          $formatted_rate = number_format($rate_value, $display_decimals, '.', ',');
          
          // Remove unnecessary trailing zeros while maintaining at least store decimals
          if ($display_decimals > 0 && strpos($formatted_rate, '.') !== false) {
            // Keep at least the store's configured decimals
            $min_decimals = $rate_decimals;
            $formatted_rate = rtrim(rtrim($formatted_rate, '0'), '.');
            
            // If we removed too many decimals, add back the minimum
            if (strpos($formatted_rate, '.') === false && $min_decimals > 0) {
              $formatted_rate = number_format($rate_value, $min_decimals, '.', ',');
            } elseif (strpos($formatted_rate, '.') !== false) {
              $current_decimals = strlen(substr($formatted_rate, strpos($formatted_rate, '.') + 1));
              if ($current_decimals < $min_decimals) {
                $formatted_rate = number_format($rate_value, $min_decimals, '.', ',');
              }
            }
          }
          
          echo $formatted_rate;
        ?></td>
        <td class="text-right"><?= store_number_format($discount_amt); ?></td>
        <?php if($has_tax): ?>
        <td class="text-right"><?= store_number_format($r->tax_amt); ?></td>
        <?php endif; ?>
        <td class="text-right"><?= store_number_format($r->total_cost); ?></td>
      </tr>
      <?php endforeach; ?>
    </tbody>
  </table>

  <!-- FOOTER TABLE -->
  <table class="main-table">
    
    <!-- TERMS & TOTALS ROW -->
    <tr class="footer-row">
      <td class="terms-col">
        <div class="terms-title">Terms & Conditions:</div>
        <div class="terms-text">
          <?php if(!empty($invoice_terms)): ?>
            <?= nl2br(html_entity_decode($invoice_terms)); ?>
          <?php endif; ?>
          <?php if(!empty($sales_note)): ?>
            <div style="margin-top:6px;"><strong>Note:</strong> <?= $sales_note; ?></div>
          <?php endif; ?>
        </div>
      </td>
      <td class="totals-col">
        <table class="totals-table">
          <tr>
            <td class="tot-label">Subtotal:</td>
            <td class="tot-value"><?php echo format_currency_with_symbol($subtotal, $currency_symbol); ?></td>
          </tr>
          <?php if($tot_discount > 0): ?>
          <tr>
            <td class="tot-label">Item Disc.:</td>
            <td class="tot-value"><?php echo format_currency_with_symbol($tot_discount, $currency_symbol); ?></td>
          </tr>
          <?php endif; ?>
          <?php if($other_charges_amt > 0): ?>
          <tr>
            <td class="tot-label">Other Charges:</td>
            <td class="tot-value"><?php echo format_currency_with_symbol($other_charges_amt, $currency_symbol); ?></td>
          </tr>
          <?php endif; ?>
          <?php if($tot_discount_to_all_amt > 0): ?>
          <tr>
            <td class="tot-label">Discount (<?= store_number_format($discount_to_all_input)." ".$discount_to_all_type; ?>):</td>
            <td class="tot-value"><?php echo format_currency_with_symbol($tot_discount_to_all_amt, $currency_symbol); ?></td>
          </tr>
          <?php endif; ?>
          <?php if($tax_amt_total > 0): ?>
          <tr>
            <td class="tot-label">Tax Amount:</td>
            <td class="tot-value"><?php echo format_currency_with_symbol($tax_amt_total, $currency_symbol); ?></td>
          </tr>
          <?php endif; ?>
          <?php if($round_off != 0): ?>
          <tr>
            <td class="tot-label">Round Off:</td>
            <td class="tot-value"><?php echo format_currency_with_symbol($round_off, $currency_symbol); ?></td>
          </tr>
          <?php endif; ?>
          <tr class="grand-row">
            <td class="tot-label">Grand Total:</td>
            <td class="tot-value"><?php echo format_currency_with_symbol($grand_total, $currency_symbol); ?></td>
          </tr>
        </table>
      </td>
    </tr>

    <!-- TAX SUMMARY ROW -->
    <tr>
      <td colspan="2" style="padding: 0;">
        <div class="tax-summary-section">
          <div class="tax-summary-title">Tax Summary</div>
          <table class="tax-summary-table">
            <thead>
              <tr>
                <th style="width: 20%;">Tax Rate</th>
                <th style="width: 26%;">Taxable Amount</th>
                <th style="width: 26%;">Tax Amount</th>
                <th style="width: 28%;">Total Amount</th>
              </tr>
            </thead>
            <tbody>
              <?php
              $s4_taxable = 0; $s4_tax = 0; $s4_total = 0;
              foreach($tax_summary_data as $key => $t4) {
                $t4_label = $t4['rate'] . '%';
                if ($key == 'exempt') {
                  $t4_label = 'Exempt';
                } elseif ($t4['rate'] == 0) {
                  $t4_label = '0%';
                }
                $s4_taxable += $t4['taxable']; 
                $s4_tax += $t4['tax']; 
                $s4_total += $t4['total'];
              ?>
              <tr>
                <td><?= $t4_label; ?></td>
                <td class="text-right"><?php echo format_currency_with_symbol($t4['taxable'], $currency_symbol); ?></td>
                <td class="text-right"><?php echo format_currency_with_symbol($t4['tax'], $currency_symbol); ?></td>
                <td class="text-right"><?php echo format_currency_with_symbol($t4['total'], $currency_symbol); ?></td>
              </tr>
              <?php } ?>
              <tr class="total-row">
                <td><strong>Total</strong></td>
                <td class="text-right"><strong><?php echo format_currency_with_symbol($s4_taxable, $currency_symbol); ?></strong></td>
                <td class="text-right"><strong><?php echo format_currency_with_symbol($s4_tax, $currency_symbol); ?></strong></td>
                <td class="text-right"><strong><?php echo format_currency_with_symbol($s4_total, $currency_symbol); ?></strong></td>
              </tr>
            </tbody>
          </table>
        </div>
      </td>
    </tr>

    <!-- AMOUNT IN WORDS & SIGNATURE ROW -->
    <tr class="bottom-row">
      <td class="words-col">
        <div class="words-title">Total Amount in Word</div>
        <div class="words-text">
          <?= no_to_words($grand_total, $currency_code); ?>
        </div>
      </td>
      <td class="signature-col">
        <div class="sig-line"></div>
        <div class="sig-label">Seal & Signature</div>
      </td>
    </tr>

  </table>

</div> <!-- End invoice-wrapper -->
</div> <!-- End invoice-a4-container -->

<!-- Print and Close Buttons -->
<div class="invoice-actions" style="position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%); z-index: 1000; display: flex; gap: 10px;">
  <button onclick="window.print()" class="btn-print" style="background: #800080; color: white; border: none; padding: 12px 24px; border-radius: 5px; cursor: pointer; font-size: 14px; font-weight: 600; box-shadow: 0 2px 8px rgba(0,0,0,0.2);">
    <i class="fa fa-print"></i> Print
  </button>
  <button onclick="goBack()" class="btn-back" style="background: #6c757d; color: white; border: none; padding: 12px 24px; border-radius: 5px; cursor: pointer; font-size: 14px; font-weight: 600; box-shadow: 0 2px 8px rgba(0,0,0,0.2);">
    <i class="fa fa-times"></i> Close
  </button>
</div>

<style>
  @media print {
    .invoice-actions {
      display: none !important;
    }
  }
  .btn-print:hover {
    background: #0056b3 !important;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.3) !important;
  }
  .btn-back:hover {
    background: #5a6268 !important;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.3) !important;
  }
  .btn-print:active, .btn-back:active {
    transform: translateY(0);
  }
</style>

<script>
function goBack() {
  var backUrl = '<?= isset($back_url) ? $back_url : base_url("sales/invoice/".$sales_id) ?>';
  
  // Try to go back in history first
  if (window.history.length > 1) {
    try {
      window.history.back();
      // Fallback: if back doesn't work after 500ms, redirect
      setTimeout(function() {
        window.location.href = backUrl;
      }, 500);
    } catch(e) {
      window.location.href = backUrl;
    }
  } else {
    // No history, redirect to invoice page
    window.location.href = backUrl;
  }
}
</script>

</body>
</html>