<?php

include('MyPDF.php');

class Sales extends MyPDF{
	//public $CI=null;

	protected $sales_id =null;

	//public $store =array();

	protected $customer =array();

	protected $sales =array();

	public function __construct(array $param=array())
	{
		parent::__construct();

		$this->sales_id = $param['sales_id'];

		//$this->CI =& get_instance();

		//$this->store = get_store_details();//Declared in MyPDF Pa

		$this->sales = get_sales_details($this->sales_id);
		
		$this->customer = get_customer_details($this->sales->customer_id);

	}
	public function _get_customer_details()
    {   

    	$customer = $this->customer;//array()

    	$store = $this->store;//array()

    	//Customer Records
	    $state = (!empty($customer->state_id)) ? get_state_details($customer->state_id) : '';
	    $customer_state_name = (!empty($state)) ? $state->state : $store->state;

        $w = 100;
        $h = 40;

        $custmer_details = '<span style="color:rgb(65, 59, 212);font-style:italic;">'.$this->CI->lang->line('bill_to').'</span>';
        $custmer_details .= "<br><b>".$this->CI->lang->line('name')." :</b> ".$customer->customer_name;
        // Show Tax number (GST or VAT)
        if (!empty($customer->gstin)) {
            $custmer_details .= "<br><b>".$this->CI->lang->line('tax_number')." :</b> ".$customer->gstin;
        } elseif (!empty($customer->tax_number)) {
            $custmer_details .= "<br><b>".$this->CI->lang->line('tax_number')." :</b> ".$customer->tax_number;
        }
        // Show Phone (prefer mobile, fallback to phone)
        $phone_number = (!empty($customer->mobile)) ? $customer->mobile : (!empty($customer->phone) ? $customer->phone : '');
        if (!empty($phone_number)) {
            $custmer_details .= "<br><b>".$this->CI->lang->line('phone')." :</b> ".$phone_number;
        }

        //$this->setCellMargins(1,1,1,1);
        $this->setCellPaddings(2,1,1,1);
        $this->setFont($this->get_font_name(), '', 9);
        $this->setFillColor(255, 255, 255);

        $this->writeHTMLCell($w, $h, $x ='6', $y='52', $custmer_details, 1, 0, 1, true, 'J', true);
        return $this;
    } 

    public function _get_invoice_details()
    {
    	$sales = $this->sales;//array()

        $w = 100;
        $h = 40;
        $invoice_details = "";
        $invoice_details = '<span style="color:rgb(65, 59, 212);font-style:italic;">'.$this->CI->lang->line('invoice_details').'</span>';
        $invoice_details .= '<br><b>'.$this->CI->lang->line('invoice_no').' :</b> <span style="font-size:16px;">'.$sales->sales_code.'</span>';
        $invoice_details .= '<br><b>'.$this->CI->lang->line('date').' :</b> <span style="">'.show_date($sales->sales_date).'</span>';
        $invoice_details .= '<br><b>'.$this->CI->lang->line('due_date').' :</b> <span style="">'.((!empty($sales->due_date)) ? show_date($sales->due_date):'').'</span>';
        $invoice_details .= (!empty($sales->reference_no)) ? '<br><b>'.$this->CI->lang->line('reference_no').' :</b> <span style="">'.$sales->reference_no.'</span>' : '';
        $invoice_details .= (!empty($sales->lpo_number)) ? '<br><b>'.($this->CI->lang->line('lpo_number') ?: 'L.P.O No.').' :</b> <span style="color:#337ab7; font-weight:bold;">'.$sales->lpo_number.'</span>' : '';
        $invoice_details .= '<br><b>'.$this->CI->lang->line('payment_status').' :</b> <span style="">'.$sales->payment_status.'</span>';

        $this->writeHTMLCell($w, $h, $x ='104', $y='', $invoice_details, 1, 1, 1, true, 'J', true);
        return $this;
    }

    public function _get_shipping_address()
    {
        $w = 100;
        $h = 40;

        $customer = $this->customer;//array()
        //Customer Shipping Address Records
	    $country='';
	    $state='';
	    $city='';
	    $address='';
	    $postcode='';
	    if(!empty($customer->shippingaddress_id)){
	        $Q2 = $this->CI->db->select("c.country,s.state,a.city,a.postcode,a.address")
	                        ->where("a.id",$customer->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){
	          $country=$Q2->row()->country;
	          $address=$Q2->row()->address;
	          $state=$Q2->row()->state;
	          $city=$Q2->row()->city;
	          $postcode=$Q2->row()->postcode;
	        }
	      }

        $custmer_details = '<span style="color:rgb(65, 59, 212);font-style:italic;">'.$this->CI->lang->line('ship_to').'</span>';

        $custmer_details .= "<br><b>".$this->CI->lang->line('name')." :</b> ".$customer->customer_name;
        $custmer_details .= "<br><b>".$this->CI->lang->line('mobile')." :</b> ".$customer->mobile;
        $custmer_details .= "<br><b>".$this->CI->lang->line('address')." :</b> ".$address;
        $custmer_details .= "<br><b>".$this->CI->lang->line('postcode')." :</b> ".$postcode;
        $custmer_details .= "<br><b>".$this->CI->lang->line('city')." :</b> ".$city;
        $custmer_details .= "<br><b>".$this->CI->lang->line('state')." :</b> ".$state;

        $this->writeHTMLCell($w, $h, $x ='6', $y='90', $custmer_details, 1, 0, 1, true, 'J', true);
        return $this;
    }

    public function _get_bank_details()
    {
    	$store = $this->store;
        $w = 100;
        $h = 40;
        $invoice_details = "";
        $invoice_details = '<span style="color:rgb(65, 59, 212);font-style:italic;">'.$this->CI->lang->line("bank_details").'</span><br>';
        $invoice_details .= nl2br($store->bank_details);

        $this->writeHTMLCell($w, $h, $x ='104', $y='', $invoice_details, 1, 1, 1, true, 'J', true);
        return $this;
    }

   
	public function show_pdf()
	{
		$this->_main_body();
	}

	

	public function _main_body()
	{	
		$sales 		= $this->sales;//array()
		$store 		= $this->store;//array()
		$customer 	= $this->customer;//array()
			
		$this->_invoice_name = "Sales Invoice";

		//$this->_QRCODE = $sales->sales_code;

		// set font
		$this->setFont($this->get_font_name(), 'B', 20);

		// add a page
		$this->AddPage();

		// Cusomer Details
		$this->_get_customer_details(); 

		// Cusomer Details
		$this->_get_invoice_details();

		// Shipping Details
		$this->_get_shipping_address(); 

		// Bank Details
		$this->_get_bank_details();

		//Search Coupon Details
		$coupon_code = $coupon_type = '';
	    $coupon_value=0;
	    if(!empty($sales->coupon_id)){
	      $coupon_details =get_customer_coupon_details($sales->coupon_id);
	      $coupon_code =$coupon_details->code;
	      $coupon_value =$coupon_details->value;
	      $coupon_type =$coupon_details->type;
	    } 
		$this->setFont($this->get_font_name(), '', 8);

		// set cell padding
		$this->setCellPaddings(1, 1, 1, 1);

		// set cell margins
		//$this->setCellMargins(1, 1, 1, 1);

		// set color for background
		$this->setFillColor(255, 255, 255);

		$this->Ln(0);

		
		$show_tax = true;


		$this->setFont($this->get_font_name(), '', 8);

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

		$tbl = '
		<style type="text/css">
			.main-table {
			    border: 1px solid #2c3e50;
			    border-collapse: collapse;
			}
			table, td, th {
			    border-collapse: collapse;
			    border: 0.5px solid #34495e;
			}
			table + table, table + table tr:first-child th, table + table tr:first-child td {
			    border-top: 0;
			}
			.text-right{
				text-align: right;
			}
			.text-center{
				text-align: center;
			}
			.text-bold{
				font-weight: bold;
			}
			.header-row {
			    background-color: #2c3e50;
			    color: #ffffff;
			}
			.alt-row {
			    background-color: #f8f9fa;
			}
			.total-row {
			    background-color: #ecf0f1;
			    font-weight: bold;
			}
			.grand-total-row {
			    background-color: #2c3e50;
			    color: #ffffff;
			    font-weight: bold;
			}
		</style>
		<table class="main-table">';

			$widthArray = array(
				'sl_no' 		=> '7',
				'description' 	=> '25',
				'hsn' 			=> '8',
				'unit_cost' 	=> '10',
				'qty' 			=> '6',
				'unit' 			=> '6',
				'tax' 			=> '8',
				'tax_amt'		=> '10',
				'disc' 			=> '10',
				'amount' 		=> '10',

			);

			$tot_col = count($widthArray);

			$equalize =0;

			if(!$show_tax){
				$tot_col -=2;
				$equalize = 20/$tot_col;
			}

			//Sum the value
			$sumOfWidth = 0;

			$colW =array();
			foreach($widthArray as $key => $val){

				//if tax hidden
				if(!$show_tax){
					$makeZero = array('tax','tax_amt');
					$val = (in_array($key,$makeZero)) ? 0 : $val+$equalize;
				}
				else{
					//Add percentage value
					$val +=$equalize;
				}
				
				//Update value
				$colWidthSize[$key] = $val;

				//New Array => Reasssign % symbol
				$colW[$key] = $val.'%';

				//Sum of value
				$sumOfWidth+=$val;
			}

			
			
		    $tbl .='<thead>
		        <tr style="background-color: #2c3e50; color:#ffffff;" class="text-bold">
			        <th colspan="1" style="width: '.$colW['sl_no'].'; padding:5px; text-align:center;">#</th>
			        <th colspan="1" style="width: '.$colW['description'].'; padding:5px;">'.$this->CI->lang->line("description").'</th>
			        <th colspan="1" style="width: '.$colW['hsn'].'; padding:5px; text-align:center;">'.$this->CI->lang->line("hsn").'</th>
			        <th colspan="1" style="width: '.$colW['unit_cost'].'; padding:5px; text-align:right;">Price</th>
			        <th colspan="1" style="width: '.$colW['qty'].'; padding:5px; text-align:center;">Qty</th>
			        <th colspan="1" style="width: '.$colW['unit'].'; padding:5px; text-align:center;">Unit</th>';
			        if($show_tax){
			        	$tbl .='<th colspan="1" style="width: '.$colW['tax'].'; padding:5px; text-align:center;">Tax%</th>';
			        	$tbl .='<th colspan="1" style="width: '.$colW['tax_amt'].'; padding:5px; text-align:right;">Tax Amt</th>';
			    	}
			        $tbl .='<th colspan="1" style="width: '.$colW['disc'].'; padding:5px; text-align:right;">Disc</th>
			        <th colspan="1" style="width: '.$colW['amount'].'; padding:5px; text-align:right;">Total</th>
		        </tr>
		    </thead>
		    <tbody>';
		        
		      $i=1;
              $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;
              
              $tot_price_per_unit=0;
              $sum_of_tot_price=0;

              $this->CI->db->select(" a.description, c.item_name, a.sales_qty, a.tax_type,
                                  a.price_per_unit, b.tax, b.tax_name, a.tax_amt,
                                  a.discount_input, a.discount_amt, a.unit_total_cost,
                                  a.total_cost, d.unit_name as default_unit,
                                  c.sku, c.hsn, a.batch_number, a.manufacturing_date, a.expiry_date, c.batch_tracking_enabled,
                                  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
                              ");
              $this->CI->db->where("a.sales_id",$this->sales_id);
              $this->CI->db->from("db_salesitems a");
              $this->CI->db->join("db_tax b","b.id=a.tax_id","left");
              $this->CI->db->join("db_items c","c.id=a.item_id","left");
              $this->CI->db->join("db_units d","d.id = c.unit_id","left");
              $this->CI->db->join("db_units main_unit","main_unit.id = c.main_unit_id","left");
              $this->CI->db->join("db_units alt_unit","alt_unit.id = c.alternate_unit_id","left");
              //$this->CI->db->limit("10");
              
              $q2=$this->CI->db->get();

		      
		      $row_count = 0;
		        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."";
                  $before_tax=$res2->unit_total_cost;// * $res2->sales_qty;
                  $tot_cost_before_tax=$before_tax * $res2->sales_qty;

                  $price_per_unit = $res2->price_per_unit;
                  if($res2->tax_type=='Inclusive'){
                    $price_per_unit -= ($res2->tax_amt/$res2->sales_qty);
                  }

                  $tot_price = $price_per_unit * $res2->sales_qty;

                  // Determine correct unit name based on unit_type (multi-unit support)
                  $display_unit = $res2->default_unit; // Default to item's 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;
                      }
                  }

                  // Alternating row colors
                  $row_bg = ($row_count % 2 == 1) ? 'background-color:#f8f9fa;' : '';
                  $row_count++;

                 $tbl .='<tr style="'.$row_bg.'" nobr="true">';
				      $tbl .='<td colspan="1" style="width: '.$colW['sl_no'].'; text-align:center; padding:4px;">'.$i++.'</td>';
				      $tbl .='<td colspan="1" style="width: '.$colW['description'].'; padding:4px;" >';
				      $tbl .= '<b>'.$res2->item_name.'</b>';
				      $tbl .= (!empty($res2->description)) ? "<br><i style='color:#666; font-size:7px;'>[".nl2br($res2->description)."]</i>" : '';
				      // Display batch details if batch is enabled and batch information exists
				      if($res2->batch_tracking_enabled == 1 && !empty($res2->batch_number)) {
				          $tbl .= "<br><span style='font-size:7px; color:#555;'><b>Batch:</b> ".$res2->batch_number;
				          if(!empty($res2->expiry_date) && $res2->expiry_date != '0000-00-00') {
				              $formatted_exp_date = 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;
				              $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';
				              }
				              $tbl .= " | <b>Exp:</b> ".$formatted_exp_date." <span style='color:".$days_color.";'>(" . $days_label . ")</span>";
				          }
				          $tbl .= "</span>";
				      }
				      $tbl .= '</td>';
				      $tbl .='<td colspan="1" style="width: '.$colW['hsn'].'; text-align:center; padding:4px;">'.$res2->hsn.'</td>';
				      $tbl .='<td colspan="1" class="text-right" style="width: '.$colW['unit_cost'].'; padding:4px;">'.store_number_format($price_per_unit).'</td>';
				      $tbl .='<td colspan="1" style="width: '.$colW['qty'].'; text-align:center; padding:4px;">'.format_qty($res2->sales_qty).'</td>';
				      $tbl .='<td colspan="1" style="width: '.$colW['unit'].'; text-align:center; padding:4px;">'.$display_unit.'</td>';
				      if($show_tax){
					      $tbl .='<td colspan="1" style="width: '.$colW['tax'].'; text-align:center; padding:4px;">'.$res2->tax_name.'</td>';
					      $tbl .='<td colspan="1" class="text-right" style="width: '.$colW['tax_amt'].'; padding:4px;">'.store_number_format($res2->tax_amt).'</td>';
					  }
				      $tbl .='<td colspan="1" class="text-right" style="width: '.$colW['disc'].'; padding:4px;">'.store_number_format($discount_amt).'</td>';
				      $tbl .='<td colspan="1" class="text-right" style="width: '.$colW['amount'].'; padding:4px; font-weight:bold;">'.store_number_format($res2->total_cost).'</td>';
		          $tbl .='</tr>';

                  $tot_qty +=$res2->sales_qty;
                  $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 +=$res2->total_cost;
                  $tot_price_per_unit +=$price_per_unit;
                  $sum_of_tot_price +=$tot_price;

              }

              // Recalculate grand_total from items for accuracy
              // This ensures correct totals even if database has corrupt data
              if ($tot_total_cost > 0) {
                  $calc_grand_total = $tot_total_cost + floatval($sales->other_charges_amt) - floatval($sales->tot_discount_to_all_amt) - floatval($sales->coupon_amt) + floatval($sales->round_off);
                  $sales->grand_total = $calc_grand_total;
              }

		    $tbl .='</tbody>
		    
		</table>
		';

		$tbl .='<table>
		            <tbody>';

		            	$tbl .='<tr nobr="true" class="text-bold" style="background-color:#ecf0f1;">';

		                	$tbl .='<td colspan="3" style="width:'.($colWidthSize['sl_no']+$colWidthSize['description']+$colWidthSize['hsn']).'%; padding:5px; font-weight:bold;">';
		                	$tbl .='<b>'.$this->CI->lang->line("total").'</b>';
		                	$tbl .='</td>';

		                	$tbl .='<td colspan="1" class="text-right" style="width:'.($colWidthSize['unit_cost']).'%; padding:5px;">';
		                	$tbl .=store_number_format($tot_price_per_unit);
		                	$tbl .='</td>';

		                	$tbl .='<td colspan="1" style="width:'.($colWidthSize['qty']).'%; text-align:center; padding:5px;">';
		                	$tbl .='<b>'.format_qty($tot_qty).'</b>';
		                	$tbl .='</td>';

		                	$tbl .='<td colspan="1" class="text-right" style="width:'.($colWidthSize['unit']).'%; padding:5px;">';
			                $tbl .='';
			                $tbl .='</td>';

		                	if($show_tax){
			                	$tbl .='<td colspan="1" class="text-right" style="width:'.($colWidthSize['tax']).'%; padding:5px;">';
			                	$tbl .='';
			                	$tbl .='</td>';

			                	$tbl .='<td colspan="1" class="text-right" style="width:'.($colWidthSize['tax_amt']).'%; padding:5px;">';
			                	$tbl .='<b>'.store_number_format($tot_tax_amt).'</b>';
			                	$tbl .='</td>';
			                }

			                $tbl .='<td colspan="1" class="text-right" style="width:'.($colWidthSize['disc']).'%; padding:5px;">';
		                	$tbl .=store_number_format($tot_discount_amt);
		                	$tbl .='</td>';

		                	$tbl .='<td colspan="1" class="text-right" style="width:'.($colWidthSize['amount']).'%; padding:5px;">';
		                	$tbl .='<b>'.$currency_symbol.' '.store_number_format($tot_total_cost).'</b>';
		                	$tbl .='</td>';


		                $tbl .='</tr>';

		                //Sub Total
		                $tbl .='<tr nobr="true">
		                	<td colspan="'.((!$show_tax)?4:6).'" style="width:'.($sumOfWidth-$colWidthSize['amount']-$colWidthSize['disc']-$colWidthSize['tax_amt']-(($show_tax)?0:$colWidthSize['qty'])).'%">';
		                	$tbl .='';
		                	$tbl .='</td>
		                	<td colspan="2" class="text-right" style="width:'.($colWidthSize['disc']+$colWidthSize['tax_amt']+(($show_tax)?0:$colWidthSize['qty'])).'%">';
		                	$tbl .=$this->CI->lang->line("subtotal");
		                	$tbl .='</td>
		                	<td colspan="1" class="text-right" style="width:'.($colWidthSize['amount']).'%">';
		                	$tbl .=store_number_format($tot_total_cost);
		                	$tbl .='</td>';
		                $tbl .='</tr>';

		                //Other charges
		                $tbl .='<tr nobr="true">
		                	<td colspan="'.((!$show_tax)?4:6).'" style="width:'.($sumOfWidth-$colWidthSize['amount']-$colWidthSize['disc']-$colWidthSize['tax_amt']-(($show_tax)?0:$colWidthSize['qty'])).'%">';
		                	$tbl .='';
		                	$tbl .='</td>
		                	<td colspan="2" class="text-right" style="width:'.($colWidthSize['disc']+$colWidthSize['tax_amt']+(($show_tax)?0:$colWidthSize['qty'])).'%">';
		                	$tbl .=$this->CI->lang->line("other_charges");
		                	$tbl .='</td>
		                	<td colspan="1" class="text-right" style="width:'.($colWidthSize['amount']).'%">';
		                	$tbl .=store_number_format($sales->other_charges_amt);
		                	$tbl .='</td>';
		                $tbl .='</tr>';

		                //Coupon
		                if(!empty($coupon_code)){
			                $tbl .='<tr nobr="true">
			                	<td colspan="'.((!$show_tax)?4:6).'" style="width:'.($sumOfWidth-$colWidthSize['amount']-$colWidthSize['disc']-$colWidthSize['tax_amt']-(($show_tax)?0:$colWidthSize['qty'])).'%">';
			                	$tbl .="<b>".$this->CI->lang->line("couponCode")."</b>: ".getTruncatedCCNumber($coupon_code);
			                	$tbl .='</td>
			                	<td colspan="2" class="text-right" style="width:'.($colWidthSize['disc']+$colWidthSize['tax_amt']+(($show_tax)?0:$colWidthSize['qty'])).'%">';
			                	$tbl .=$this->CI->lang->line("couponDiscount").":";
			                	$tbl .=($coupon_type=='Percentage') ? $coupon_value .'%' : '[Fixed]' ;
			                	$tbl .='</td>
			                	<td colspan="1" class="text-right" style="width:'.($colWidthSize['amount']).'%">';
			                	$tbl .=store_number_format($sales->coupon_amt);
			                	$tbl .='</td>';
			                $tbl .='</tr>';
		            	}

		            	//Discount on All
		            	$tbl .='<tr nobr="true">
		                	<td colspan="'.((!$show_tax)?4:6).'" style="width:'.($sumOfWidth-$colWidthSize['amount']-$colWidthSize['disc']-$colWidthSize['tax_amt']-(($show_tax)?0:$colWidthSize['qty'])).'%">';
		                	$tbl .='';
		                	$tbl .='</td>
		                	<td colspan="2" class="text-right" style="width:'.($colWidthSize['disc']+$colWidthSize['tax_amt']+(($show_tax)?0:$colWidthSize['qty'])).'%">';
		                	$tbl .=$this->CI->lang->line("discount_on_all");
		                	$tbl .="[";
		                	$tbl .=store_number_format($sales->discount_to_all_input)." ".(($sales->discount_to_all_type=='percentage') ? '%' : 'Fixed');
		                	$tbl .="]";
		                	$tbl .='</td>
		                	<td colspan="1" class="text-right" style="width:'.($colWidthSize['amount']).'%">';
		                	$tbl .=store_number_format($sales->tot_discount_to_all_amt);
		                	$tbl .='</td>';
		                $tbl .='</tr>';

		                //Round Off
		                $tbl .='<tr nobr="true">
		                	<td colspan="'.((!$show_tax)?4:6).'" style="width:'.($sumOfWidth-$colWidthSize['amount']-$colWidthSize['disc']-$colWidthSize['tax_amt']-(($show_tax)?0:$colWidthSize['qty'])).'%">';
		                	$tbl .='';
		                	$tbl .='</td>
		                	<td colspan="2" class="text-right" style="width:'.($colWidthSize['disc']+$colWidthSize['tax_amt']+(($show_tax)?0:$colWidthSize['qty'])).'%">';
		                	$tbl .=$this->CI->lang->line("round_off");
		                	$tbl .='</td>
		                	<td colspan="1" class="text-right" style="width:'.($colWidthSize['amount']).'%">';
		                	$tbl .=store_number_format($sales->round_off);
		                	$tbl .='</td>';
		                $tbl .='</tr>';

		                // TAX SUMMARY - Group taxes by rate
		                if($show_tax) {
		                    $tax_summary_q = $this->CI->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 = '".$this->sales_id."'
		                        GROUP BY b.tax, b.tax_name
		                        ORDER BY b.tax DESC
		                    ");

		                    if($tax_summary_q->num_rows() > 0) {
		                        $tbl .='<tr nobr="true">
		                            <td colspan="'.((!$show_tax)?7:9).'" style="width:'.$sumOfWidth.'%; padding:8px 5px 5px 5px; border-bottom:none;">
		                            <b style="color:#2c3e50; font-size:10px;"><i class="fa fa-calculator"></i> '.$this->CI->lang->line("tax_summary").'</b>
		                            </td>
		                        </tr>';

		                        $tbl .='<tr nobr="true">
		                            <td colspan="'.((!$show_tax)?7:9).'" style="width:'.$sumOfWidth.'%; padding:0 5px 8px 5px;">
		                            <table border="1" cellpadding="4" style="width:60%; border-collapse:collapse; font-size:8px; border:1px solid #bdc3c7;">
		                                <thead>
		                                    <tr style="background-color:#34495e; color:#ffffff;">
		                                        <th style="width:25%; text-align:center; padding:4px;">Tax Rate</th>
		                                        <th style="width:25%; text-align:right; padding:4px;">Taxable ('.$currency_symbol.')</th>
		                                        <th style="width:25%; text-align:right; padding:4px;">Tax ('.$currency_symbol.')</th>
		                                        <th style="width:25%; text-align:right; padding:4px;">Total ('.$currency_symbol.')</th>
		                                    </tr>
		                                </thead>
		                                <tbody>';

		                        $sum_taxable = 0; $sum_tax = 0; $sum_total = 0;
		                        $row_alt = false;
		                        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;
		                            $row_bg = $row_alt ? 'background-color:#f8f9fa;' : '';
		                            $row_alt = !$row_alt;

		                            $tbl .='<tr style="'.$row_bg.'">
		                                <td style="text-align:center; padding:3px;">'.$tx_label.'</td>
		                                <td style="text-align:right; padding:3px;">'.store_number_format($tx->taxable_amount).'</td>
		                                <td style="text-align:right; padding:3px;">'.store_number_format($tx->tax_amount).'</td>
		                                <td style="text-align:right; padding:3px;">'.store_number_format($tx->total_amount).'</td>
		                            </tr>';
		                        }

		                        $tbl .='<tr style="background-color:#ecf0f1; font-weight:bold;">
		                                <td style="text-align:center; padding:4px;">Total</td>
		                                <td style="text-align:right; padding:4px;">'.store_number_format($sum_taxable).'</td>
		                                <td style="text-align:right; padding:4px;">'.store_number_format($sum_tax).'</td>
		                                <td style="text-align:right; padding:4px;">'.store_number_format($sum_total).'</td>
		                            </tr>';

		                        $tbl .='</tbody>
		                            </table>
		                            </td>
		                        </tr>';
		                    }
		                }
		                // END TAX SUMMARY

		                //Grand Total - Highlighted Row
		                $tbl .='<tr nobr="true" style="background-color:#2c3e50; color:#ffffff;">
		                	<td colspan="'.((!$show_tax)?4:6).'" style="width:'.($sumOfWidth-$colWidthSize['amount']-$colWidthSize['disc']-$colWidthSize['tax_amt']-(($show_tax)?0:$colWidthSize['qty'])).'%; padding:8px; font-size:9px;">';
		                	$tbl .="<b>".$this->CI->lang->line("amount_in_words").":</b><br>".no_to_words($sales->grand_total)." Only";
		                	$tbl .='</td>
		                	<td colspan="2" class="text-right" style="width:'.($colWidthSize['disc']+$colWidthSize['tax_amt']-(($show_tax)?0:$colWidthSize['qty'])).'%; padding:8px; font-size:11px;">';
		                	$tbl .="<b>".$this->CI->lang->line("grand_total")."</b>";
		                	$tbl .='</td>
		                	<td colspan="1" class="text-right" style="width:'.($colWidthSize['amount']).'%; padding:8px; font-size:12px;">';
		                	$tbl .="<b>'.$currency_symbol.' ".store_number_format($sales->grand_total)."</b>";
		                	$tbl .='</td>';
		                $tbl .='</tr>';

		                if($store->previous_balance_bit==1){
		                	$previous_due=($customer->sales_due)-($sales->grand_total-$sales->paid_amount);
						    $previous_due = ($previous_due>0) ? $previous_due : 0;
						    $total_due=$customer->sales_due;

				            $tbl .='<tr nobr="true">
			                	<td colspan="'.((!$show_tax)?4:6).'" style="width:'.($sumOfWidth-$colWidthSize['amount']-$colWidthSize['disc']-$colWidthSize['tax_amt']).'%">';
			                	$tbl .='';
			                	$tbl .='</td>
			                	<td colspan="2" class="text-right" style="width:'.($colWidthSize['disc']+$colWidthSize['tax_amt']).'%">';
			                	$tbl .=$this->CI->lang->line("previous_balance");
			                	$tbl .='</td>
			                	<td colspan="1" class="text-right" style="width:'.($colWidthSize['amount']).'%">';
			                	$tbl .=store_number_format($previous_due);
			                	$tbl .='</td>';
			                $tbl .='</tr>';

			                $tbl .='<tr nobr="true">
			                	<td colspan="'.((!$show_tax)?4:6).'" style="width:'.($sumOfWidth-$colWidthSize['amount']-$colWidthSize['disc']-$colWidthSize['tax_amt']).'%">';
			                	$tbl .='';
			                	$tbl .='</td>
			                	<td colspan="2" class="text-right" style="width:'.($colWidthSize['disc']+$colWidthSize['tax_amt']).'%">';
			                	$tbl .=$this->CI->lang->line("total_due");
			                	$tbl .='</td>
			                	<td colspan="1" class="text-right" style="width:'.($colWidthSize['amount']).'%">';
			                	$tbl .=store_number_format($total_due);
			                	$tbl .='</td>';
			                $tbl .='</tr>';
		            	}
		            	$tbl .='<tr nobr="true">
		                	<td colspan="'.((!$show_tax)?7:9).'" style="width:'.($sumOfWidth).'%; height:30px;">';
		                	$tbl .="<b>".$this->CI->lang->line("note")."</b>: ".nl2br($sales->sales_note);
		                	$tbl .='</td>';
		                $tbl .='</tr>';


		            $tbl .='</tbody>
		        </table>
		       
		        ';

		$tbl .='<table nobr="true">
		            <tbody>
		                <tr nobr="true">
		                    <td colspan="12"><div style="font-size:10px;"><span style="color:rgb(65, 59, 212);font-style:italic;">'.$this->CI->lang->line("termsAndConditions").':</span><br>';
		                        	$tbl .=nl2br(html_entity_decode($sales->invoice_terms));
		                    		$tbl .='</div>
		                    		</td>
		                    <td colspan="6" style="vertical-align:bottom;text-align:center;min-height:60px;height:60px;">
		                    	<div style="font-size:10px;">
			                    	<span style="color:rgb(65, 59, 212);font-style:italic;vertical-align:bottom;">
			                    	'.$this->CI->lang->line("authorised_signatory").'
			                    	:</span>
		                    	</div>';
		                    	if(!empty($this->get_signature_image_path())){
			                    	$tbl .='<div>
			                    		<img style="height:60px;" src="'.$this->get_signature_image_path().'"/>
			                    	</div>';
		                    	}

		                    $tbl .='</td>
		                </tr>
		                <tr nobr="true">
		                    <td colspan="18" class="text-center">';
		                        	$tbl .=nl2br($store->sales_invoice_footer_text);
		                    		$tbl .='
		                    </td>
		                </tr>
		            </tbody>
		        </table>
		       
		        ';

		      //  echo $tbl;exit;
		$this->writeHTMLCell('', '', $x ='', $y='', $tbl, 0, 1, 1, true, 'J', true);

		$this->Output('invoice_100.pdf', 'I');
	}

}