<?php
session_start();
include "../config/config.php";
$id = $_GET['id'];
?>
<style>
    thead{
        background: #dbcbcb;
    }
    table.table tbody tr:hover td {
        background: none !important;
    }
</style>

<?php
    $statement = $pdo->prepare("SELECT tbl_sales.*,
                                (SELECT SUM(amount) FROM tbl_payments WHERE tbl_payments.sale_id=tbl_sales.id and accounts=1) as sales_paid_amount,
                                (SELECT COUNT(id) FROM tbl_sale_items WHERE tbl_sale_items.sale_id=tbl_sales.id) as product_total_items,
                                tbl_customers.customer_name,tbl_customers.mobile_no 
                                FROM tbl_sales 
                                    LEFT JOIN tbl_customers ON tbl_sales.customer_id=tbl_customers.id 
                                    where tbl_sales.id=?");
    $statement->execute(array($id));
    $emp_data = $statement->fetchAll(PDO::FETCH_ASSOC);
    $totalData = $statement->rowCount();
    if($totalData==1){
        foreach($emp_data as $data){
            
            $total_paid_amount = $data['sales_paid_amount'];
            $grand_total = $data['grand_total'];
            $paid_amount = $data['paid'];
            $balance_amount = $data['balance'];
            
            $current_balance = $grand_total-$total_paid_amount;
            
            if($data["gst_percentage"]!=0){
                if($data["tax_type"]==1){
    		 	    $tax_type = "Exclusive";
    		 	}else if($data["tax_type"]==2){
    		 	    $tax_type ="Inclusive";
    		 	}else{
    		 	    $tax_type="Null";
    		 	}
    		 	
    		 	if($data["gst_type"]==1){
    		 	   $gst_type="GST"; 
    		 	}else if($data["gst_type"]==2){
    		 	   $gst_type="IGST";  
    		 	}else{
    		 	    $gst_type="Null";
    		 	}
            }else{
                $tax_type="";
                $gst_type=""; 
            }
            
		 	
		 	
		 	
                    	if($total_paid_amount==$grand_total){
                            $nestedData ="<span class='btn btn-success btn-xs'>Payment Completed</span>";
                        }else if($total_paid_amount!=0){
                            $nestedData ="<span class='btn btn-warning btn-xs'>Payment Due</span>";
                        }else if($total_paid_amount==0){
                            $nestedData ="<span class='btn btn-danger btn-xs'>Payment Pending</span>";
                        }else{
                            $nestedData ="<span class='btn btn-danger btn-xs'>NULL</span>";
                        }
        	
        }
    }
?>

<div class="modal-dialog" role="document" style="width: 900px;">
    <div class="modal-content" id="printableArea">
      <div class="modal-header">
            <h4 class="modal-title" id="exampleModalLabel">
                Sales Details
                <a class="btn btn-primary" href='modal/payment-add-modal.php?id=<?=$id?>' id='<?=$id?>' data-toggle='ajax-modal' title='Payment' style="margin-left: 50px;padding: 3px 10px 3px 10px;"><i class="fa fa-inr"></i>  Add Payments</a>
                <span class="btn btn-success" style="margin-left: 100px;padding: 3px 10px 3px 10px;">Total Amount: <b><?=number_format($grand_total,2)?></b> </span>
                <span class="btn btn-danger" style="padding: 3px 10px 3px 10px;">Balance Amount: <b><?=number_format($current_balance,2)?></b> </span>
            </h4>
            
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true"><i class="fa fa-times" style="margin-top: -23px; font-size: 28px;"></i></span>
            </button>
      </div>
      
           
           
      <div class="modal-body">
        <div class="row">
            
            
<div class="col-md-12" style="padding-top: 5px;">
 
<table class="table table-striped">
    <tr>
        <th style="width: 20%;">Invoice Date</th>
        <td style="width: 30%; background: none !important;"><?=date('d-m-Y', strtotime($data['date']))?></td>
        <th style="width: 20%;">Invoice No</th>
        <td style="width: 30%;"><?=$data['invoice_no']?></td>
    </tr>
    <tr>
        <th>Customer Name</th>
        <td style="vertical-align: top;"><?=$data['customer_name']?></td>
        <th>Mobile No</th>
        <td style="vertical-align: top;"><?=$data['mobile_no']?></td>
    </tr>
    <tr>
        <th>GST</th>
        <td><?=$data['gst_percentage']?> %</td>
        <th>Tax Type - GST Type</th>
        <td><?=$tax_type?> - <?=$gst_type?></td>
    </tr>
    <tr>
        <th>Product Items</th>
        <td><?=number_format($data['product_total_items'], 2)?></td>
        <th>Payment Status</th>
        <td><?=$nestedData?></td>
    </tr>
    
    <tr>
        <th>New Product Amount</th>
        <td><?=number_format($data['total_amount'], 2)?></td>
        <th>Old Product Amount</th>
        <td><?=number_format($data['old_product_amount'], 2)?></td>
    </tr>
    <tr>
        <th>GST Amount</th>
        <td><?=number_format($data['gst_amount'], 2)?></td>
        <th>Tax After Amount</th>
        <td><?=number_format($data['total_amount_after_tax'], 2)?></td>
    </tr>
    <tr>
        <th>Discount</th>
        <td><?=number_format($data['discount_amount'], 2)?></td>
        <th>Grand Total</th>
        <td><?=number_format($data['grand_total'], 2)?></td>
    </tr>
    
    
</table>

</div>

<form id="return_form_details">
<input type="hidden" name="ids" value="<?=$id?>">
<div class="col-md-6" style="padding-top: 5px;">
<select name="return_type" class="form-control">
    <option value="1">Sales Return</option>
</select>
</div> 


<div class="col-md-6" style="padding-top: 5px;">
    <input type="submit" class="btn btn-info btn-md" value="Submit">
</div>
</form> 
 
 
 
 
<div class="col-md-12" style="padding-top: 5px;"> 
 
 

<table class="table table-striped">
  <thead>
    <tr>
      <th scope="col">S.No</th>
      <th scope="col">Product Name</th>
      <th scope="col">C-S-T</th>
      <th scope="col">Per Stone Amount - Per Product Amount</th>
      <th scope="col">Total Amount</th>
    </tr>
  </thead>
  <tbody>
      
<?php
    $statement = $pdo->prepare("SELECT *,(SELECT name FROM tbl_products_name WHERE tbl_products_name.id=tbl_sale_items.product_id) as product_name FROM tbl_sale_items where sale_id=?");
    $statement->execute(array($id));
    $sales_items_data = $statement->fetchAll(PDO::FETCH_ASSOC);
    $totalData = $statement->rowCount();
    if($totalData>0){
        $i=1;
        foreach($sales_items_data as $data){
            
            $c_wt = $data['cross_weight'];
            $s_wt = $data['stone_weight'];
            $n_wt = $data['net_weight'];
            
            $per_product_amount = $data['per_gram_amount'];
            $per_stone_amount = $data['per_stone_amount'];
            
?>
            
            <tr>
              <td style="text-align: center;"><?=$i++?></td>
              <td style="text-align: center;"><?=$data['product_name']?></td>
              <td style="text-align: center;"><?=$c_wt?> - <?=$s_wt?> - <?=$n_wt?></td>
              <td style="text-align: center;"><?=$per_product_amount?> - <?=$per_stone_amount?></td>
              <td style="text-align: right; padding-right: 35px;"><?=number_format($data['total'],2)?></td>
            </tr>
            
<?php   }
    }else{
        echo "<tr><td colspan='6' style='text-align: center;'>No Sale Items Record Found</td></tr>";
    }
?>
  </tbody>
</table>


<table class="table table-striped">
  <thead>
    <tr>
      <th scope="col">S.No</th>
      <th scope="col">Product</th>
      <th scope="col">Purity</th>
      <th scope="col">Unit</th>
      <th scope="col">Type</th>
      <th scope="col">Weight</th>
      <th scope="col">Per Gram Price</th>
      <th scope="col">Total Amount</th>
    </tr>
  </thead>
  <tbody>
      
<?php
    $statement = $pdo->prepare("SELECT old_s.*, 
tbl_ids_products.name as product_ids_name,
tbl_ids_purity.name as purity_name,
tbl_units.name as unit_name
FROM `tbl_sale_old_items` old_s
LEFT JOIN tbl_ids_products ON tbl_ids_products.id=old_s.pro_ids
LEFT JOIN tbl_ids_purity ON tbl_ids_purity.id=old_s.purity
LEFT JOIN tbl_units ON tbl_units.id=old_s.unit
where sale_id=?");
    $statement->execute(array($id));
    $sales_items_data = $statement->fetchAll(PDO::FETCH_ASSOC);
    $totalData = $statement->rowCount();
    if($totalData>0){
        $i=1;
        foreach($sales_items_data as $data){
            
            if($data['type']==1){
                $old_product_type = "Own Product";
            }else if($data['type']==2){
                $old_product_type = "Other Product";
            }
            
     
            
?>
            
            <tr>
              <td style="text-align: center;"><?=$i++?></td>
              <td style="text-align: center;"><?=$data['product_ids_name']?></td>
              <td style="text-align: center;"><?=$data['purity_name']?></td>
              <td style="text-align: center;"><?=$data['unit_name']?></td>
              <td style="text-align: center;"><?=$old_product_type?></td>
              <td style="text-align: center;"><?=$data['weight']?></td>
              <td style="text-align: right; padding-right: 35px;"><?=number_format($data['price'],2)?></td>
              <td style="text-align: right; padding-right: 35px;"><?=number_format($data['total'],2)?></td>
            </tr>
            
<?php   }
    }else{
        echo "<tr><td colspan='8' style='text-align: center;'>No Old Sale Items Records Found</td></tr>";
    }
?>
  </tbody>
</table>







      
           
            
        </div>
      </div>
      
      
      <div class="modal-footer">
        <button type="button" class="btn btn-danger pull-left" data-dismiss="modal"><i class="fa fa-times"></i> Close</button>
        <!--<button type="button" class="btn btn-success pull-right" onclick="printDiv('printableArea')"><i class="bi bi-printer-fill"></i> Print</button>-->
      </div>

    </div>
</div>
<script>
    $(document).ready(function(){
        var grand_total = $('#total_amount').text();
        var db_paid_amount = $('#db_paid').val();
        remaining_amount = grand_total-db_paid_amount;
        
        console.log("Grand Total: "+grand_total);
        console.log("Paid Amount: "+db_paid_amount);
        console.log("Balance Amount: "+remaining_amount);
        
        $("#balance_amount").text(remaining_amount.toFixed(2));
        
        $('#paid_amount').val(remaining_amount);
        
        
        
        $('#paid_amount').keyup(function(){
            var paid=Number($(this).val());
            calculate=remaining_amount-paid;
            $("#balance_amount").text(calculate.toFixed(2));
            $("#new_balance").val(calculate.toFixed(2));
            
            if($("#balance_amount").text() < 0){
                 $("#submit").prop("disabled", true);
            }else{
                $("#submit").prop("disabled", false);
            }
        });
    });
</script>
<script>

    function printDiv(divName) {
        var printContents = document.getElementById(divName);
        var originalContents = document.body.innerHTML;
        
        var htmlToPrint = '' +
        '<style type="text/css">' +
        'table th, table td, table thead, table tbody {' +
        'border:1px solid #000 !important;' +
        'padding:0.5em;' +
        '}' +
        '</style>';
        
        htmlToPrint += printContents.outerHTML;
        
        document.body.innerHTML = printContents.outerHTML;
        
        window.print();
        
        document.body.innerHTML = originalContents;
    }
    
</script>

<script>
$(document).ready(function(){
    $('#return_form_details').on('submit', function(e){
        e.preventDefault();
        console.log("Submitted");
                var formData = new FormData(this);
                formData.append('type', 'sales_return');
                            $.ajax({
                            url: 'apis/return.php',
                            type: 'post',
                            dataType: 'json',
                            data: formData,
                            cache: false,
                            contentType: false,
                            processData: false,
                            enctype: 'multipart/form-data',
                            success: function (response) {
                                if(response['status']==200){
                                     alert(response['message']);
                                     location.reload();
                                     
                                }else{
                                    alert(response['message']);
                                }
                            }
                        });
                

    });
});
</script>