<?php
ob_start();
session_start();
include "../config/config.php";
$id=$_GET['id'];
?>



<?php
    $statement = $pdo->prepare("SELECT * FROM tbl_payments p where p.id=".$id);
    $statement->execute();
    $emp_data = $statement->fetchAll(PDO::FETCH_ASSOC);
    $totalData = $statement->rowCount();
    if($totalData==1){
        foreach($emp_data as $data){
            
            $purchase_id = $data['purchase_id'];
            $sales_id = $data['sale_id'];
            $payment_date = $data['date'];
            $payment_amount = $data['amount'];
            $payment_paid_by = $data['payment_type'];
            $reference = $data['reference_no'];
            $notes = $data['notes'];
        }
    }
?>

<?php
    $statement = $pdo->prepare("SELECT *,
    (SELECT COALESCE(SUM(amount),0) FROM tbl_payments WHERE tbl_payments.purchase_id=e.id and accounts=2) as purchase_paid_amount
    FROM tbl_purchases e where e.id=?");
    $statement->execute(array($purchase_id));
    $emp_data = $statement->fetchAll(PDO::FETCH_ASSOC);
    $totalData = $statement->rowCount();
    if($totalData==1){
        foreach($emp_data as $data){
            $grand_total = $data['grand_total'];
            $paid_amount = $data['purchase_paid_amount'];
            $balance_amount = $grand_total-$paid_amount;
        }
    }
?>
<div class="modal-dialog" role="document" style="width: 565px;">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title" id="exampleModalLabel">Update Purchase Payment</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>
       <form  id="update_payment_form" >
           
           <input type="hidden" name="payment_id" id="payment_id" value="<?=$id?>" class="form-control" />
           <!--Hidden Values Starts Here-->
           <input type="hidden" name="purchase_id" id="purchase_id" value="<?=$purchase_id?>" class="form-control"/>
            <input type="hidden" name="grand_total" id="grand_total" value="<?=$grand_total?>" class="form-control"/>
            <input type="hidden" name="db_paid" id="db_paid" value="<?=$paid_amount?>" class="form-control"/>
            <input type="hidden" name="this_payment" id="this_payment" value="<?=$payment_amount?>" class="form-control"/>
            <input type="hidden" name="new_balance" id="new_balance" value="" class="form-control"/>
            <!--Hidden Values Ends Here-->
           
           
           
           
           
           
           
           
           
           
           
           
           
           
           
           
      <div class="modal-body">
        <div class="row">
            
            <div class="col-md-12" style="padding-top: 5px;">
                <table style="width: 100%;">
                    <tr>
                        <th style="text-align: left;"><span class="label label-success" style="padding: 5px;font-size: 18px;"><i class="fa fa-inr"></i> Total Amount: <span id="total_amount"><?=number_format($grand_total,2)?></span></span></th>
                        <th style="text-align: left;"><span class="label label-danger" style="padding: 5px;font-size: 18px;"><i class="fa fa-inr"></i> Remaining Amount: <span id="balance_amount">0.00</span></span></th>
                    </tr>
                </table>
            </div>
            
            
            
            <div class="col-md-6" style="padding-top: 25px;">
                <label>Amount</label>
                <input type="text" name="paid_amount" value="<?=$payment_amount?>" placeholder="Enter the Amount" class="form-control" required="required" id="paid_amount" />
            </div>
            <div class="col-md-6" style="padding-top: 25px;">
                <label>Payment Date</label>
                <input type="date" name="payment_date"  value="<?=$payment_date?>"  class="form-control" id="payment_date" />
            </div>
            
            
            
            
            <div class="col-md-6" style="padding-top: 8px;">
                <label>Payment Type</label>
                <select name="payment_type" class="form-control select2" id="payment_type" style="width: 100%;">
                    <?php 
                    $statement = $pdo->prepare("SELECT * FROM `tbl_payment_type` WHERE status=1");
                    $statement->execute();
                    $location_result = $statement->fetchAll(PDO::FETCH_ASSOC); 
                        foreach ($location_result as $result) { ?>
                            <option value="<?=$result['id']?>" <?php if($payment_paid_by==$result['id']){echo "selected";}?>><?=$result['name']?></option>
                    <?php } ?>
                </select>
            </div>
            
            
            
            <div class="col-md-6" style="padding-top: 8px;">
                <label>Reference</label>
                <input type="text" name="reference" value="<?=$reference?>" placeholder="Reference No" class="form-control"  id="reference" />
            </div>
            
            
            
            
            <div class="col-md-12" style="padding-top: 8px;">
                <label>Notes</label>
                <textarea name="notes" id="notes" placeholder="Notes" rows="4" class="form-control"><?=$notes?></textarea>
            </div>
            
        </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="submit" class="btn btn-success" id="submit"><i class="fa fa-save"></i> Save</button>
      </div>
       </form>  
    </div>
</div>
<script>
    $(document).ready(function(){
        
        
        var grand_total = $('#grand_total').val();
        var db_paid_amount = $('#db_paid').val();
        var payment_amount = $('#this_payment').val();
        
        b = db_paid_amount-payment_amount;
        
        remaining_amount = parseFloat(grand_total)-(parseFloat(payment_amount)+parseFloat(b));
        
        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').keyup(function(){
            
            
            var paid=Number($(this).val());
            bal = payment_amount;
            if(paid!=payment_amount){
                bal = payment_amount-paid;
            }
            
            calculate = parseFloat(remaining_amount)+parseFloat(bal);
            
            console.log("Keyup Paid: "+paid);
            console.log("Payment Amount: "+payment_amount);
            console.log("Calculate: "+calculate);
            
            
            $("#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>
$(document).ready(function(){
    console.log("Sale Update Payment Working");
    
    $('#update_payment_form').on('submit', function(e){
        console.log("Submitted");
                e.preventDefault();
                $("#submit").prop('disabled', true);
                var formData = new FormData(this);
                formData.append('type', 'update_purchase_payment');
                            $.ajax({
                            url: 'apis/payments.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']);
                                     $("#submit").prop('disabled', false);
                                     location.reload();
                                }else{
                                    alert(response['message']);
                                    $("#submit").prop('disabled', false);
                                }
                            }
                        });
                
    });     
            });
</script>