<!DOCTYPE html>
<html>
<title><?= $page_title;?> - Invoice</title>
<head>
<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;
}

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 !important;
    height: auto !important;
    overflow-x: hidden !important;
    overflow-y: visible !important;
}
.invoice-container {
    max-width: 800px;
    margin: 10px auto;
    background: #fff;
    border: 1px solid #2c3e50;
    box-shadow: 0 0 20px rgba(0,0,0,0.1);
}

/* Header Styles */
.invoice-header {
    background: linear-gradient(135deg, #2c3e50 0%, #1a252f 100%);
    color: #fff;
    padding: 15px 20px;
    text-align: center;
}
.invoice-header h1 {
    font-size: 22px;
    font-weight: 600;
    letter-spacing: 2px;
    margin: 0;
}

/* Company & Customer Info */
.info-section {
    display: table;
    width: 100%;
    border-bottom: 2px solid #2c3e50;
}
.info-box {
    display: table-cell;
    width: 50%;
    padding: 15px 20px;
    vertical-align: top;
}
.info-box.company {
    border-right: 1px solid #e0e0e0;
}
.info-box.logo {
    text-align: right;
    vertical-align: middle;
}
.info-box.logo img {
    max-height: 80px;
    max-width: 150px;
}
.company-name {
    font-size: 18px;
    font-weight: 700;
    color: #2c3e50;
    margin-bottom: 8px;
}
.info-label {
    color: #666;
    font-size: 10px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}
.info-value {
    font-weight: 600;
    color: #333;
}

/* Customer & Invoice Details Row */
.details-row {
    display: table;
    width: 100%;
    border-bottom: 2px solid #2c3e50;
}
.details-box {
    display: table-cell;
    width: 50%;
    padding: 12px 20px;
    vertical-align: top;
}
.details-box:first-child {
    border-right: 1px solid #e0e0e0;
}
.details-title {
    background: #ecf0f1;
    color: #2c3e50;
    font-size: 11px;
    font-weight: 700;
    text-transform: uppercase;
    padding: 6px 10px;
    margin: -12px -20px 10px -20px;
    letter-spacing: 0.5px;
}
.detail-line {
    margin-bottom: 4px;
    font-size: 11px;
}
.detail-line strong {
    color: #2c3e50;
}

/* Items Table */
.items-table {
    width: 100%;
    max-width: 100%;
    border-collapse: collapse;
    box-sizing: border-box;
    table-layout: auto;
    display: table;
}

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

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

.items-table tbody td {
    display: table-cell;
}
.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 td {
    padding: 8px;
    border: 1px solid #ddd;
    vertical-align: top;
    font-size: 11px;
}
.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;
}
.item-desc {
    color: #666;
    font-size: 10px;
    font-style: italic;
}
.batch-info {
    font-size: 9px;
    color: #555;
    margin-top: 3px;
}

/* Totals Section */
.totals-section {
    width: 100%;
    border-collapse: collapse;
}
.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;
    background: #fff;
}
.totals-section .grand-total-row td {
    background: linear-gradient(135deg, #2c3e50 0%, #1a252f 100%);
    color: #fff;
    font-size: 14px;
    font-weight: 700;
    padding: 12px 15px;
}
.totals-section .amount-words td {
    background: #ecf0f1;
    font-style: italic;
    font-size: 11px;
    padding: 10px 15px;
}

/* Tax Summary */
.tax-summary-container {
    padding: 15px 20px;
    background: #f8f9fa;
    border-top: 1px solid #ddd;
}
.tax-summary-title {
    font-size: 12px;
    font-weight: 700;
    color: #2c3e50;
    margin-bottom: 10px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}
.tax-summary-table {
    width: 60%;
    border-collapse: collapse;
    font-size: 11px;
}
.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;
}
.signature-box:first-child {
    margin-right: 50px;
}

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

/* 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;
  min-height: auto;
  height: auto;
}

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

@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;
        height: auto !important;
    }
    
    .invoice-container {
        width: 100% !important;
        border: 1px solid #000 !important; /* Border on all sides around invoice content - matching sample */
        padding: 5mm !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 display correctly */
    .invoice-container table {
        display: table !important;
        width: 100% !important;
        max-width: 100% !important;
    }
    
    .invoice-container table tbody {
        display: table-row-group !important;
        visibility: visible !important;
    }
    
    .invoice-container table tbody tr {
        display: table-row !important;
        visibility: visible !important;
    }
    
    .invoice-container table tbody td {
        display: table-cell !important;
        visibility: visible !important;
    }
    
    .invoice-container .items-table {
        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 .tax-summary-table {
        display: table !important;
        visibility: visible !important;
    }
    
    .invoice-container .tax-summary-table tbody {
        display: table-row-group !important;
        visibility: visible !important;
    }
    
    .invoice-container .tax-summary-table tbody tr {
        display: table-row !important;
        visibility: visible !important;
    }
    
    .invoice-container .tax-summary-table tbody td {
        display: table-cell !important;
        visibility: visible !important;
    }
    
    .no-print {
        display: none !important;
    }
}
</style>
</head>
<body onload="window.print();">
<?php
// Load multi-currency helper
$this->load->helper('multi_currency_helper');

// Get store details
$q1 = $this->db->query("select * from db_store where status=1 and id=".get_current_store_id());
$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 = $res1->postcode;
$company_gst_no = $res1->gst_no;
// Get VAT and PIN numbers - ensure they're retrieved correctly
$company_vat_no = '';
$company_pan_no = '';
if(isset($res1->vat_no) && !empty($res1->vat_no)) {
    $company_vat_no = trim($res1->vat_no);
}
if(isset($res1->pan_no) && !empty($res1->pan_no)) {
    $company_pan_no = trim($res1->pan_no);
}
$store_logo = $res1->store_logo;
$store_website = $res1->store_website;

// Get footer text
$q4 = $this->db->query("select sales_invoice_footer_text from db_store where id=".get_current_store_id());
$res4 = $q4->row();
$sales_invoice_footer_text = $res4->sales_invoice_footer_text;

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

// Get sales and customer details
$q3 = $this->db->query("SELECT b.customer_previous_due, b.customer_total_due, a.customer_name, a.mobile, a.phone, a.gstin, a.tax_number, a.email,
                       a.opening_balance, 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.sales_status,
                       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'");

$res3 = $q3->row();
$customer_name = $res3->customer_name;
$customer_mobile = $res3->mobile;
$customer_phone = $res3->phone;
$customer_email = $res3->email;
$customer_country = get_country($res3->country_id);
$customer_state = get_state($res3->state_id);
$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;
$sales_code = $res3->sales_code;
$sales_note = $res3->sales_note;
$sales_status = $res3->sales_status;
$created_by = $res3->created_by;
$previous_due = $res3->customer_previous_due;
$total_due = $res3->customer_total_due;

$subtotal = $res3->subtotal;
$grand_total = $res3->grand_total;
$other_charges_input = $res3->other_charges_input;
$other_charges_tax_id = $res3->other_charges_tax_id;
$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;
?>

<div class="invoice-a4-container">
<div class="invoice-container">
    <!-- Invoice Header -->
    <div class="invoice-header">
        <h1><?= $this->lang->line('invoice') ?: 'INVOICE' ?></h1>
    </div>

    <!-- Company Info & Logo -->
    <div class="info-section">
        <div class="info-box company">
            <div class="company-name"><?= $store_name ?></div>
            <div class="detail-line"><?= $company_address ?></div>
            <?php if(!empty($company_city) || !empty($company_state)): ?>
            <div class="detail-line">
                <?= $company_city ?><?= !empty($company_state) ? ', '.$company_state : '' ?>
                <?= !empty($company_postcode) ? ' - '.$company_postcode : '' ?>
            </div>
            <?php endif; ?>
            <?php if(!empty(trim($company_mobile)) || !empty(trim($company_phone))): ?>
            <div class="detail-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="detail-line"><strong><?= $this->lang->line('email') ?>:</strong> <?= $company_email ?></div>
            <?php endif; ?>
            <?php if(!empty($company_pan_no) && $company_pan_no != ''): ?>
            <div class="detail-line"><strong>VAT No:</strong> <?= htmlspecialchars($company_pan_no) ?></div>
            <?php endif; ?>
            <?php if(!empty(trim($company_gst_no))): ?>
            <div class="detail-line"><strong>TAX No:</strong> <?= $company_gst_no ?></div>
            <?php endif; ?>
            <?php if(!empty($company_vat_no) && $company_vat_no != '' && trim($company_vat_no) != trim($company_gst_no)): ?>
            <div class="detail-line"><strong>PIN No:</strong> <?= htmlspecialchars($company_vat_no) ?></div>
            <?php endif; ?>
            <?php if(!empty(trim($store_website))): ?>
            <div class="detail-line"><strong>Website:</strong> <?= $store_website ?></div>
            <?php endif; ?>
        </div>
        <div class="info-box logo">
            <?php if(!empty($store_logo)): ?>
            <img src="<?= base_url($store_logo) ?>" alt="Logo">
            <?php endif; ?>
        </div>
    </div>

    <!-- Customer & Invoice Details -->
    <div class="details-row">
        <div class="details-box">
            <div class="details-title"><?= $this->lang->line('customer_details') ?: 'Customer Details' ?></div>
            <div class="detail-line"><strong><?= $this->lang->line('name') ?>:</strong> <?= $customer_name ?></div>
            <div class="detail-line"><strong><?= $this->lang->line('mobile') ?>:</strong> <?= $customer_mobile ?></div>
            <?php if(!empty($customer_address)): ?>
            <div class="detail-line"><?= $customer_address ?></div>
            <?php endif; ?>
            <?php if(!empty($customer_state) || !empty($customer_postcode)): ?>
            <div class="detail-line">
                <?= $customer_state ?><?= !empty($customer_postcode) ? ' - '.$customer_postcode : '' ?>
            </div>
            <?php endif; ?>
            <?php if(!empty(trim($customer_email))): ?>
            <div class="detail-line"><strong><?= $this->lang->line('email') ?>:</strong> <?= $customer_email ?></div>
            <?php endif; ?>
            <?php if(!empty(trim($customer_gst_no))): ?>
            <div class="detail-line"><strong><?= $this->lang->line('gst_number') ?>:</strong> <?= $customer_gst_no ?></div>
            <?php endif; ?>
            <?php if(!empty(trim($customer_tax_number))): ?>
            <div class="detail-line"><strong><?= $this->lang->line('tax_number') ?>:</strong> <?= $customer_tax_number ?></div>
            <?php endif; ?>
        </div>
        <div class="details-box">
            <div class="details-title"><?= $this->lang->line('invoice_details') ?: 'Invoice Details' ?></div>
            <div class="detail-line"><strong><?= $this->lang->line('invoice_no') ?>:</strong> <?= $sales_code ?></div>
            <div class="detail-line"><strong><?= $this->lang->line('date') ?>:</strong> <?= show_date($sales_date) ?> <?= $created_time ?></div>
            <?php if(!empty($reference_no)): ?>
            <div class="detail-line"><strong><?= $this->lang->line('reference_no') ?>:</strong> <?= $reference_no ?></div>
            <?php endif; ?>
            <div class="detail-line"><strong><?= $this->lang->line('sales_man') ?>:</strong> <?= ucfirst($created_by) ?></div>
            <div class="detail-line"><strong><?= $this->lang->line('status') ?>:</strong>
                <span style="color: <?= $payment_status == 'Paid' ? '#27ae60' : ($payment_status == 'Partial' ? '#f39c12' : '#e74c3c') ?>;">
                    <?= $payment_status ?>
                </span>
            </div>
        </div>
    </div>

    <!-- Items Table -->
    <table class="items-table">
        <thead>
            <tr>
                <th style="width:5%;">#</th>
                <th style="width:30%;"><?= $this->lang->line('description') ?></th>
                <th style="width:8%;"><?= $this->lang->line('hsn') ?></th>
                <th style="width:10%;" class="text-right"><?= $this->lang->line('price') ?: 'Price' ?></th>
                <th style="width:8%;" 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:8%;" class="text-center"><?= $this->lang->line('tax') ?>%</th>
                <th style="width:8%;" class="text-right"><?= $this->lang->line('tax_amount') ?: 'Tax' ?></th>
                <th style="width:7%;" class="text-right"><?= $this->lang->line('disc') ?: 'Disc' ?></th>
                <th style="width:10%;" class="text-right"><?= $this->lang->line('total') ?></th>
            </tr>
        </thead>
        <tbody>
        <?php
        $i = 0;
        $tot_qty = 0;
        $tot_sales_price = 0;
        $tot_tax_amt = 0;
        $tot_discount_amt = 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.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, c.hsn, 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, c.conversion_factor,
                                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='10' style='text-align:center; padding:20px; color:#999;'>No items found for this invoice.</td></tr>";
        } else {
            foreach ($q2->result() as $res2) {
            $discount = (empty($res2->discount_input) || $res2->discount_input == 0) ? '0' : $res2->discount_input."%";
            $discount_amt = (empty($res2->discount_amt) || $res2->discount_input == 0) ? '0' : $res2->discount_amt;

            // Calculate price per unit (excluding tax for inclusive)
            $price_per_unit = $res2->price_per_unit;
            if($res2->tax_type == 'Inclusive' && $res2->sales_qty > 0) {
                $price_per_unit -= ($res2->tax_amt / $res2->sales_qty);
            }

            // 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(!empty($res2->description)): ?>
                    <div class="item-desc">[<?= nl2br($res2->description) ?>]</div>
                    <?php endif; ?>
                    <?php if(false && $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-center"><?= $res2->hsn ?></td>
                <td class="text-right"><?= store_number_format($price_per_unit) ?></td>
                <td class="text-center"><?= format_qty($res2->sales_qty) ?></td>
                <td class="text-center"><?= $display_unit ?></td>
                <td class="text-center"><?= $res2->tax_name ?></td>
                <td class="text-right"><?= store_number_format($res2->tax_amt) ?></td>
                <td class="text-right"><?= store_number_format($discount_amt) ?></td>
                <td class="text-right" style="font-weight:600;"><?= store_number_format($res2->total_cost) ?></td>
            </tr>
            <?php
            $tot_qty += $res2->sales_qty;
            $tot_sales_price += $res2->price_per_unit;
            $tot_tax_amt += $res2->tax_amt;
            $tot_discount_amt += $res2->discount_amt;
            $tot_unit_total_cost += $res2->unit_total_cost;
            $tot_total_cost += $res2->total_cost;
            }
        }
        ?>
        </tbody>
    </table>

    <!-- Totals -->
    <table class="totals-section">
        <tr>
            <td class="label-cell" colspan="7"><?= $this->lang->line('subtotal') ?></td>
            <td class="value-cell"><?= $currency_symbol ?> <?= store_number_format($tot_total_cost) ?></td>
        </tr>
        <?php if($other_charges_amt > 0): ?>
        <tr>
            <td class="label-cell" colspan="7"><?= $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="7"><?= $this->lang->line('discount_on_all') ?> (<?= store_number_format($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; ?>
        <?php if($round_off != 0): ?>
        <tr>
            <td class="label-cell" colspan="7"><?= $this->lang->line('round_off') ?></td>
            <td class="value-cell"><?= $currency_symbol ?> <?= store_number_format($round_off) ?></td>
        </tr>
        <?php endif; ?>
        <tr class="amount-words">
            <td colspan="8">
                <strong><?= $this->lang->line('in_words') ?>:</strong>
                <em><?= no_to_words($grand_total) ?> <?= $this->lang->line('only') ?></em>
            </td>
        </tr>
        <tr class="grand-total-row">
            <td colspan="7" 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="7"><?= $this->lang->line('paid_amount') ?></td>
            <td class="value-cell" style="color:#27ae60;"><?= $currency_symbol ?> <?= store_number_format($paid_amount) ?></td>
        </tr>
        <?php if($previous_due > 0): ?>
        <tr>
            <td class="label-cell" colspan="7"><?= $this->lang->line('previous_due') ?></td>
            <td class="value-cell"><?= $currency_symbol ?> <?= store_number_format($previous_due) ?></td>
        </tr>
        <?php endif; ?>
        <?php if($total_due > 0): ?>
        <tr>
            <td class="label-cell" colspan="7" 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($total_due) ?></td>
        </tr>
        <?php endif; ?>
    </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>
  @page {
    size: A4;
    margin: 15mm 8mm 8mm 8mm; /* Top margin: 15mm for proper print spacing, others: 8mm */
}

@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>
