<!DOCTYPE html>
<html>
<head>
	<title>Default Invoice Format</title>
<style type="text/css">

/* =========================
   BASE STYLE
   ========================= */
body {
    font-family: arial;
    font-size: 13px;
    margin: 0;
    padding: 6px;
    color: #000;
    font-weight:400;
    letter-spacing: 0.4px; /* 🔥 improved */
    line-height: 1.4;
}

table {
    width: 100%;
    border-collapse: collapse;
}

/* TEXT */
td, th {
    padding: 3px;
    font-size: 12px;
    vertical-align: top;
    font-weight: 400;
    color: #000;
    line-height: 1.3;
}

/* =========================
   HEADER / FOOTER
   ========================= */
.invoice-header td {
    text-align: center;
    padding: 4px;
    font-weight: 500;
    line-height: 1.3;
}

.invoice-header strong {
    font-size: 14px; /* 🔥 retail feel */
    letter-spacing: 0.5px;
}

.invoice-footer td {
    padding: 4px;
}

/* 🔥 Divider before totals */
.invoice-footer {
    border-top: 1px solid #000;
    margin-top: 4px;
}

/* 🔥 Emphasize final line */
.invoice-footer tr:last-child td {
    font-weight: 700;
    font-size: 13px;
}

/* =========================
   ITEMS TABLE (CLEAN STYLE)
   ========================= */
.invoice-items-table {
    width: 100%;
    table-layout: fixed;
    border-collapse: collapse;
}

/* REMOVE ALL GRID LINES */
.invoice-items-table th,
.invoice-items-table td {
    border: none;
}

/* 🔥 ONLY TOP + BOTTOM LINE */
.invoice-items-table thead tr {
    border-top: 1px solid #000;
    border-bottom: 1px solid #000;
}

.invoice-items-table tbody {
    border-bottom: 1px solid #000;
}

/* HEADER */
.invoice-items-table th {
    font-weight: 600;
    letter-spacing: 0.3px;
}

/* ROW SPACING */
.invoice-items-table tbody tr td {
    padding-top: 4px;
    padding-bottom: 4px;
}

/* Remove row clutter */
.invoice-items-table tbody tr {
    border-bottom: 0;
}

/* =========================
   COLUMN STRUCTURE
   ========================= */
.invoice-items-table th:nth-child(1),
.invoice-items-table td:nth-child(1) {
    width: 5%;
    text-align: center;
}

.invoice-items-table th:nth-child(2),
.invoice-items-table td:nth-child(2) {
    width: 45%;
    text-align: left;

    /* 🔥 PERFECT TEXT WRAPPING */
    white-space: normal;
    word-break: normal;
    overflow-wrap: break-word;
    line-height: 1.4;
    font-weight: 400;
}

.invoice-items-table th:nth-child(3),
.invoice-items-table td:nth-child(3) {
    width: 15%;
    text-align: center;
    white-space: nowrap;
    font-weight: 500;
}

.invoice-items-table th:nth-child(4),
.invoice-items-table td:nth-child(4) {
    width: 15%;
    text-align: right;
    white-space: nowrap;
}

.invoice-items-table th:nth-child(5),
.invoice-items-table td:nth-child(5) {
    width: 20%;
    text-align: right;
    white-space: nowrap;
}

/* 🔥 PERFECT NUMBER ALIGNMENT */
td[style*="right"] {
    font-weight: 500;
    font-variant-numeric: tabular-nums;
    letter-spacing: 0.2px;
    white-space: nowrap;
}

/* =========================
   GENERAL ROW CONTROL
   ========================= */
tr {
    line-height: 1.2;
}

/* =========================
   SMART COMPACT MODES
   ========================= */

/* Medium (15+ items) */
.compact-mode body {
    font-size: 11px;
}

.compact-mode td,
.compact-mode th {
    padding: 2px;
}

.compact-mode .invoice-items-table td:nth-child(2) {
    line-height: 1.2;
}

/* 🔥 Ultra compact (25+ items) */
.ultra-compact body {
    font-size: 10px;
}

.ultra-compact td,
.ultra-compact th {
    padding: 1px;
}

.ultra-compact .invoice-items-table td:nth-child(2) {
    font-size: 10px;
    line-height: 1.1;
}

/* =========================
   PRINT OPTIMIZATION
   ========================= */
@media print {

    @page {
        size: auto;
        margin: 2mm;
    }

    html, body {
        margin: 0;
        padding: 4px;
    }

    body {
        font-size: 11px;
        line-height: 1.3;
    }

    table {
        font-size: 10px;
    }

    td, th {
        padding: 2px;
        font-size: 10px;
    }

    table, tr, td {
        page-break-inside: avoid !important;
        break-inside: avoid !important;
    }

    .invoice-header,
    .invoice-footer {
        page-break-inside: avoid !important;
    }

    .invoice-items-table tr {
        page-break-inside: avoid !important;
    }

    .no-print {
        display: none !important;
    }
}

/* =========================
   80mm THERMAL
   ========================= */
@media print and (max-width: 85mm) {
    body { font-size: 11px; }
    table { font-size: 10px; }
}

/* =========================
   58mm THERMAL
   ========================= */
@media print and (max-width: 63mm) {
    body { font-size: 10px; }
    table { font-size: 9px; }

    td, th {
        padding: 2px;
        font-size: 9px;
    }
}

/* =========================
   A4 SUPPORT
   ========================= */
@media print and (min-width: 210mm) {
    @page {
        size: A4;
        margin: 1cm;
    }

    body { font-size: 12px; }
    table { font-size: 11px; }
    /* =========================
   NUMBER OVERFLOW CONTROL
   ========================= */

/* All numeric columns */
.invoice-items-table td:nth-child(3),
.invoice-items-table td:nth-child(4),
.invoice-items-table td:nth-child(5),
.invoice-items-table td:nth-child(6),
td[style*="right"] {

    white-space: nowrap !important;     /* never wrap */
    overflow: hidden;                  /* prevent spill */
    text-overflow: ellipsis;           /* cut cleanly if too long */
    max-width: 0;                      /* 🔥 forces proper truncation */
    font-variant-numeric: tabular-nums;
}

/* Keep table stable */
.invoice-items-table {
    table-layout: fixed;
}

/* =========================
   SMART FONT SHRINK (BETTER THAN CUTTING)
   ========================= */

/* Slight shrink when content is tight */
.compact-mode td[style*="right"] {
    font-size: 10px;
}

.ultra-compact td[style*="right"] {
    font-size: 9px;
}

    td, th {
        padding: 5px;
    }
}
</style>
</head>
<body onload="checkAndPrint();"><!--  -->
	<script>
function checkAndPrint() {
    setTimeout(function () {
        window.print();
    }, 500);
}

window.onafterprint = function () {
    window.close();
};

// fallback (if onafterprint fails)
setTimeout(() => {
    window.close();
}, 5000);
/* ðŸ”¥ Compress items perfectly */
window.addEventListener("load", function () {
    var rows = document.querySelectorAll('.invoice-items-table tbody tr').length;

    if (rows > 20) {
        document.body.classList.add('compact-mode');
    }
});
</script>
	<?php
	$CI =& get_instance();
	
    
  	$q3=$this->db->query("SELECT b.coupon_id,b.coupon_amt, b.created_by, b.customer_previous_due,b.customer_total_due,b.store_id,a.customer_name,a.mobile,a.phone,a.gstin,a.tax_number,a.email,a.delete_bit,b.invoice_terms,
                           a.opening_balance,a.country_id,a.state_id,
                           a.postcode,a.address,b.sales_date,b.created_time,b.reference_no,
                           b.sales_code,b.sales_note,a.sales_due,
                           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=$res3->country_id;
    $customer_state=$res3->state_id;
    $customer_address=$res3->address;
    $customer_postcode=$res3->postcode;
    $customer_gst_no=$res3->gstin;
    $customer_tax_number=$res3->tax_number;
    $customer_opening_balance=$res3->opening_balance;
    $sales_date=show_date($res3->sales_date);
    $reference_no=$res3->reference_no;
    $created_time=show_time($res3->created_time);
    $sales_code=$res3->sales_code;
    $sales_note=$res3->sales_note;
    $customer_delete_bit=$res3->delete_bit;
   // $invoice_terms=nl2br($res3->invoice_terms);

    $previous_due=$res3->sales_due-($res3->grand_total-$res3->paid_amount);//$res3->customer_previous_due;
    $previous_due = ($previous_due>0) ? $previous_due : 0;
    $total_due=$res3->sales_due;//$res3->customer_total_due;

    $coupon_id=$res3->coupon_id;
    $coupon_amt=$res3->coupon_amt;

    $coupon_code = '';
    $coupon_type = '';
    $coupon_value=0;
    if(!empty($coupon_id)){
    	$coupon_details =get_customer_coupon_details($coupon_id);
    	$coupon_code =$coupon_details->code;
    	$coupon_value =$coupon_details->value;
    	$coupon_type =$coupon_details->type;
    } 

    
    $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;
    
    // Recalculate paid_amount from payment records if it's invalid (1 or 0)
    // Sum only valid payments (exclude payments that are 1 or 0, as they're likely bad data)
    if ($paid_amount <= 0 || abs($paid_amount - 1) < 0.01) {
        $payment_query = $this->db->query("SELECT payment FROM db_salespayments WHERE sales_id = $sales_id");
        $calculated_paid = 0;
        if ($payment_query->num_rows() > 0) {
            foreach ($payment_query->result() as $pay_row) {
                $pay_amt = floatval($pay_row->payment);
                // Only include valid payments (not 1 or 0)
                if ($pay_amt > 0 && abs($pay_amt - 1) >= 0.01) {
                    $calculated_paid += $pay_amt;
                }
            }
            if ($calculated_paid > 0) {
                $paid_amount = $calculated_paid;
            }
        }
    }
    $discount_to_all_input=$res3->discount_to_all_input;
    $discount_to_all_type=$res3->discount_to_all_type;
    //$discount_to_all_type = ($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;
    
    if($discount_to_all_input>0){
    	$str="($discount_to_all_input%)";
    }else{
    	$str="(Fixed)";
    }


    if(!empty($customer_state)){
      $q6 = $this->db->query("select state from db_states where id='$customer_state'");
      if($q6->num_rows()>0){
      	$customer_state = $q6->row()->state;
      }
    }

    $overall_discounted = $tot_discount_to_all_amt + $coupon_amt;

    $q1=$this->db->query("select * from db_store where id=".$res3->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;//Goods and Service Tax Number (issued by govt.)
    $company_vat_number		=$res1->vat_no;//Goods and Service Tax Number (issued by govt.)
    $store_logo=(!empty($res1->store_logo)) ? $res1->store_logo : '';
    $store_website		=$res1->store_website;
    $mrp_column		=$res1->mrp_column;
    $previous_balance_bit	=$res1->previous_balance_bit;
    $pos_invoice_format_id	=$res1->pos_invoice_format_id;
    $t_and_c_status_pos	=$res1->t_and_c_status_pos;
    
    // Get show_logo_on_pos_invoice setting - explicitly check and cast to integer
    // Default to 0 (hide logo) if column doesn't exist or value is NULL/empty
    $show_logo_on_pos_invoice = 0; // Default to hide logo
    if(property_exists($res1, 'show_logo_on_pos_invoice')) {
        $db_value = $res1->show_logo_on_pos_invoice;
        // Only show logo if value is explicitly 1 (not just truthy)
        if($db_value !== null && $db_value !== '' && (int)$db_value === 1) {
            $show_logo_on_pos_invoice = 1;
        }
    }


    ?>
	<div class="table-container">
	<table width="100%">
		<tbody class="invoice-header">
        <?php if($show_logo_on_pos_invoice === 1 && !empty($store_logo)) { ?>
		<tr>
			<td align="center">
				<img src="<?= base_url($store_logo);?>" width="30%" height="auto">
			</td>
		</tr>
		<?php } ?>
		<tr>
			<td align="center">
				<span>													 
                <strong><?= $store_name; ?></strong><br>
                	<?php echo (!empty(trim($company_address))) ? $this->lang->line('company_address')."".$company_address."<br>" : '';?> 
		            <?= $company_city; ?>
		            <?php echo (!empty(trim($company_postcode))) ? "-".$company_postcode : '';?>
		            <br>
		            <?php if(!empty(trim($company_mobile)) || !empty(trim($company_phone))) {
		            			echo $this->lang->line('phone').": ";
		            			if(!empty(trim($company_mobile))) echo $company_mobile;
		            			if(!empty(trim($company_mobile)) && !empty(trim($company_phone))) echo ", ";
		            			if(!empty(trim($company_phone))) echo $company_phone;
		            			echo "<br>";
		            		}
		            ?>
		            <?php echo (!empty(trim($company_gst_no)) && gst_number()) ? $this->lang->line('gst_number').": ".$company_gst_no."<br>" : '';?>
		            <?php echo (!empty(trim($company_vat_number)) && vat_number()) ? $this->lang->line('vat_number').": ".$company_vat_number."<br>" : '';?>
		            <?php echo (!empty($company_email)) ? $company_email."," : '';
		            		echo (!empty($store_website)) ? $store_website."<br>" : '';

		            ?> 
			</span>
			</td>
		</tr>
		<tr><td align="center"><strong>----<?= $this->lang->line('cash_sale_invoice'); ?>----</strong></td></tr>
		<tr>
			<td>
				<table width="100%">
					<tr>
						<td width="40%"><?= $this->lang->line('cash_sale_invoice'); ?></td>
						<td><b>#<?= $sales_code; ?></b></td>
					</tr>
					<tr>
						<td><?= $this->lang->line('name'); ?></td>
						<td><?= $customer_name; ?></td>
					</tr>
					<tr>
						<td><?= $this->lang->line('seller'); ?></td>
						<td><?= ucfirst($res3->created_by) ?></td>
					</tr>
					<tr>
						<td><?= $this->lang->line('date').":".$sales_date; ?></td>
						<td style="text-align: right;"><?= $this->lang->line('time').":".$created_time; ?></td>
					</tr>
				</table>
				
			</td>
		</tr>
		</tbody>
		<tbody class="invoice-items">
		<tr>
			<td>

				<table width="100%" cellpadding="0" cellspacing="0" class="invoice-items-table">
					<thead>
					<tr>
						<th style="font-size: 11px; text-align: left;padding-left: 2px; padding-right: 2px;">#</th>
						<th style="font-size: 11px; text-align: left;padding-left: 2px; padding-right: 2px;"><?= $this->lang->line('description'); ?></th>
						
						<th style="font-size: 11px; text-align: center;padding-left: 2px; padding-right: 2px;"><?= 'Qty'; ?></th>
						<?php if($mrp_column){ ?>
						<th style="font-size: 11px; text-align: right;padding-left: 2px; padding-right: 2px;"><?= $this->lang->line('mrp'); ?></th>
						<?php  } ?>
						<th style="font-size: 11px; text-align: right;padding-left: 2px; padding-right: 2px;"><?= $this->lang->line('rate'); ?></th>
						<th style="font-size: 11px; text-align: right;padding-left: 2px; padding-right: 2px;"><?= $this->lang->line('total'); ?></th>
					</tr>
					</thead>
					<tbody style="border-bottom-style: dashed;border-width: 0.1px;">
						<?php
			              $i=0;
			              $tot_qty=0;
			              $subtotal=0;
			              $tax_amt=0;
			              $this->db->select(" a.description,c.mrp,c.item_name, a.sales_qty,a.unit_type,a.sales_qty_main,a.sales_qty_alternate,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.main_unit_id,c.alternate_unit_id,um.unit_name as main_unit_name,ua.unit_name as alternate_unit_name,
                                  c.sku,c.hsn, a.batch_number, a.manufacturing_date, a.expiry_date, c.batch_tracking_enabled
                              ");
			              $this->db->where("a.sales_id",$sales_id);
			              $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 um","um.id = c.main_unit_id","left");
			              $this->db->join("db_units ua","ua.id = c.alternate_unit_id","left");
			              $q2=$this->db->get();
			              foreach ($q2->result() as $res2) {
			                  echo "<tr>";  
			                  echo "<td style='padding-left: 2px; padding-right: 2px;' valign='top'>".++$i."</td>";
			                  echo "<td style='padding-left: 2px; padding-right: 2px;'>".$res2->item_name;
                              // Compact batch details: show Batch, Expiry, and Days to Expiry
                              if(false && isset($res2->batch_tracking_enabled) && $res2->batch_tracking_enabled == 1 && !empty($res2->batch_number)) {
                                  $exp_text = '';
                                  $days_text = '';
                                  if(isset($res2->expiry_date) && !empty($res2->expiry_date) && $res2->expiry_date != '0000-00-00') {
                                      $exp_text = date('d-m-Y', strtotime($res2->expiry_date));
                                      // Calculate days to expiry
                                      $today = new DateTime();
                                      $expiry = new DateTime($res2->expiry_date);
                                      $diff = $today->diff($expiry);
                                      $days_remaining = $diff->invert ? -$diff->days : $diff->days;
                                      if($days_remaining < 0) {
                                          $days_text = '<span style="color:#d9534f;">Expired</span>';
                                      } elseif($days_remaining <= 30) {
                                          $days_text = '<span style="color:#f0ad4e;">'.$days_remaining.'d</span>';
                                      } else {
                                          $days_text = '<span style="color:#5cb85c;">'.$days_remaining.'d</span>';
                                      }
                                  }
                                  $parts = array();
                                  $parts[] = '<strong>Batch:</strong> '.htmlspecialchars($res2->batch_number, ENT_QUOTES, 'UTF-8');
                                  if(!empty($exp_text)) { $parts[] = '<strong>Exp:</strong> '.$exp_text; }
                                  if(!empty($days_text)) { $parts[] = $days_text; }
                                  echo '<br><small>'.implode(' | ', $parts).'</small>';
                              }
			                  echo "</td>";
			                  
			                  // Show quantity with unit name (supports multi-unit)
			                  // Use unit_type as the primary indicator of which unit was used
			                  $qty_display = '';
			                  $unit_label = '';
			                  $main_unit_name = !empty($res2->main_unit_name) ? $res2->main_unit_name : '';
			                  $alt_unit_name  = !empty($res2->alternate_unit_name) ? $res2->alternate_unit_name : '';
			             $qty_display = format_qty($res2->sales_qty);

echo "<td style='text-align: center;padding-left: 2px; padding-right: 2px;'>".$qty_display."</td>";
			                  if($mrp_column){
			                  	echo "<td style='text-align: right;padding-left: 2px; padding-right: 2px;'>".store_number_format($res2->mrp)."</td>";
			                  }
			                  // Always recalculate line total from price/qty/tax/discount for print so stored total_cost never shows wrong one-digit values
			                  $calc_price = floatval($res2->price_per_unit);
			                  $calc_qty = floatval($res2->sales_qty);
			                  $calc_discount = floatval($res2->discount_amt);
			                  $calc_tax = floatval($res2->tax_amt);
			                  $display_total_cost = floatval($res2->total_cost);
			                  $display_unit_total_cost = floatval($res2->unit_total_cost);

			                  if ($calc_price > 0 && $calc_qty > 0) {
			                      $base_amt = ($calc_price * $calc_qty) - $calc_discount;
			                      if (isset($res2->tax_type) && $res2->tax_type == 'Inclusive') {
			                          $display_total_cost = $base_amt;
			                      } else {
			                          $display_total_cost = $base_amt + $calc_tax;
			                      }
			                      $display_unit_total_cost = $display_total_cost / $calc_qty;
			                  }

			                  echo "<td style='text-align: right;padding-left: 2px; padding-right: 2px;'>".store_number_format($display_unit_total_cost)."</td>";
			                  echo "<td style='text-align: right;padding-left: 2px; padding-right: 2px;' >".store_number_format($display_total_cost)."</td>";
			                  echo "</tr>";  
			                  //$tot_qty+=$res2->sales_qty;
			                  $subtotal+=($display_total_cost);
			                  $tax_amt+=$res2->tax_amt;
			                  $overall_discounted+=$res2->discount_amt;
			              }
			              $before_tax = $subtotal-$tax_amt;

			              // Always recalculate grand_total from items for accuracy
			              // This ensures correct totals even if database has corrupt data
			              $calc_subtotal = floatval($subtotal);
			              $calc_tax_amt = floatval($tax_amt);
			              $calc_other_charges = floatval($other_charges_amt);
			              $calc_discount_all = floatval($tot_discount_to_all_amt);
			              $calc_coupon = floatval($coupon_amt);
			              $calc_round_off = floatval($round_off);

			              // Note: $calc_subtotal is already the sum of total_cost values (which include tax)
			              // So we should NOT add tax_amt again - that would double-count
			              $calculated_grand_total = $calc_subtotal + $calc_other_charges - $calc_discount_all - $calc_coupon + $calc_round_off;

			              // Always use calculated value if items were found, otherwise keep database value
			              if ($calc_subtotal > 0) {
			                  $grand_total = $calculated_grand_total;
			              }



			              ?>
					
				   </tbody>
					<tfoot class="invoice-footer">
					 <!-- <tr><td colspan="5"><hr></td></tr>    -->
							
					 <?php if(false){ ?>
					 <tr >
						<td style=" padding-left: 2px; padding-right: 2px;" colspan="<?=$mrp_column+4?>" align="right"><?= $this->lang->line('before_tax'); ?></td>
						<td style=" padding-left: 2px; padding-right: 2px;" align="right"><?= store_number_format($before_tax);?></td>
					</tr>
					<?php } ?>

					<!-- Show GST Details -->
					<?php
						if(false &&  get_store_details()->pos_invoice_format_id == 1){
							?>
							<tr >
								<td style=" padding-left: 2px; padding-right: 2px;" colspan="<?=$mrp_column+4?>" align="right"><?= $this->lang->line('tax_amount'); ?></td>
								<td style=" padding-left: 2px; padding-right: 2px;" align="right"><?= store_number_format($tax_amt);?></td>
							</tr>
							
							<?php
						}
						else if(false){
						$this->db->select(" 
                                b.tax,
                                b.tax_name,
                                COALESCE(SUM(a.tax_amt),0) AS sum_of_tax_amt,
                                c.tax_type
                             ");
            $this->db->where("a.sales_id",$sales_id);
            $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->group_by("a.tax_id");
            $q5=$this->db->get();

            if($q5->num_rows()>0){
            	foreach($q5->result() as $row){
            			$tax_per = $row->tax;
            			$sum_of_tax_amt = $row->sum_of_tax_amt;

            		if( $customer_delete_bit==1 || (strtoupper($customer_state) == strtoupper($company_state))){
            				
                    $sgst_per = $cgst_per = ($tax_per/2)."%";
                    $sgst_amt = $cgst_amt = $sum_of_tax_amt / 2;
                    $igst_per = $igst_amt = '';
                    ?>
                    	<tr>
												<td style=" padding-left: 2px; padding-right: 2px;" colspan="<?=$mrp_column+4?>" align="right">
													<?= $this->lang->line('cgst'); ?> 
													<?= $sgst_per ?>
													</td>
												<td style=" padding-left: 2px; padding-right: 2px;" align="right"><?= store_number_format($cgst_amt); ?></td>
											</tr>
											<tr>
												<td style=" padding-left: 2px; padding-right: 2px;" colspan="<?=$mrp_column+4?>" align="right">
													<?= $this->lang->line('sgst'); ?> 
													<?= $cgst_per ?>
													</td>
												<td style=" padding-left: 2px; padding-right: 2px;" align="right"><?= store_number_format($sgst_amt); ?></td>
											</tr>

                    <?php
                  }else{
                    $sgst_per = $cgst_per = '';
                    $sgst_amt = $cgst_amt = '';
                    $igst_per = $tax_per."%";
                    $igst_amt = $sum_of_tax_amt;

                    ?>
                    	<tr>
												<td style=" padding-left: 2px; padding-right: 2px;" colspan="<?=$mrp_column+4?>" align="right">
													<?= $this->lang->line('igst'); ?> 
													<?= $igst_per ?>
													</td>
												<td style=" padding-left: 2px; padding-right: 2px;" align="right"><?= store_number_format($igst_amt); ?></td>
											</tr>
                    <?php

                  }


            		?>
            			
            		<?php
            	}
            }
            else{

            }

          }//pos_invoice_format_id else
					?>
					<!-- End -->
					<!-- <tr >
						<td style=" padding-left: 2px; padding-right: 2px;" colspan="<?=$mrp_column+4?>" align="right"><?= $this->lang->line('subtotal'); ?></td>
						<td style=" padding-left: 2px; padding-right: 2px;" align="right"><?= store_number_format($subtotal);?></td>
					</tr> -->
					<!-- <tr>
	                     <td style=' padding-left: 2px; padding-right: 2px;' colspan='<?=$mrp_column+4?>' align='right'>Tax Amt</td>
	                      <td style=' padding-left: 2px; padding-right: 2px;' align='right'><?= store_number_format($tax_amt);?></td>
	                </tr> -->
	        <?php if(!empty($coupon_code)) {?>
					<tr>
						<td style=" padding-left: 2px; padding-right: 2px;" colspan="<?=$mrp_column+4?>" align="right"><?= $this->lang->line('couponDiscount'); ?> <?= ($coupon_type=='Percentage') ? $coupon_value .'%' : '[Fixed]' ;?></td>
						<td style=" padding-left: 2px; padding-right: 2px;" align="right"><?= store_number_format($coupon_amt); ?></td>
					</tr>
					<?php } ?>

	        <?php if(!empty($tot_discount_to_all_amt) && $tot_discount_to_all_amt!=0) {?>
					<tr>
						<td style=" padding-left: 2px; padding-right: 2px;" colspan="<?=$mrp_column+4?>" align="right"><?= $this->lang->line('discount'); ?> <?= ($discount_to_all_type=='in_percentage') ? $discount_to_all_input .'%' : '[Fixed]' ;?></td>
						<td style=" padding-left: 2px; padding-right: 2px;" align="right"><?= store_number_format($tot_discount_to_all_amt); ?></td>
					</tr>
					<?php } ?>
					

					<!-- <tr><td style="border-bottom-style: dashed;border-width: 0.1px;" colspan="5"></td></tr>   -->

					

					<tr>
						<td style=" padding-left: 2px; padding-right: 2px;" colspan="<?=$mrp_column+4?>" align="right"><?= $this->lang->line('total'); ?></td>
						<td style=" padding-left: 2px; padding-right: 2px;" align="right"><?= store_number_format($grand_total); ?></td>
					</tr>
					<tr>
						<td style=" padding-left: 2px; padding-right: 2px;" colspan="<?=$mrp_column+4?>" align="right"><?= $this->lang->line('tot_discounted_amt'); ?></td>
						<td style=" padding-left: 2px; padding-right: 2px;" align="right"><?= store_number_format($overall_discounted); ?></td>
					</tr>
					
					<!-- change_return_status -->
					<?php if(change_return_status()) {
						$change_return_amount = get_change_return_amount($sales_id); ?>
						<tr>
							<td style=" padding-left: 2px; padding-right: 2px;" colspan="<?=$mrp_column+4?>" align="right"><?= $this->lang->line('paid_amount'); ?></td>
							<td style=" padding-left: 2px; padding-right: 2px;" align="right"><?= store_number_format($paid_amount+$change_return_amount); ?></td>
						</tr>
						<tr>
							<td style=" padding-left: 2px; padding-right: 2px;" colspan="<?=$mrp_column+4?>" align="right"><?= $this->lang->line('refund'); ?></td>
							<td style=" padding-left: 2px; padding-right: 2px;" align="right"><?= store_number_format($change_return_amount); ?></td>
						</tr>
					<?php }
					else{ ?>
						<tr>
						<td style=" padding-left: 2px; padding-right: 2px;" colspan="<?=$mrp_column+4?>" align="right"><?= $this->lang->line('paid_amount'); ?></td>
						<td style=" padding-left: 2px; padding-right: 2px;" align="right"><?= store_number_format($paid_amount); ?></td>
					</tr>
					
					<?php } ?>

					<?php if($previous_balance_bit==1) {?>
					<tr>
						<td style=" padding-left: 2px; padding-right: 2px;" colspan="<?=$mrp_column+4?>" align="right"><?= $this->lang->line('previous_due'); ?></td>
						<td style=" padding-left: 2px; padding-right: 2px;" align="right"><?= store_number_format($previous_due); ?></td>
					</tr>
					<tr>
						<td style=" padding-left: 2px; padding-right: 2px;" colspan="<?=$mrp_column+4?>" align="right"><?= $this->lang->line('total_due_amount'); ?></td>
						<td style=" padding-left: 2px; padding-right: 2px;" align="right"><?= store_number_format($total_due); ?></td>
					</tr>
					<?php } ?>
					<?php if(!empty($coupon_code)) {?>
					<tr>
						<td colspan="<?=$mrp_column+5?>" align="left">
							<b><?= $this->lang->line('couponCode'); ?>:</b> <i><?=getTruncatedCCNumber($coupon_code);?></i>
						</td>
					</tr>
					<?php }?>

					<tr>
						<td colspan="<?=$mrp_column+5?>" align="left">
							<b><u>Note:</u></b> <i><?=$sales_note;?></i>
						</td>
					</tr>

					<!-- TAX SUMMARY -->
					 
					 <?php if(false){ ?>
					<tr>
						<td colspan="<?=$mrp_column+5?>" align="left">
							<table style="border:1px solid;border-collapse:collapse;margin-top:5px;margin-bottom:5px;" width="100%" cellpadding="2" cellspacing="0">
								<tr style="background-color: #f0f0f0;">
									<th colspan="4" style="border:1px solid;text-align:center;font-weight:bold;padding:3px;">TAX SUMMARY</th>
								</tr>
								<tr style="background-color: #f0f0f0;">
									<th style="border:1px solid;text-align:center;padding:2px;font-size:11px;">Tax Rate</th>
									<th style="border:1px solid;text-align:right;padding:2px;font-size:11px;">Taxable Amt</th>
									<th style="border:1px solid;text-align:right;padding:2px;font-size:11px;">Tax Amt</th>
									<th style="border:1px solid;text-align:right;padding:2px;font-size:11px;">Total Amt</th>
								</tr>
								<?php 
								// Build tax summary with proper calculation for inclusive/exclusive tax
								$tax_summary_q = $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'
								");
								
								$tax_summary_data = array();
								foreach($tax_summary_q->result() as $tax_item) {
									$tax_rate = floatval($tax_item->tax_rate);
									$tax_key = $tax_rate . '%';
									if ($tax_rate == 0) {
										$tax_key = (stripos($tax_item->tax_name, 'exempt') !== false) ? 'exempt' : '0%';
									}
									
									if (!isset($tax_summary_data[$tax_key])) {
										$tax_summary_data[$tax_key] = array(
											'rate' => $tax_rate,
											'name' => $tax_item->tax_name,
											'taxable' => 0,
											'tax' => 0,
											'total' => 0
										);
									}
									
									// Ensure we have valid numeric values
									$item_total_cost = floatval($tax_item->total_cost);
									$item_tax_amt = floatval($tax_item->tax_amt);
									
									// If values are invalid, recalculate
									if ($item_total_cost <= 0 || $item_total_cost == 1) {
										$item_price = floatval($tax_item->price_per_unit);
										$item_qty = floatval($tax_item->sales_qty);
										$item_discount = floatval($tax_item->discount_amt);
										
										if ($item_price > 0 && $item_qty > 0) {
											$base_amount = ($item_price * $item_qty) - $item_discount;
											if ($tax_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 ($tax_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;
								}
								
								$pos_taxable_total = 0;
								$pos_tax_total = 0;
								$pos_summary_total = 0;
								// Sort by tax rate descending
								krsort($tax_summary_data);
								foreach($tax_summary_data as $key => $tax_r) {
									$tax_lbl = $tax_r['rate'] . '%';
									if ($key == 'exempt') {
										$tax_lbl = 'Ex.';
									} elseif ($tax_r['rate'] == 0) {
										$tax_lbl = '0%';
									}
									
									$pos_taxable_total += $tax_r['taxable'];
									$pos_tax_total += $tax_r['tax'];
									$pos_summary_total += $tax_r['total'];
									
									echo '<tr>';
									echo '<td style="border:1px solid;text-align:center;padding:2px;font-size:11px;">' . $tax_lbl . '</td>';
									echo '<td style="border:1px solid;text-align:right;padding:2px;font-size:11px;">' . $CI->currency() . ' ' . store_number_format($tax_r['taxable']) . '</td>';
									echo '<td style="border:1px solid;text-align:right;padding:2px;font-size:11px;">' . $CI->currency() . ' ' . store_number_format($tax_r['tax']) . '</td>';
									echo '<td style="border:1px solid;text-align:right;padding:2px;font-size:11px;">' . $CI->currency() . ' ' . store_number_format($tax_r['total']) . '</td>';
									echo '</tr>';
								}
								?>
								<tr style="background-color: #f0f0f0; font-weight: bold;">
									<td style="border:1px solid;text-align:center;padding:2px;font-size:11px;">Totals</td>
									<td style="border:1px solid;text-align:right;padding:2px;font-size:11px;"><?= $CI->currency() . ' ' . store_number_format($pos_taxable_total); ?></td>
									<td style="border:1px solid;text-align:right;padding:2px;font-size:11px;"><?= $CI->currency() . ' ' . store_number_format($pos_tax_total); ?></td>
									<td style="border:1px solid;text-align:right;padding:2px;font-size:11px;"><?= $CI->currency() . ' ' . store_number_format($pos_summary_total); ?></td>
								</tr>
							</table>
						</td>
					</tr>
					<!-- END TAX SUMMARY -->
                       <?php } ?> 
					<tr>
						<td colspan="<?=$mrp_column+5?>" align="left">
							<table style="border:1px solid;border-collapse:collapse;" width="100%" cellpadding="0" cellspacing="0">
								<tr>
									<th style="border:1px solid;text-align:center;font-weight:bold;">#</th>
									<th style="border:1px solid;text-align:center;"><?= $this->lang->line('payment_type'); ?></th>
									<th style="border:1px solid;text-align:center;"><?= $this->lang->line('amount'); ?></th>
								</tr>
								<?php 
                            if(isset($sales_id)){
                              $q4 = $this->db->query("select * from db_salespayments where sales_id=$sales_id");
                              if($q4->num_rows()>0){
                                $i=1;
                                $total_paid = 0;
                                foreach ($q4->result() as $res4) {
                                  // Ensure payment amount is valid
                                  $payment_amt = floatval($res4->payment);
                                  // Display payment even if it's "1" (will be handled by recalculated total)
                                  echo "<tr>";
                                  echo '<td style="border:1px solid;padding-left:2px;">'.$i++."</td>";
                                  echo '<td style="border:1px solid;padding-left:2px;">';
                                    echo $res4->payment_type;
                                  echo '</td>';
                                  echo '<td style="border:1px solid;text-align: right;padding-right:2px;">'.store_number_format($payment_amt).'</td>';
                                  echo "</tr>";
                                  // Only add to total if payment is valid (not 1 or 0)
                                  if ($payment_amt > 0 && abs($payment_amt - 1) >= 0.01) {
                                    $total_paid += $payment_amt;
                                  }
                                }
                                echo '<tr>';
                                    echo '<td colspan="2" style="border:1px solid;text-align:right;padding-right:2px;">';
                                            echo $this->lang->line('total');
                                    echo '</td>';
                                    echo '<td class="text-right" style="padding-right:2px;">';
                                			echo store_number_format($total_paid);
                                	echo '</td>';
                                echo '</tr>';

                                
                              }
                              else{
                                echo "<tr><td colspan='3' class='text-center text-bold'>Unpaid!!</td></tr>";
                              }

                            }
                            else{
                              echo "<tr><td colspan='3' class='text-center text-bold'>Payments Pending!!</td></tr>";
                            }
                          ?>
							
							</table>
						</td>
					</tr>
					
					<?php
						if($t_and_c_status_pos){ ?>
							<tr>
								<td colspan="<?=$mrp_column+5?>" align="left">
									&nbsp;
								</td>
							</tr>
							<tr style='border:1px solid;'>
						<td colspan="<?=$mrp_column+5?>" align="left">
							<b><u><?= $this->lang->line('invoiceTerms'); ?>:</u></b> <i><?=nl2br(get_invoice_terms_for_pos());?></i>
						</td>
					</tr>
						<?php }
					 ?>
					<tr>
						<td colspan="<?=$mrp_column+5?>" align="center">----------<?= $this->lang->line('thank_you_visit_again'); ?>----------</td>
					</tr>

					<!-- QR Code removed as per requirement
					<tr>
						<td colspan="<?=$mrp_column+5?>" align="center">
						<?php 
								//if the parameter value has slash
								 $sales_code = str_replace('=', '-', str_replace('/', '_', base64_encode($sales_code)));
						?>
							<div style="display:inline-block;vertical-align:middle;line-height:16px !important;">
								
								<?php

								echo $CI->print_qr($sales_code);
								?>

							</div>
						
						</td>
					</tr>
					-->

					</tfoot>
				</table>
			</td>
		</tr>
	</table>
	</div>
	<center >
  <div class="row no-print">
  <div class="col-md-12">
  <div class="col-md-2 col-md-offset-5 col-xs-4 col-xs-offset-4 form-group">
    <button type="button" id="" class="btn btn-block btn-success btn-xs" onclick="window.print();" title="Print">Print</button>
    <?php if(isset($_GET['redirect'])){ ?>
		<a href="<?= base_url().$_GET['redirect'];?>"><button type="button" class="btn btn-block btn-danger btn-xs" title="Back">Back</button></a>
	<?php } ?>
   </div>
   </div>
   </div>

</center>
</body>
</html>