<!DOCTYPE html>
<html>
<title><?= $page_title;?> - Default Invoice</title>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel='shortcut icon' href='<?php echo $theme_link; ?>images/favicon.ico' />
<style>
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

html {
    height: auto !important;
    min-height: auto !important;
    overflow: visible !important;
    width: 100%;
}

body {
    font-family: 'Segoe UI', 'Open Sans', Arial, sans-serif;
    font-size: 12px;
    color: #333;
    background: #fff;
    line-height: 1.4;
    margin: 0;
    padding: 20px;
    min-height: auto;
    height: auto;
    overflow-x: hidden;
    overflow-y: visible;
    display: block;
}

/* Header */
.invoice-header {
    background: linear-gradient(135deg, #2c3e50 0%, #1a252f 100%);
    color: #fff;
    padding: 12px 20px;
    display: table;
    width: 100%;
}
.header-left {
    display: table-cell;
    width: 70%;
    vertical-align: middle;
}
.header-right {
    display: table-cell;
    width: 30%;
    text-align: right;
    vertical-align: middle;
}
.invoice-title {
    font-size: 20px;
    font-weight: 700;
    letter-spacing: 1px;
}
.invoice-status {
    display: inline-block;
    padding: 3px 10px;
    border-radius: 3px;
    font-size: 11px;
    font-weight: 600;
    text-transform: uppercase;
}
.status-paid { background: #27ae60; }
.status-partial { background: #f39c12; }
.status-unpaid { background: #e74c3c; }

/* Company Section */
.company-section {
    display: table;
    width: 100%;
    max-width: 100%;
    border-bottom: 2px solid #2c3e50;
    box-sizing: border-box;
}
.company-info {
    display: table-cell;
    width: 60%;
    padding: 15px 20px;
    vertical-align: top;
}
.invoice-meta {
    display: table-cell;
    width: 40%;
    padding: 15px 20px;
    vertical-align: top;
    border-left: 1px solid #e0e0e0;
}
.company-name {
    font-size: 18px;
    font-weight: 700;
    color: #2c3e50;
    margin-bottom: 8px;
}
.info-line {
    margin-bottom: 3px;
    font-size: 11px;
}
.meta-row {
    display: table;
    width: 100%;
    margin-bottom: 5px;
}
.meta-label {
    display: table-cell;
    width: 40%;
    font-weight: 600;
    color: #555;
    font-size: 11px;
}
.meta-value {
    display: table-cell;
    width: 60%;
    font-size: 11px;
    color: #333;
}

/* Customer/Shipping Section */
.address-section {
    display: table;
    width: 100%;
    max-width: 100%;
    border-bottom: 2px solid #2c3e50;
    box-sizing: border-box;
}
.address-box {
    display: table-cell;
    width: 50%;
    padding: 12px 20px;
    vertical-align: top;
}
.address-box:first-child {
    border-right: 1px solid #e0e0e0;
}
.address-title {
    background: #ecf0f1;
    color: #2c3e50;
    font-size: 11px;
    font-weight: 700;
    text-transform: uppercase;
    padding: 5px 10px;
    margin: -12px -20px 10px -20px;
    letter-spacing: 0.5px;
}

/* Items Table */
.items-table {
    width: 100%;
    max-width: 100%;
    border-collapse: collapse;
    box-sizing: border-box;
    table-layout: auto;
    display: table;
}
.items-table thead th {
    background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
    color: #fff;
    padding: 10px 8px;
    font-size: 11px;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.3px;
    border: 1px solid #2c3e50;
}
.items-table tbody {
    display: table-row-group;
}

.items-table tbody tr {
    display: table-row;
}

.items-table tbody td {
    padding: 8px;
    border: 1px solid #ddd;
    vertical-align: top;
    font-size: 11px;
    display: table-cell;
}
.items-table tbody tr:nth-child(even) {
    background-color: #f8f9fa;
}
.items-table tbody tr:hover {
    background-color: #ecf0f1;
}
.text-right { text-align: right; }
.text-center { text-align: center; }
.item-name { font-weight: 600; color: #2c3e50; }
.batch-info { font-size: 9px; color: #555; margin-top: 3px; }

/* Totals */
.totals-section {
    width: 100%;
    max-width: 100%;
    border-collapse: collapse;
    box-sizing: border-box;
    display: table;
}

.totals-section tr {
    display: table-row;
}
.totals-section td {
    padding: 8px 15px;
    border: 1px solid #ddd;
}
.totals-section .label-cell {
    text-align: right;
    font-weight: 500;
    color: #555;
    background: #f8f9fa;
}
.totals-section .value-cell {
    text-align: right;
    font-weight: 600;
    width: 120px;
}
.totals-section .grand-total-row td {
    background: linear-gradient(135deg, #2c3e50 0%, #1a252f 100%);
    color: #fff;
    font-size: 13px;
    font-weight: 700;
    padding: 10px 15px;
}
.totals-section .total-row td {
    background: #ecf0f1;
    font-weight: 700;
}

/* Tax Summary */
.tax-summary-container {
    padding: 15px 20px;
    background: #f8f9fa;
    border-top: 1px solid #ddd;
    display: block;
    visibility: visible;
    opacity: 1;
}
.tax-summary-title {
    font-size: 12px;
    font-weight: 700;
    color: #2c3e50;
    margin-bottom: 10px;
    text-transform: uppercase;
}
.tax-summary-table {
    width: 60%;
    border-collapse: collapse;
    font-size: 11px;
    display: table;
}

.tax-summary-table tbody {
    display: table-row-group;
}

.tax-summary-table tbody tr {
    display: table-row;
}

.tax-summary-table tbody td {
    display: table-cell;
}
.tax-summary-table th {
    background: #34495e;
    color: #fff;
    padding: 8px 10px;
    font-weight: 600;
    border: 1px solid #2c3e50;
}
.tax-summary-table td {
    padding: 6px 10px;
    border: 1px solid #ddd;
    background: #fff;
}
.tax-summary-table tr:nth-child(even) td {
    background: #f8f9fa;
}
.tax-summary-table .total-row td {
    background: #ecf0f1;
    font-weight: 700;
}

/* Signatures */
.signatures-section {
    display: table;
    width: 100%;
    padding: 40px 20px 20px 20px;
    border-top: 1px solid #ddd;
}
.signature-box {
    display: table-cell;
    width: 50%;
    text-align: center;
    padding-top: 40px;
    border-top: 1px dashed #999;
    font-size: 11px;
    color: #666;
    font-weight: 500;
}

/* Footer */
.invoice-footer {
    background: #ecf0f1;
    padding: 10px 20px;
    text-align: center;
    font-size: 10px;
    color: #666;
    border-top: 1px solid #ddd;
}

@page {
    size: A4 !important;
    margin: 0 15mm 0 15mm !important; /* Left and right margins only - borders will be on top/bottom */
}

/* A4 Invoice Container */
.invoice-a4-container {
  width: 100%;
  max-width: 180mm; /* A4 width (210mm) - left margin (15mm) - right margin (15mm) = 180mm */
  margin: 0 auto;
  padding: 0;
  background: #fff;
  box-sizing: border-box;
  overflow: visible !important;
  min-height: auto !important;
  height: auto !important;
  position: relative;
}

.invoice-container {
    width: 100%;
    max-width: 100%;
    margin: 0;
    background: #fff;
    border: 1px solid #000; /* Border on all sides around invoice content - matching sample */
    padding: 6mm; /* Internal padding for content - matching sample spacing */
    box-shadow: none;
    box-sizing: border-box;
    overflow: visible !important;
    min-height: auto !important;
    height: auto !important;
    display: block;
    position: relative;
}

/* Ensure all sections are visible */
.invoice-container > * {
    display: block !important;
    visibility: visible !important;
    opacity: 1 !important;
}

.invoice-container .invoice-header,
.invoice-container .company-section,
.invoice-container .address-section,
.invoice-container .items-table,
.invoice-container .totals-section,
.invoice-container .tax-summary-container,
.invoice-container .signatures-section,
.invoice-container .invoice-footer {
    display: block !important;
    visibility: visible !important;
    opacity: 1 !important;
}

@media print {
@page {
    size: A4 !important;
    margin: 10mm 15mm 10mm 15mm !important; /* Top/bottom: 10mm, Left/right: 15mm for proper spacing */
}
    
    html, body { 
        height: auto !important;
        min-height: auto !important;
        overflow: visible !important;
        -webkit-print-color-adjust: exact !important; 
        print-color-adjust: exact !important;
        padding: 0 !important;
    }
    
    .invoice-a4-container {
        width: 100% !important;
        max-width: 180mm !important;
        margin: 0 auto !important;
        padding: 0 !important;
        overflow: visible !important;
        min-height: auto !important;
    }
    
    .invoice-container { 
        width: 100% !important;
        border: 1px solid #000 !important; /* Border on all sides around invoice content - matching sample */
        padding: 6mm !important; /* Internal padding for content - matching sample spacing */
        box-shadow: none !important; 
        margin: 0 !important; 
        max-width: 100% !important;
        box-sizing: border-box !important;
        overflow: visible !important;
        min-height: auto !important;
        height: auto !important;
    }
    
    /* Ensure tables and content fit within container */
    .invoice-container table {
        width: 100% !important;
        max-width: 100% !important;
        table-layout: auto !important;
        display: table !important;
    }
    
    .invoice-container table tbody {
        display: table-row-group !important;
    }
    
    .invoice-container table tbody tr {
        display: table-row !important;
    }
    
    .invoice-container table tbody td {
        display: table-cell !important;
    }
    
    .invoice-container .company-section,
    .invoice-container .address-section {
        width: 100% !important;
        max-width: 100% !important;
        box-sizing: border-box !important;
        display: table !important;
    }
    
    .invoice-container .items-table {
        width: 100% !important;
        max-width: 100% !important;
        box-sizing: border-box !important;
        display: table !important;
        visibility: visible !important;
        opacity: 1 !important;
    }
    
    .invoice-container .items-table tbody {
        display: table-row-group !important;
        visibility: visible !important;
    }
    
    .invoice-container .items-table tbody tr {
        display: table-row !important;
        visibility: visible !important;
    }
    
    .invoice-container .items-table tbody td {
        display: table-cell !important;
        visibility: visible !important;
    }
    
    .invoice-container .totals-section {
        width: 100% !important;
        max-width: 100% !important;
        box-sizing: border-box !important;
        display: table !important;
    }
    
    .invoice-container .tax-summary-container {
        width: 100% !important;
        max-width: 100% !important;
        box-sizing: border-box !important;
        display: block !important;
        visibility: visible !important;
    }
    
    .invoice-container .tax-summary-table {
        width: 100% !important;
        max-width: 100% !important;
        box-sizing: border-box !important;
        display: table !important;
    }
    
    .invoice-container .tax-summary-table tbody {
        display: table-row-group !important;
        visibility: visible !important;
    }
    
    .invoice-container .signatures-section {
        width: 100% !important;
        max-width: 100% !important;
        box-sizing: border-box !important;
        display: table !important;
    }
    
    /* Prevent content overflow */
    .invoice-container * {
        box-sizing: border-box;
    }
    
    .invoice-container .company-info,
    .invoice-container .invoice-meta,
    .invoice-container .address-box {
        max-width: 100% !important;
        word-wrap: break-word !important;
    }
}
</style>
</head>
<body>
<div class="invoice-a4-container">
<?php
$CI =& get_instance();

// Load multi-currency helper
$this->load->helper('multi_currency_helper');

// Get sales and customer details
$q3 = $this->db->query("SELECT b.store_id, a.customer_name, a.mobile, a.phone, a.gstin, a.tax_number, a.email,
                       a.opening_balance, a.country_id, a.state_id, a.city,
                       a.postcode, a.address, b.sales_date, b.created_time, b.reference_no, b.lpo_number,
                       b.sales_code, b.sales_note, b.sales_status, b.created_by,
                       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_input,0) as other_charges_input,
                       other_charges_tax_id,
                       coalesce(b.other_charges_amt,0) as other_charges_amt,
                       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.payment_status
                       FROM db_customers a, db_sales b
                       WHERE a.id = b.customer_id AND b.id = '$sales_id' AND b.store_id = ".get_current_store_id());

if($q3->num_rows() == 0){
    echo "<div style='padding:20px; color:red;'>Error: Sales invoice not found or access denied.</div>";
    exit;
}

$res3 = $q3->row();
$customer_name = $res3->customer_name;
$customer_mobile = $res3->mobile;
$customer_phone = $res3->phone;
$customer_email = $res3->email;
$customer_country = $res3->country_id;
$customer_state = $res3->state_id;
$customer_city = $res3->city;
$customer_address = $res3->address;
$customer_postcode = $res3->postcode;
$customer_gst_no = $res3->gstin;
$customer_tax_number = $res3->tax_number;
$sales_date = $res3->sales_date;
$created_time = $res3->created_time;
$reference_no = $res3->reference_no;
$lpo_number = isset($res3->lpo_number) ? $res3->lpo_number : '';
$sales_code = $res3->sales_code;
$sales_note = $res3->sales_note;
$sales_status = $res3->sales_status;
$created_by = isset($res3->created_by) ? $res3->created_by : '';

$subtotal = $res3->subtotal;
$grand_total = $res3->grand_total;
$other_charges_amt = $res3->other_charges_amt;
$paid_amount = $res3->paid_amount;
$discount_to_all_input = $res3->discount_to_all_input;
$discount_to_all_type = $res3->discount_to_all_type;
$discount_to_all_type_label = ($discount_to_all_type == 'in_percentage') ? '%' : 'Fixed';
$tot_discount_to_all_amt = $res3->tot_discount_to_all_amt;
$round_off = $res3->round_off;
$payment_status = $res3->payment_status;

// Get country/state names
if(!empty($customer_country)){
    $customer_country = $this->db->query("select country from db_country where id='$customer_country'")->row()->country ?? '';
}
if(!empty($customer_state)){
    $customer_state = $this->db->query("select state from db_states where id='$customer_state'")->row()->state ?? '';
}

// Get store details
$q1 = $this->db->query("select * from db_store where 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_country = $res1->country;
$company_state = $res1->state;
$company_city = $res1->city;
$company_address = $res1->address;
$company_postcode = isset($res1->postcode) ? $res1->postcode : '';
$company_gst_no = $res1->gst_no;
$company_vat_no = $res1->vat_no;
$company_pan_no = isset($res1->pan_no) ? $res1->pan_no : '';
$store_website = $res1->store_website;
$sales_invoice_footer_text = $res1->sales_invoice_footer_text;

// Get currency
$store_currency = get_store_currency();
$currency_symbol = !empty($store_currency->symbol) ? $store_currency->symbol : '$';
?>

<div class="invoice-container">
    <!-- Header -->
    <div class="invoice-header">
        <div class="header-left">
            <span class="invoice-title"><?= $this->lang->line('sales_invoice') ?: 'SALES INVOICE' ?></span>
        </div>
        <div class="header-right">
            <?php
            $status_class = 'status-unpaid';
            if($payment_status == 'Paid') $status_class = 'status-paid';
            elseif($payment_status == 'Partial') $status_class = 'status-partial';
            ?>
            <span class="invoice-status <?= $status_class ?>"><?= $payment_status ?></span>
        </div>
    </div>

    <!-- Company Info & Invoice Meta -->
    <div class="company-section">
        <div class="company-info">
            <div class="company-name"><?= $store_name ?></div>
            <div class="info-line"><?= $company_address ?></div>
            <?php if(!empty($company_city) || !empty($company_state)): ?>
            <div class="info-line">
                <?= $company_city ?><?= !empty($company_state) ? ', '.$company_state : '' ?>
                <?= !empty($company_country) ? ', '.$company_country : '' ?>
            </div>
            <?php endif; ?>
            <?php if(!empty(trim($company_mobile)) || !empty(trim($company_phone))): ?>
            <div class="info-line"><strong><?= $this->lang->line('phone') ?>:</strong> <?= !empty(trim($company_mobile)) ? $company_mobile : '' ?><?= (!empty(trim($company_mobile)) && !empty(trim($company_phone))) ? ', ' : '' ?><?= !empty(trim($company_phone)) ? $company_phone : '' ?></div>
            <?php endif; ?>
            <?php if(!empty(trim($company_email))): ?>
            <div class="info-line"><strong><?= $this->lang->line('email') ?>:</strong> <?= $company_email ?></div>
            <?php endif; ?>
            <?php if(!empty(trim($company_gst_no))): ?>
            <div class="info-line"><strong><?= $this->lang->line('gst_number') ?>:</strong> <?= $company_gst_no ?></div>
            <?php elseif(!empty(trim($company_vat_no))): ?>
            <div class="info-line"><strong><?= $this->lang->line('vat_number') ?>:</strong> <?= $company_vat_no ?></div>
            <?php endif; ?>
        </div>
        <div class="invoice-meta">
            <div class="meta-row">
                <span class="meta-label"><?= $this->lang->line('invoice_no') ?>:</span>
                <span class="meta-value" style="font-weight:700; color:#2c3e50;"><?= $sales_code ?></span>
            </div>
            <div class="meta-row">
                <span class="meta-label"><?= $this->lang->line('date') ?>:</span>
                <span class="meta-value"><?= show_date($sales_date) ?> <?= $created_time ?></span>
            </div>
            <?php if(!empty($reference_no)): ?>
            <div class="meta-row">
                <span class="meta-label"><?= $this->lang->line('reference_no') ?>:</span>
                <span class="meta-value"><?= $reference_no ?></span>
            </div>
            <?php endif; ?>
            <?php if(!empty($lpo_number)): ?>
            <div class="meta-row">
                <span class="meta-label"><?= $this->lang->line('lpo_number') ?: 'L.P.O No.' ?>:</span>
                <span class="meta-value" style="color:#3498db; font-weight:600;"><?= $lpo_number ?></span>
            </div>
            <?php endif; ?>
            <?php if(!empty($created_by)): ?>
            <div class="meta-row">
                <span class="meta-label"><?= $this->lang->line('sales_man') ?>:</span>
                <span class="meta-value"><?= ucfirst($created_by) ?></span>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Customer & Shipping Address -->
    <div class="address-section">
        <div class="address-box">
            <div class="address-title"><?= $this->lang->line('customer_address') ?: 'Customer Address' ?></div>
            <div class="info-line"><strong><?= $this->lang->line('name') ?>:</strong> <?= $customer_name ?></div>
            <?php if(!empty(trim($customer_mobile))): ?>
            <div class="info-line"><strong><?= $this->lang->line('mobile') ?>:</strong> <?= $customer_mobile ?></div>
            <?php endif; ?>
            <?php if(!empty($customer_address)): ?>
            <div class="info-line"><?= $customer_address ?></div>
            <?php endif; ?>
            <?php if(!empty($customer_city) || !empty($customer_state) || !empty($customer_postcode)): ?>
            <div class="info-line">
                <?= $customer_city ?><?= !empty($customer_state) ? ', '.$customer_state : '' ?>
                <?= !empty($customer_postcode) ? ' - '.$customer_postcode : '' ?>
            </div>
            <?php endif; ?>
            <?php if(!empty(trim($customer_gst_no)) && function_exists('gst_number') && gst_number()): ?>
            <div class="info-line"><strong><?= $this->lang->line('gst_number') ?>:</strong> <?= $customer_gst_no ?></div>
            <?php endif; ?>
            <?php if(!empty(trim($customer_tax_number))): ?>
            <div class="info-line"><strong><?= $this->lang->line('tax_number') ?>:</strong> <?= $customer_tax_number ?></div>
            <?php endif; ?>
        </div>
        <div class="address-box">
            <div class="address-title"><?= $this->lang->line('shipping_address') ?: 'Shipping Address' ?></div>
            <div class="info-line"><strong><?= $this->lang->line('name') ?>:</strong> <?= $customer_name ?></div>
            <?php if(!empty(trim($customer_mobile))): ?>
            <div class="info-line"><strong><?= $this->lang->line('mobile') ?>:</strong> <?= $customer_mobile ?></div>
            <?php endif; ?>
            <?php if(!empty($customer_address)): ?>
            <div class="info-line"><?= $customer_address ?></div>
            <?php endif; ?>
            <?php if(!empty($customer_city) || !empty($customer_state) || !empty($customer_postcode)): ?>
            <div class="info-line">
                <?= $customer_city ?><?= !empty($customer_state) ? ', '.$customer_state : '' ?>
                <?= !empty($customer_postcode) ? ' - '.$customer_postcode : '' ?>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Items Table -->
    <table class="items-table">
        <thead>
            <tr>
                <th style="width:5%;">#</th>
                <th style="width:35%;"><?= $this->lang->line('item_name') ?></th>
                <th style="width:12%;" class="text-right"><?= $this->lang->line('sales_price') ?></th>
                <th style="width:10%;" class="text-center"><?= $this->lang->line('qty') ?: 'Qty' ?></th>
                <th style="width:8%;" class="text-center"><?= $this->lang->line('unit') ?: 'Unit' ?></th>
                <th style="width:12%;" class="text-right"><?= $this->lang->line('unit_cost') ?></th>
                <th style="width:12%;" class="text-right"><?= $this->lang->line('total_amount') ?></th>
            </tr>
        </thead>
        <tbody>
        <?php
        $i = 0;
        $tot_qty = 0;
        $tot_unit_total_cost = 0;
        $tot_total_cost = 0;

        // Query with multi-unit support
        $q2 = $this->db->query("SELECT c.item_name, a.sales_qty, a.description,
                                a.price_per_unit, b.tax, b.tax_name, a.tax_amt, a.tax_type,
                                a.discount_input, a.discount_amt, a.unit_total_cost,
                                a.total_cost, a.batch_number, a.manufacturing_date, a.expiry_date,
                                c.batch_tracking_enabled,
                                d.unit_name as default_unit,
                                a.unit_type, c.main_unit_id, c.alternate_unit_id,
                                main_unit.unit_name as main_unit_name,
                                alt_unit.unit_name as alternate_unit_name
                                FROM db_salesitems AS a
                                LEFT JOIN db_tax AS b ON b.id = a.tax_id
                                LEFT JOIN db_items AS c ON c.id = a.item_id
                                LEFT JOIN db_units AS d ON d.id = c.unit_id
                                LEFT JOIN db_units AS main_unit ON main_unit.id = c.main_unit_id
                                LEFT JOIN db_units AS alt_unit ON alt_unit.id = c.alternate_unit_id
                                WHERE a.sales_id = '$sales_id'");

        if($q2->num_rows() == 0){
            echo "<tr><td colspan='7' style='text-align:center; padding:20px; color:#999;'>No items found for this invoice.</td></tr>";
        } else {
            foreach ($q2->result() as $res2) {
            // Determine correct unit name based on unit_type (multi-unit support)
            $display_unit = $res2->default_unit;
            if (!empty($res2->unit_type)) {
                if ($res2->unit_type == 'main' && !empty($res2->main_unit_name)) {
                    $display_unit = $res2->main_unit_name;
                } elseif ($res2->unit_type == 'alternate' && !empty($res2->alternate_unit_name)) {
                    $display_unit = $res2->alternate_unit_name;
                }
            }
            ?>
            <tr>
                <td class="text-center"><?= ++$i ?></td>
                <td>
                    <span class="item-name"><?= $res2->item_name ?></span>
                    <?php if($res2->batch_tracking_enabled == 1 && !empty($res2->batch_number)): ?>
                    <div class="batch-info">
                        <strong>Batch:</strong> <?= $res2->batch_number ?>
                        <?php if(!empty($res2->expiry_date) && $res2->expiry_date != '0000-00-00'):
                            $formatted_exp_date = date('d-m-Y', strtotime($res2->expiry_date));
                            $today = new DateTime();
                            $expiry = new DateTime($res2->expiry_date);
                            $diff = $today->diff($expiry);
                            $days_remaining = $diff->invert ? -$diff->days : $diff->days;
                            $days_color = '#27ae60';
                            $days_label = $days_remaining.'d';
                            if($days_remaining < 0) { $days_color = '#e74c3c'; $days_label = 'Expired'; }
                            elseif($days_remaining <= 30) { $days_color = '#f39c12'; }
                        ?>
                        | <strong>Exp:</strong> <?= $formatted_exp_date ?>
                        <span style="color:<?= $days_color ?>;">(<?= $days_label ?>)</span>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                </td>
                <td class="text-right"><?= store_number_format($res2->price_per_unit) ?></td>
                <td class="text-center"><?= format_qty($res2->sales_qty) ?></td>
                <td class="text-center"><?= $display_unit ?></td>
                <td class="text-right"><?= store_number_format($res2->unit_total_cost) ?></td>
                <td class="text-right" style="font-weight:600;"><?= store_number_format($res2->total_cost) ?></td>
            </tr>
            <?php
            $tot_qty += $res2->sales_qty;
            $tot_unit_total_cost += $res2->unit_total_cost;
            $tot_total_cost += $res2->total_cost;
            }
        }

        // Recalculate for accuracy
        if ($tot_total_cost > 0) {
            $subtotal = $tot_total_cost;
            $grand_total = $tot_total_cost + floatval($other_charges_amt) - floatval($tot_discount_to_all_amt) + floatval($round_off);
        }
        ?>
        </tbody>
    </table>

    <!-- Totals -->
    <table class="totals-section">
        <tr class="total-row">
            <td class="label-cell" colspan="4"><?= $this->lang->line('total') ?></td>
            <td class="text-center" style="width:80px;"><?= format_qty($tot_qty) ?></td>
            <td class="text-right" style="width:100px;"><?= store_number_format($tot_unit_total_cost) ?></td>
            <td class="value-cell"><?= $currency_symbol ?> <?= store_number_format($tot_total_cost) ?></td>
        </tr>
        <tr>
            <td class="label-cell" colspan="6"><?= $this->lang->line('subtotal') ?></td>
            <td class="value-cell"><?= $currency_symbol ?> <?= store_number_format($subtotal) ?></td>
        </tr>
        <?php if($other_charges_amt > 0): ?>
        <tr>
            <td class="label-cell" colspan="6"><?= $this->lang->line('other_charges') ?></td>
            <td class="value-cell"><?= $currency_symbol ?> <?= store_number_format($other_charges_amt) ?></td>
        </tr>
        <?php endif; ?>
        <?php if($tot_discount_to_all_amt > 0): ?>
        <tr>
            <td class="label-cell" colspan="6"><?= $this->lang->line('discount_on_all') ?> (<?= $discount_to_all_input ?> <?= $discount_to_all_type_label ?>)</td>
            <td class="value-cell">- <?= $currency_symbol ?> <?= store_number_format($tot_discount_to_all_amt) ?></td>
        </tr>
        <?php endif; ?>
        <tr class="grand-total-row">
            <td colspan="6" style="text-align:right;"><?= $this->lang->line('grand_total') ?></td>
            <td style="text-align:right;"><?= $currency_symbol ?> <?= store_number_format($grand_total) ?></td>
        </tr>
        <tr>
            <td class="label-cell" colspan="6"><?= $this->lang->line('paid_amount') ?></td>
            <td class="value-cell" style="color:#27ae60;"><?= $currency_symbol ?> <?= store_number_format($paid_amount) ?></td>
        </tr>
        <tr>
            <td class="label-cell" colspan="6" style="font-weight:700;"><?= $this->lang->line('due_amount') ?></td>
            <td class="value-cell" style="color:#e74c3c; font-weight:700;"><?= $currency_symbol ?> <?= store_number_format($grand_total - $paid_amount) ?></td>
        </tr>
    </table>

    <!-- Tax Summary -->
    <div class="tax-summary-container">
        <div class="tax-summary-title"><?= $this->lang->line('tax_summary') ?: 'Tax Summary' ?></div>
        <table class="tax-summary-table">
            <thead>
                <tr>
                    <th class="text-center" style="width:25%;"><?= $this->lang->line('tax_rate') ?: 'Tax Rate' ?></th>
                    <th class="text-right" style="width:25%;"><?= $this->lang->line('taxable_amount') ?: 'Taxable' ?> (<?= $currency_symbol ?>)</th>
                    <th class="text-right" style="width:25%;"><?= $this->lang->line('tax_amount') ?: 'Tax' ?> (<?= $currency_symbol ?>)</th>
                    <th class="text-right" style="width:25%;"><?= $this->lang->line('total') ?> (<?= $currency_symbol ?>)</th>
                </tr>
            </thead>
            <tbody>
            <?php
            $tax_summary_q = $this->db->query("
                SELECT b.tax as tax_rate, b.tax_name,
                    SUM(a.total_cost - a.tax_amt) as taxable_amount,
                    SUM(a.tax_amt) as tax_amount,
                    SUM(a.total_cost) as total_amount
                FROM db_salesitems a
                LEFT JOIN db_tax b ON b.id = a.tax_id
                WHERE a.sales_id = '$sales_id'
                GROUP BY b.tax, b.tax_name
                ORDER BY b.tax DESC
            ");

            $sum_taxable = 0;
            $sum_tax = 0;
            $sum_total = 0;

            if($tax_summary_q->num_rows() > 0):
                foreach($tax_summary_q->result() as $tx):
                    $tx_label = $tx->tax_rate . '%';
                    if(strtolower($tx->tax_name) == 'exempt' || $tx->tax_rate == 0) {
                        $tx_label = ($tx->tax_rate == 0 && strtolower($tx->tax_name) != 'exempt') ? '0%' : 'Exempt';
                    }
                    $sum_taxable += $tx->taxable_amount;
                    $sum_tax += $tx->tax_amount;
                    $sum_total += $tx->total_amount;
            ?>
                <tr>
                    <td class="text-center"><?= $tx_label ?></td>
                    <td class="text-right"><?= store_number_format($tx->taxable_amount) ?></td>
                    <td class="text-right"><?= store_number_format($tx->tax_amount) ?></td>
                    <td class="text-right"><?= store_number_format($tx->total_amount) ?></td>
                </tr>
            <?php
                endforeach;
            endif;
            ?>
                <tr class="total-row">
                    <td class="text-center"><strong><?= $this->lang->line('total') ?: 'Total' ?></strong></td>
                    <td class="text-right"><?= store_number_format($sum_taxable) ?></td>
                    <td class="text-right"><?= store_number_format($sum_tax) ?></td>
                    <td class="text-right"><?= store_number_format($sum_total) ?></td>
                </tr>
            </tbody>
        </table>
    </div>

    <!-- Signatures -->
    <div class="signatures-section">
        <div style="display:table-row;">
            <div class="signature-box"><?= $this->lang->line('customer_signature') ?: 'Customer Signature' ?></div>
            <div class="signature-box"><?= $this->lang->line('authorised_signature') ?: 'Authorized Signature' ?></div>
        </div>
    </div>

    <!-- Footer -->
    <?php if(!empty($sales_invoice_footer_text)): ?>
    <div class="invoice-footer">
        <?= $sales_invoice_footer_text ?>
    </div>
    <?php endif; ?>
</div> <!-- End invoice-container -->
</div> <!-- End invoice-a4-container -->

<!-- Print and Back 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: #007bff; 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-arrow-left"></i> Back
  </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") ?>';
  
  // Try to go back in history first
  if (window.history.length > 1) {
    try {
      window.history.back();
      setTimeout(function() {
        window.location.href = backUrl;
      }, 500);
    } catch(e) {
      window.location.href = backUrl;
    }
  } else {
    window.location.href = backUrl;
  }
}
</script>

</body>
</html>
