<!DOCTYPE html>
<html>
<title><?= $page_title;?>- GST Format</title>
<head>
<link rel='shortcut icon' href='<?php echo $theme_link; ?>images/favicon.ico' />

<style>

table, th, td {
    border: 0.02pt solid #0070C0;
    border-collapse: collapse;   
    

}
th, td {
    /*padding: 5px;*/
    text-align: left;   
    vertical-align:top 
}
body{
  word-wrap: break-word;
  font-family:  'sans-serif','Arial';
  font-size: 11px;
  /*height: 210mm;*/
}
.style_hidden{
  border-style: hidden;
}
.fixed_table{
  table-layout:fixed;
}
.text-center{
  text-align: center;
}
.text-left{
  text-align: left;
}
.text-right{
  text-align: right;
}
.text-bold{
  font-weight: bold;
}
.bg-sky{
  background-color: #E8F3FD;
}
/* 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;
}

/* Invoice Content with Borders */
.invoice-content-border {
  border: 1px solid #000; /* Border on all sides around invoice content - matching sample */
  padding: 5mm; /* Internal padding for content - matching sample spacing */
  box-sizing: border-box;
  width: 100%;
}

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

@media print {
    @page {
        size: A4 !important;
        margin: 0 15mm 0 15mm !important; /* Left and right margins only - borders on top/bottom */
    }
    
    .invoice-a4-container {
        width: 100% !important;
        max-width: 180mm !important;
        margin: 0 auto !important;
        padding: 0 !important;
    }
    
    .invoice-content-border {
        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-sizing: border-box !important;
    }
}

 #clockwise {
       rotate: 90;
    }

    #counterclockwise {
       rotate: -90;
    }

</style>
</head>
<body>
<div class="invoice-a4-container">
<div class="invoice-content-border">
<?php
   
    //Current Store Records
    $store_rec = get_store_details();
    $store_logo=(!empty($store_rec->store_logo)) ? $store_rec->store_logo : store_demo_logo();

    //Sales Records
    $sales_rec = get_sales_details($sales_id);
    $customer_rec = get_customer_details($sales_rec->customer_id);

    //Customer Records
    $state_rec = (!empty($customer_rec->state_id)) ? get_state_details($customer_rec->state_id) : '';
    $customer_state_name = (!empty($state_rec)) ? $state_rec->state : $store_rec->state;
    
    //Customer Find Previous Due & Total Due
    $previous_due=($customer_rec->sales_due)-($sales_rec->grand_total-$sales_rec->paid_amount);
    $previous_due = ($previous_due>0) ? $previous_due : 0;
    $total_due=$customer_rec->sales_due;

    //Customer Shipping Address Records
    $shipping_country='';
    $shipping_state='';
    $shipping_city='';
    $shipping_address='';
    $shipping_postcode='';
    if(!empty($customer_rec->shippingaddress_id)){
        $Q2 = $this->db->select("c.country,s.state,a.city,a.postcode,a.address")
                        ->where("a.id",$customer_rec->shippingaddress_id)
                        ->from("db_shippingaddress a")
                        ->join("db_country c","c.id = a.country_id",'left')
                        ->join("db_states s","s.id = a.state_id",'left')
                        ->get();                    
        if($Q2->num_rows()>0){
          $shipping_country=$Q2->row()->country;
          $shipping_state=$Q2->row()->state;
          $shipping_city=$Q2->row()->city;
          $shipping_address=$Q2->row()->address;
          $shipping_postcode=$Q2->row()->postcode;
        }
      }

    //Customer if Coupon Code applied, then get Records
    $coupon_code = '';
    $coupon_type = '';
    $coupon_value=0;
    if(!empty($sales_rec->coupon_id)){
      $coupon_details =get_customer_coupon_details($sales_rec->coupon_id);
      $coupon_code =$coupon_details->code;
      $coupon_value =$coupon_details->value;
      $coupon_type =$coupon_details->type;
    }

    ?>

<caption>
      <center>
        <span style="font-size: 18px;text-transform: uppercase;">
          Tax Invoice
        </span>
      </center>
</caption>

<table autosize="1" style="overflow: wrap" id='mytable' align="center" width="100%" height='100%'  cellpadding="0" cellspacing="0"  >
<!-- <table align="center" width="100%" height='100%'   > -->
    <thead>

      <tr>
        <th colspan="16">
          <table width="100%" height='100%' class="style_hidden fixed_table">
              <tr>
                <!-- First Half -->
                <td colspan="2">
                  <img src="<?= base_url($store_logo);?>" width='100%'>
                </td>

                <td colspan=5>
                <span style="font-size: 12px;">
                  <b><?php echo $store_rec->store_name; ?></b><br/>
                    <?php echo $this->lang->line('address')." : ".$store_rec->address; ?><br/>
                    <?php echo $this->lang->line('mobile')." : ".$store_rec->mobile; ?><br/>
                   <!--  <?php echo $store_rec->country; ?><br/> -->
                    
                    <?php echo (!empty(trim($store_rec->email))) ? $this->lang->line('email')." : ".$store_rec->email."<br>" : '';?>
                    <?php echo (!empty(trim($store_rec->gst_no))) ? $this->lang->line('gst_number')." : ".$store_rec->gst_no."<br>" : '';?>
                    <!-- <?php echo (!empty(trim($store_rec->vat_no))) ? $this->lang->line('tax_number')." : ".$store_rec->vat_no."<br>" : '';?> -->
                  </span>
                </td>

                <!-- Second Half -->
                <td colspan="6" rowspan="1">
                  <span>
                    <table style="width: 100%;" class="style_hidden fixed_table">
                    
                        <tr>
                          <td colspan="4">
                            Invoice No.<br>
                            <span style="font-size: 100%;">
                              <b><?php echo "$sales_rec->sales_code"; ?></b>
                            </span>
                          </td>
                          <td colspan="4">
                            Dated<br>
                            <span style="font-size: 12px;">
                              <b><?php echo show_date($sales_rec->sales_date); ?></b>
                            </span>
                          </td>
                        </tr>
                        <tr>
                          <td colspan="8">
                            Reference No.<br>
                            <span style="font-size: 12px;">
                              <b><?php echo "$sales_rec->reference_no"; ?></b>
                            </span>
                          </td>
                          
                        </tr>
                        
                        <tr>
                          <td colspan="8">
                            <span>
                                <b><?= $this->lang->line('bank_details'); ?></b><br/>
                              </span>
                              <span style="font-size: 12px;">
                                  <?= nl2br($store_rec->bank_details);  ?><br><br/>
                                 
                                </span>
                                 
                          </td>
                        </tr>
                        

                    
                    </table>
                  </span>
                </td>
              </tr>

              <tr>
                <!-- Bottom Half -->
                <td colspan="7">
                  <b><?= $this->lang->line('customer_details'); ?></b><br/>
                  <span style="font-size: 12px;">
                      <?php echo $this->lang->line('name')." : ".$customer_rec->customer_name; ?><br/>
                        <?php echo (!empty(trim($customer_rec->address))) ? $this->lang->line('address')." : ".$customer_rec->address."<br>" : '';?>
                        <?php echo (!empty(trim($customer_rec->gstin))) ? $this->lang->line('gstin')." : ".$customer_rec->gstin."<br>" : '';?>
                        <?php 
                               /* if(!empty($customer_rec->customer_mobile)){
                                  echo $customer_rec->customer_mobile;
                                }*/
                                
                                /*
                                if(!empty($customer_rec->state_id)){
                                  echo ",".$customer_rec->state_id;
                                }
                                if(!empty($customer_rec->city)){
                                  echo ",".$customer_rec->city;
                                }
                                if(!empty($customer_rec->postcode)){
                                  echo "-".$customer_rec->postcode;
                                }*/
                              ?>
                              
                        
                        <?php echo (!empty(trim($customer_rec->email))) ? $this->lang->line('email')." : ".$customer_rec->email."<br>" : '';?>
                        <?php echo (!empty(trim($customer_rec->mobile))) ? $this->lang->line('mobile')." : ".$customer_rec->mobile."<br>" : '';?>
                        <!--<?php echo (!empty(trim($customer_rec->tax_number))) ? $this->lang->line('tax_number').": ".$customer_rec->tax_number."<br>" : '';?> -->
                  </span>
                </td>

                <td colspan="6">
                  <b><?= $this->lang->line('shipping_address'); ?></b><br/>
                  <span style="font-size: 12px;">
                      <?php echo $this->lang->line('name')." : ".$customer_rec->customer_name; ?><br/>
                        
                       <?php 
                                    echo $this->lang->line('address') .":".$shipping_address;
                                    echo "<br>".$this->lang->line('country') .":".$shipping_country;
                                    echo ", ".$this->lang->line('state') .":".$shipping_state;
                                    echo "<br>".$this->lang->line('city') .":".$shipping_city;
                                    echo ", ".$this->lang->line('postcode') .":".$shipping_postcode;

                                  ?>
                  </span>
                </td>

                
              </tr>




            
          </table>
      </th>
      </tr>

      <tr>
        <td colspan="16">&nbsp; </td>
      </tr>
      <tr class="bg-sky"><!-- Colspan 10 -->
        <th colspan='1' class="text-center"><?= $this->lang->line('sl_no'); ?></th>
        <th colspan='5' class="text-center" ><?= $this->lang->line('description_of_goods'); ?></th>
        <th colspan='2' class="text-center"><?= $this->lang->line('hsn/sac'); ?></th>
        <th colspan='1' class="text-center"><?= $this->lang->line('gst_rate'); ?></th>
        <th colspan='1' class="text-center"><?= $this->lang->line('qty'); ?></th>
        <th colspan='2' class="text-center"><?= $this->lang->line('rate'); ?></th>
        <th colspan='2' class="text-center"><?= $this->lang->line('discount'); ?></th>
        <th colspan='2' class="text-center"><?= $this->lang->line('amount'); ?></th>
      </tr>
  </thead>
<tbody>
  <!-- <tr>
    <td colspan='16'> -->
 <?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;
              $tot_before_tax=0;

              $this->db->select(" a.description,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 , d.unit_name,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_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 d","d.id = c.unit_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) {
                  $discount = (empty($res2->discount_input)||$res2->discount_input==0)? store_number_format(0):store_number_format($res2->discount_input)."%";
                  $discount_amt = (empty($res2->discount_amt)||$res2->discount_input==0)? '0':$res2->discount_amt."";
                  $before_tax=$res2->price_per_unit;// * $res2->sales_qty;
                  
                  // Check if total_cost is invalid (1 or 0) and recalculate if needed
                  $display_total_cost = floatval($res2->total_cost);
                  
                  // Determine the correct quantity to use for multi-unit items
                  // Always start with sales_qty as base
                  $calc_qty = floatval($res2->sales_qty);
                  if (isset($res2->unit_type) && $res2->unit_type == 'alternate') {
                      // Use alternate unit quantity if available and > 0
                      if (isset($res2->sales_qty_alternate) && floatval($res2->sales_qty_alternate) > 0) {
                          $calc_qty = floatval($res2->sales_qty_alternate);
                      }
                  } else {
                      // Use main unit quantity if available and > 0
                      if (isset($res2->sales_qty_main) && floatval($res2->sales_qty_main) > 0) {
                          $calc_qty = floatval($res2->sales_qty_main);
                      }
                  }
                  
                  // Always recalculate if total_cost is invalid (1 or 0 or very close to 1)
                  if ($display_total_cost <= 0 || abs($display_total_cost - 1) < 0.01) {
                      // Recalculate from price, qty, tax, and discount
                      $calc_price = floatval($res2->price_per_unit);
                      $calc_discount = floatval($res2->discount_amt);
                      $calc_tax = floatval($res2->tax_amt);
                      
                      // Ensure we have a valid quantity
                      if ($calc_qty <= 0) {
                          $calc_qty = floatval($res2->sales_qty);
                      }
                      
                      // Recalculate if we have valid price and quantity
                      if ($calc_price > 0 && $calc_qty > 0) {
                          $base_amt = ($calc_price * $calc_qty) - $calc_discount;
                          if ($res2->tax_type == 'Inclusive') {
                              $display_total_cost = $base_amt;
                          } else {
                              $display_total_cost = $base_amt + $calc_tax;
                          }
                      } elseif ($calc_price > 0 && $calc_qty <= 0) {
                          // If we have price but no qty, try to use unit_total_cost
                          if (!empty($res2->unit_total_cost) && floatval($res2->unit_total_cost) > 0) {
                              $display_total_cost = floatval($res2->unit_total_cost);
                          }
                      }
                  }
                  $tot_cost_before_tax = $display_total_cost;
                  echo "<tr>";  
                  echo "<td colspan='1' class='text-center'>".++$i."</td>";
                  echo "<td colspan='5'>";
                  echo $res2->item_name;
                  echo (!empty($res2->description)) ? "<br><i>[".nl2br($res2->description)."]</i>" : '';
                  // Display batch details if batch is enabled and batch information exists
                  if($res2->batch_enabled == 1 && !empty($res2->batch_number)) {
                      echo "<br><small><strong>Batch No:</strong> ".$res2->batch_number."</small>";
                      if(!empty($res2->manufacturing_date) && $res2->manufacturing_date != '0000-00-00') {
                          $formatted_mfg_date = date('d-m-Y', strtotime($res2->manufacturing_date));
                          echo "<br><small><strong>MFG Date:</strong> ".$formatted_mfg_date."</small>";
                      }
                      if(!empty($res2->expiry_date) && $res2->expiry_date != '0000-00-00') {
                          $formatted_exp_date = date('d-m-Y', strtotime($res2->expiry_date));
                          echo "<br><small><strong>Expiry Date:</strong> ".$formatted_exp_date."</small>";
                      }
                  }
                  echo "</td>";
                  echo "<td colspan='2' class='text-center'>".$res2->hsn."</td>";
                  
                  echo "<td colspan='1' class='text-right'>".store_number_format($res2->tax)."%</td>";
                  
                  // Display quantity with unit name (supports multi-unit)
                  $qty_display = '';
                  $unit_label = '';
                  $main_unit_name = !empty($res2->main_unit_name) ? $res2->main_unit_name : $res2->unit_name;
                  $alt_unit_name = !empty($res2->alternate_unit_name) ? $res2->alternate_unit_name : '';
                  
                  if (isset($res2->unit_type) && $res2->unit_type == 'alternate') {
                      if (isset($res2->sales_qty_alternate) && $res2->sales_qty_alternate > 0) {
                          $qty_display = format_qty($res2->sales_qty_alternate);
                      } else {
                          $qty_display = format_qty($res2->sales_qty);
                      }
                      $unit_label = $alt_unit_name ? ' '.$alt_unit_name : '';
                  } else {
                      if (isset($res2->sales_qty_main) && $res2->sales_qty_main > 0) {
                          $qty_display = format_qty($res2->sales_qty_main);
                      } else {
                          $qty_display = format_qty($res2->sales_qty);
                      }
                      $unit_label = $main_unit_name ? ' '.$main_unit_name : '';
                  }
                  
                  echo "<td colspan='1' class='text-center'>".$qty_display.$unit_label."</td>";
                  //echo "<td style='text-align: right;'>".store_number_format($res2->tax_amt)."</td>";
                  //echo "<td style='text-align: right;'>".store_number_format($discount)."</td>";
                  //echo "<td style='text-align: right;'>".store_number_format($discount_amt)."</td>";
 
                  echo "<td colspan='2' class='text-right'>".store_number_format($before_tax)."</td>";
                 echo "<td colspan='2' class='text-right'>".($discount)."</td>";
                  //echo "<td class='text-right'>".store_number_format($res2->price_per_unit)."</td>";
                  
                  echo "<td colspan='2' class='text-right'>".store_number_format($tot_cost_before_tax)."</td>";
                  echo "</tr>";  
                  // Accumulate total quantity in main units for footer (use sales_qty_main if available)
                  if (isset($res2->sales_qty_main) && $res2->sales_qty_main > 0) {
                      $tot_qty += $res2->sales_qty_main;
                  } else {
                      $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_before_tax +=$before_tax;
                  $tot_total_cost +=$display_total_cost;
              }
              ?>
      <!-- </td>
  </tr> -->
  </tbody>
<tfoot>
  <?php
                        $tot_price_before_tax = $tot_price_after_tax = $tot_cgst_amt =$tot_sgst_amt=$tot_sgst_amt=$tot_igst_amt = 0;

                        $this->db->select(" c.item_name,
                                            COALESCE(SUM(a.price_per_unit),0) AS price_before_tax, 
                                            b.tax,
                                            b.tax_name,
                                            COALESCE(SUM(a.tax_amt),0) AS sum_of_tax_amt,
                                            COALESCE(SUM(a.total_cost),0) AS price_after_tax,
                                            c.tax_type,
                                            c.sku,c.hsn
                                            ");

                        $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 d","d.id = c.unit_id","left");

                        //echo $this->db->get_compiled_select();exit();
                        $q2=$this->db->get();
                        foreach ($q2->result() as $res2) {
                          $hsn = $res2->hsn;
                          //$price_before_tax = $res2->price_before_tax;
                          $price_before_tax = $res2->price_before_tax;
                          $price_after_tax = $res2->price_after_tax;

                          $tax_per = $res2->tax;
                          $sum_of_tax_amt = $res2->sum_of_tax_amt;

                          $price_before_tax = $price_after_tax - $sum_of_tax_amt;

                          $tax_type='';
                          //$tax_type = ($res2->tax_type=='Exclusive') ? 'Exc.' : 'Inc.';
                          if( $customer_rec->id==1 || (strtoupper($customer_state_name) == strtoupper($store_rec->state))){
                            $sgst_per = $cgst_per = $tax_per."%";
                            $sgst_amt = $cgst_amt = $sum_of_tax_amt / 2;
                            $igst_per = $igst_amt = '';
                          }else{
                            $sgst_per = $cgst_per = '';
                            $sgst_amt = $cgst_amt = '';
                            $igst_per = $tax_per."%";
                            $igst_amt = $sum_of_tax_amt;
                          }

                       $tot_price_before_tax +=$price_before_tax;
                       $tot_price_after_tax +=(!empty($price_after_tax)) ? $price_after_tax : 0;
                       $tot_cgst_amt +=(!empty($cgst_amt)) ? $cgst_amt : 0;
                       $tot_sgst_amt +=(!empty($sgst_amt)) ? $sgst_amt : 0;
                       $tot_igst_amt +=(!empty($igst_amt)) ? $igst_amt : 0;
                       
                     } 

                     ?>

  <tr class="bg-sky">
    <td colspan="8" class='text-center text-bold'><?= $this->lang->line('total'); ?></td>
    <td colspan="" class='text-bold text-center'></td>
    <td colspan="" class='text-bold text-center'><?=format_qty($tot_qty); ?></td>
    <td colspan="2" class='text-right' ><b><?= store_number_format($tot_before_tax); ?></b></td>
    <td colspan="2" class='text-right' ><b><?= store_number_format($discount_amt); ?></b></td>
    <td colspan="2" class='text-right' ><b><?= store_number_format($tot_total_cost); ?></b></td>
  </tr>
  <!--tr>
    <td colspan="14" class='text-right'><b><?= $this->lang->line('subtotal'); ?></b></td>
    <td colspan="2" class='text-right' ><b><?= store_number_format($tot_total_cost); ?></b></td>
  </tr-->
  <?php if($tot_cgst_amt!=0 && !empty($tot_cgst_amt)){ ?>
  <tr>
    <td colspan="14" class='text-right'><b><?= $this->lang->line('cgst'); ?></b></td>
    <td colspan="2" class='text-right' ><b><?= store_number_format($tot_cgst_amt); ?></b></td>
  </tr>
  <tr>
    <td colspan="14" class='text-right'><b><?= $this->lang->line('sgst'); ?></b></td>
    <td colspan="2" class='text-right' ><b><?= store_number_format($tot_sgst_amt); ?></b></td>
  </tr>
  <?php } else{?>
  <tr>
    <td colspan="14" class='text-right'><b><?= $this->lang->line('igst'); ?></b></td>
    <td colspan="2" class='text-right' ><b><?= store_number_format($tot_igst_amt); ?></b></td>
  </tr>
<?php } ?>
<?php if($sales_rec->other_charges_amt!=0 && !empty($sales_rec->other_charges_amt)){ ?>
  <tr>
    <td colspan="14" class='text-right'><b><?= $this->lang->line('other_charges'); ?></b></td>
    <td colspan="2" class='text-right' ><b><?= store_number_format($sales_rec->other_charges_amt); ?></b></td>
  </tr>
  <?php } ?>

  <?php if(!empty($coupon_code)){ ?>
  <tr>
    <td colspan="6" class='text-left'><b>
      <?= $this->lang->line('couponCode'); ?> : <?=getTruncatedCCNumber($coupon_code);?>
    </b>
    </td>
    <td colspan="8" class='text-right'><b>
      <?= $this->lang->line('couponDiscount'); ?> <?= ($coupon_type=='Percentage') ? $coupon_value .'%' : '[Fixed]' ;?>
    </b>
    </td>
    <td colspan="2" class='text-right' ><b><?= store_number_format($sales_rec->coupon_amt); ?></b></td>
  </tr>
  <?php } ?>

  <?php if($sales_rec->tot_discount_to_all_amt!=0 && !empty($sales_rec->tot_discount_to_all_amt)){ ?>
  <tr>
    <td colspan="14" class='text-right'><b><?= $this->lang->line('discount_on_all'); ?>(<?php echo $sales_rec->discount_to_all_input." "; echo ($sales_rec->discount_to_all_type=='in_percentage') ? '%' : 'Fixed'; ?>)</b></td>
    <td colspan="2" class='text-right' ><b><?= store_number_format($sales_rec->tot_discount_to_all_amt); ?></b></td>
  </tr>
  <?php } ?>
    <tr>
    <td colspan="14" class='text-right'><b><?= $this->lang->line('round_off'); ?></b></td>
    <td colspan="2" class='text-right' ><b><?= store_number_format($sales_rec->round_off); ?></b></td>
  </tr>
   <?php  ?>
  <tr>
    <td colspan="14" class='text-right'><b><?= $this->lang->line('grand_total'); ?></b></td>
    <td colspan="2" class='text-right' ><b><?= store_number_format($sales_rec->grand_total); ?></b></td>
  </tr>

  <?php if($store_rec->previous_balance_bit==1){ ?>
  <tr>
    <td colspan="14" class='text-right'><?= $this->lang->line('previous_balance'); ?></td>
    <td colspan="2" class='text-right' ><?php echo store_number_format($previous_due); ?></td>
  </tr>
  <tr>
    <td colspan="14" class='text-right text-italic'><?= $this->lang->line('total_due'); ?></td>
    <td colspan="2" class='text-right' ><?php echo store_number_format($total_due); ?></td>
  </tr>  
  <?php } ?>

  <tr>
    <td colspan="16">
      <span class='amt-in-word'>Amount in words:
        <i style='font-weight:bold;'><?=no_to_words($sales_rec->grand_total)." Only"?>
        </i>
    </span>  
    </td>
  </tr>
  <tr>
    <td colspan="16">
      <span class='amt-in-word'>
        <?= $this->lang->line('note') .":<b>". nl2br($sales_rec->sales_note)."</b>";?>
    </span>  
    </td>
  </tr>
  <?php if(!empty($sales_rec->invoice_terms) && $store_rec->t_and_c_status) {?>
  <tr>
    <td colspan="16">
      <span>
        <b><?= $this->lang->line('invoiceTerms') .":</b>". nl2br(html_entity_decode($sales_rec->invoice_terms))."";?>
    </span>  
    </td>
  </tr>
<?php } ?>

  <!-- Tax Table -->

  <tr>
        <td colspan="16">
          <table width="100%" class="style_hidden fixed_table">
            <tbody>
              <tr>
                <td colspan="16">
                  <span>
                    <table style="width: 100%;" class="style_hidden fixed_table">
                      <tbody>

                        <tr class="bg-sky text-bold">
                          <td colspan='1' class='text-center' rowspan="2" width="15%"><?= $this->lang->line('hsn/sac'); ?></td>
                          <td colspan='1' class='text-center' rowspan="2" width="15%"><?= $this->lang->line('taxable_amount'); ?></td>
                          <td colspan='4' class='text-center' colspan="2"  width="20%">
                            <?= $this->lang->line('cgst'); ?>
                          </td>
                          <td colspan='4' class='text-center' colspan="2" width="20%">
                            <?= $this->lang->line('sgst'); ?>
                          </td>
                          <td colspan='4' class='text-center' colspan="2" width="20%">
                            <?= $this->lang->line('igst'); ?>
                          </td>
                          <td colspan='2' class='text-center' width="10%" rowspan="2">
                            <?= $this->lang->line('total'); ?>
                          </td>
                        </tr>

                        
                        <tr class="bg-sky text-bold">
                          <td colspan='2' class='text-center'>Rate</td><td colspan='2' class='text-center'>Amt</td>
                          <td colspan='2' class='text-center'>Rate</td><td colspan='2' class='text-center'>Amt</td>
                          <td colspan='2' class='text-center'>Rate</td><td colspan='2' class='text-center'>Amt</td>
                        </tr>
                        <?php
                        $tot_price_before_tax = $tot_price_after_tax = $tot_cgst_amt =$tot_sgst_amt=$tot_sgst_amt=$tot_igst_amt = 0;
                        /*$q2=$this->db->query(" SELECT c.item_name,  COALESCE(SUM(a.price_per_unit),0) AS price_before_tax, 
                                               b.tax,b.tax_name,
                                               COALESCE(SUM(a.tax_amt),0) AS sum_of_tax_amt,
                                               COALESCE(SUM(a.total_cost),0) AS price_after_tax,c.tax_type,
                                               c.sku 
                                               FROM 
                                               db_salesitems AS a,db_tax AS b,db_items AS c , db_units AS d 
                                               WHERE 
                                               d.id = c.unit_id AND c.id=a.item_id AND b.id=a.tax_id AND a.sales_id='$sales_id' GROUP BY b.id");*/

                        $this->db->select(" c.item_name,  COALESCE(SUM(a.price_per_unit),0) AS price_before_tax, 
                                               b.tax,b.tax_name,c.hsn,
                                               COALESCE(SUM(a.tax_amt),0) AS sum_of_tax_amt,
                                               COALESCE(SUM(a.total_cost),0) AS price_after_tax,c.tax_type,
                                               c.sku 
                                            ");

                        $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 d","d.id = c.unit_id","left");
                        $this->db->group_by("c.hsn,a.tax_id");
                        //echo $this->db->get_compiled_select();exit();
                        $q2=$this->db->get();
                        
                        foreach ($q2->result() as $res2) {
                          $hsn = $res2->hsn;
                          //$price_before_tax = $res2->price_before_tax;
                          $price_before_tax = $res2->price_before_tax;
                          $price_after_tax = $res2->price_after_tax;

                          $tax_per = $res2->tax;
                          $sum_of_tax_amt = $res2->sum_of_tax_amt;

                          $price_before_tax = $price_after_tax - $sum_of_tax_amt;

                          $tax_type='';
                          //$tax_type = ($res2->tax_type=='Exclusive') ? 'Exc.' : 'Inc.';
                          if( $customer_rec->id==1 || (strtoupper($customer_state_name) == strtoupper($store_rec->state))){
                            $sgst_per = $cgst_per = $tax_per;
                            $sgst_amt = $cgst_amt = $sum_of_tax_amt / 2;
                            $igst_per = $igst_amt = 0;
                          }else{
                            $sgst_per = $cgst_per = 0;
                            $sgst_amt = $cgst_amt = 0;
                            $igst_per = $tax_per;
                            $igst_amt = $sum_of_tax_amt;
                          }
                          

                         ?>
                         <tr>
                          <td colspan='1' class='text-center'><?= $hsn ?></td>
                          <td colspan='1' class='text-center'><?= store_number_format($price_before_tax)." ".$tax_type ?></td>
                          <td colspan='2' class='text-center'><?= (!empty($cgst_per))? store_number_format($cgst_per/2):''; ?>%</td>
                            <td colspan='2' class='text-center'><?= store_number_format($cgst_amt) ?></td>
                          <td colspan='2' class='text-center'><?= (!empty($sgst_per))? store_number_format($sgst_per/2):''; ?>%</td>
                            <td colspan='2' class='text-center'><?= store_number_format($sgst_amt) ?></td>
                          <td colspan='2' class='text-center'><?= (!empty($igst_per))? store_number_format($igst_per):''; ?>%</td>
                            <td colspan='2' class='text-center'><?= store_number_format($igst_amt) ?></td>
                          <td colspan='2' class='text-center'><?=store_number_format($price_after_tax)?></td>
                        </tr>
                       <?php 
                       $tot_price_before_tax +=$price_before_tax;
                       $tot_price_after_tax +=(!empty($price_after_tax)) ? $price_after_tax : 0;
                       $tot_cgst_amt +=(!empty($cgst_amt)) ? $cgst_amt : 0;
                       $tot_sgst_amt +=(!empty($sgst_amt)) ? $sgst_amt : 0;
                       $tot_igst_amt +=(!empty($igst_amt)) ? $igst_amt : 0;
                       
                     } ?>
                          <tr class='bg-sky text-bold'>
                          <td colspan='1' class='text-center'>Total</td>
                          <td colspan='1' class='text-center'><?= store_number_format($tot_price_before_tax) ?></td>
                          <td colspan='2' class='text-center'></td>
                            <td colspan='2' class='text-center'><?= (!empty($cgst_per)) ? store_number_format($tot_cgst_amt) : '' ?></td>
                          <td colspan='2' class='text-center'></td>
                            <td colspan='2' class='text-center'><?= (!empty($sgst_per)) ? store_number_format($tot_sgst_amt) : '' ?></td>
                          <td colspan='2' class='text-center'></td>
                            <td colspan='2' class='text-center'><?= (!empty($igst_per)) ? store_number_format($tot_igst_amt) : '' ?></td>
                          <td colspan='2' class='text-center'><?=store_number_format($sales_rec->grand_total)?></td>
                        </tr>
                      </tbody>
                    </table>
                  </span>
                </td>
              </tr>
            </tbody>
          </table>
      </td>
      </tr>
      <!-- Tax table end -->

      <!-- TAX SUMMARY -->
      <tr>
        <td colspan="16" style="padding: 10px;">
          <table style="width: 60%; border: 1px solid black; border-collapse: collapse;">
            <thead>
              <tr style="background-color: #f0f0f0;">
                <th colspan="4" style="text-align: center; padding: 5px; border: 1px solid black;">TAX SUMMARY</th>
              </tr>
              <tr style="background-color: #f0f0f0;">
                <th style="padding: 5px; border: 1px solid black; text-align: center;">Tax Rate</th>
                <th style="padding: 5px; border: 1px solid black; text-align: right;">Taxable Amt</th>
                <th style="padding: 5px; border: 1px solid black; text-align: right;">Tax Amt</th>
                <th style="padding: 5px; border: 1px solid black; text-align: right;">Total Amt</th>
              </tr>
            </thead>
            <tbody>
              <?php
              // Build tax summary with proper calculation for inclusive/exclusive tax
              $tax_q4 = $this->db->query("SELECT a.tax_type, b.tax as tax_rate, b.tax_name,
                a.total_cost, a.tax_amt, a.price_per_unit, a.sales_qty, a.discount_amt
                FROM db_salesitems a JOIN db_tax b ON b.id = a.tax_id WHERE a.sales_id = '$sales_id'");
              
              $tax_summary_data = array();
              foreach($tax_q4->result() as $t4_item) {
                $tax_rate = floatval($t4_item->tax_rate);
                $tax_key = $tax_rate . '%';
                if ($tax_rate == 0) {
                  $tax_key = (stripos($t4_item->tax_name, 'exempt') !== false) ? 'exempt' : '0%';
                }
                
                if (!isset($tax_summary_data[$tax_key])) {
                  $tax_summary_data[$tax_key] = array(
                    'rate' => $tax_rate,
                    'name' => $t4_item->tax_name,
                    'taxable' => 0,
                    'tax' => 0,
                    'total' => 0
                  );
                }
                
                // Ensure we have valid numeric values
                $item_total_cost = floatval($t4_item->total_cost);
                $item_tax_amt = floatval($t4_item->tax_amt);
                
                // If values are invalid, recalculate
                if ($item_total_cost <= 0 || $item_total_cost == 1) {
                  $item_price = floatval($t4_item->price_per_unit);
                  $item_qty = floatval($t4_item->sales_qty);
                  $item_discount = floatval($t4_item->discount_amt);
                  
                  if ($item_price > 0 && $item_qty > 0) {
                    $base_amount = ($item_price * $item_qty) - $item_discount;
                    if ($t4_item->tax_type == 'Inclusive') {
                      if ($tax_rate > 0) {
                        $item_taxable_amt = $base_amount / (1 + ($tax_rate / 100));
                        $item_tax_amt = $base_amount - $item_taxable_amt;
                      } else {
                        $item_taxable_amt = $base_amount;
                        $item_tax_amt = 0;
                      }
                      $item_total_cost = $base_amount;
                    } else {
                      $item_taxable_amt = $base_amount;
                      if ($tax_rate > 0) {
                        $item_tax_amt = $base_amount * ($tax_rate / 100);
                      } else {
                        $item_tax_amt = 0;
                      }
                      $item_total_cost = $item_taxable_amt + $item_tax_amt;
                    }
                  } else {
                    $item_taxable_amt = max(0, $item_total_cost - $item_tax_amt);
                  }
                } else {
                  // Calculate taxable amount correctly based on tax type
                  if ($t4_item->tax_type == 'Inclusive') {
                    if ($tax_rate > 0 && $item_total_cost > 0) {
                      $item_taxable_amt = $item_total_cost / (1 + ($tax_rate / 100));
                      $item_tax_amt = $item_total_cost - $item_taxable_amt;
                    } else {
                      $item_taxable_amt = max(0, $item_total_cost - $item_tax_amt);
                    }
                  } else {
                    $item_taxable_amt = $item_total_cost - $item_tax_amt;
                  }
                  if ($item_taxable_amt < 0) {
                    $item_taxable_amt = 0;
                  }
                }
                
                $tax_summary_data[$tax_key]['taxable'] += $item_taxable_amt;
                $tax_summary_data[$tax_key]['tax'] += $item_tax_amt;
                $tax_summary_data[$tax_key]['total'] += $item_total_cost;
              }
              
              $s4_taxable = 0; $s4_tax = 0; $s4_total = 0;
              // Sort by tax rate descending
              krsort($tax_summary_data);
              foreach($tax_summary_data as $key => $t4) {
                $t4_label = $t4['rate'] . '%';
                if ($key == 'exempt') {
                  $t4_label = 'Ex.';
                } elseif ($t4['rate'] == 0) {
                  $t4_label = '0%';
                }
                $s4_taxable += $t4['taxable']; $s4_tax += $t4['tax']; $s4_total += $t4['total'];
                echo '<tr><td style="padding:5px;border:1px solid black;text-align:center;">'.$t4_label.'</td>';
                echo '<td style="padding:5px;border:1px solid black;text-align:right;">'.$CI->currency().' '.store_number_format($t4['taxable']).'</td>';
                echo '<td style="padding:5px;border:1px solid black;text-align:right;">'.$CI->currency().' '.store_number_format($t4['tax']).'</td>';
                echo '<td style="padding:5px;border:1px solid black;text-align:right;">'.$CI->currency().' '.store_number_format($t4['total']).'</td></tr>';
              }
              ?>
              <tr style="background-color: #f0f0f0; font-weight: bold;">
                <td style="padding:5px;border:1px solid black;text-align:center;">Totals</td>
                <td style="padding:5px;border:1px solid black;text-align:right;"><?=$CI->currency().' '.store_number_format($s4_taxable);?></td>
                <td style="padding:5px;border:1px solid black;text-align:right;"><?=$CI->currency().' '.store_number_format($s4_tax);?></td>
                <td style="padding:5px;border:1px solid black;text-align:right;"><?=$CI->currency().' '.store_number_format($s4_total);?></td>
              </tr>
            </tbody>
          </table>
        </td>
      </tr>
      <!-- END TAX SUMMARY -->

      <!-- T&C & Bank Details & signatories-->
      <tr>
        <td colspan="16">
          <table width="100%" class="style_hidden fixed_table">

              <tr>
                <td colspan="16">
                  <span>
                    <table style="width: 100%;" class="style_hidden fixed_table">



                         <tr>
                          <td colspan='8' style="height:80px;">
                            <span><b> <?= $this->lang->line('customer_signature'); ?></b></span>
                          </td>
                          <td colspan='8'>
                            <span><b> <?= $this->lang->line('authorised_signatory'); ?></b></span><br>
                            <!--img width="30%" src="uploads/stamp/stamp.png"><br-->
                          </td>
                        </tr>

                    </table>
                  </span>
                </td>
              </tr>

 </table>
      </td>
      </tr>
      <!-- T&C & Bank Details & signatories End -->

      <?php if(!empty($store_rec->sales_invoice_footer_text)) {?>
      <tr>
        <td colspan="16" style="text-align: center;font-size: 11px;">
          <?= $store_rec->sales_invoice_footer_text; ?>
        </td>
      </tr>
      <?php } ?>
      <tr>
        <td colspan="16" style="text-align: center;font-size: 11px;">
          <center>
        <span style="font-size: 11px;text-transform;">
        <!--span style="font-size: 11px;text-transform: uppercase;">
          This is Computer Generated Invoice-->
        <span style="font-size: 11px;text-transform: uppercase;">
          Thank You For Choosing Our Services
        </span>
      </center>
        </td>
      </tr>
</tfoot>
</table>
</div> <!-- End invoice-content-border -->
</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>