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

<?php
    $statement = $pdo->prepare("SELECT * FROM tbl_purchases e where e.id=?");
    $statement->execute(array($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['paid'];
            $discount_amount = $data['discount_amount'];
        }
    }
    
    
$statements = $pdo->prepare("SELECT COALESCE(SUM(amount),0) as paid_amount FROM tbl_payments e where e.purchase_id=? and e.accounts=?");
$statements->execute(array($id, 2));
$emp_datas = $statements->fetchAll(PDO::FETCH_ASSOC);
$totalDatas = $statements->rowCount();

$purchase_paid_amount = $emp_datas[0]['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">Add 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 action="" enctype="multipart/form-data" id="add_payment_form" method="post" accept-charset="utf-8">
         
           
      <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"><?=$grand_total?></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>
                <table style="width: 100%; margin-top: 25px;">
                    <tr>
                        <th style="text-align: left;"><span class="label label-warning" style="padding: 5px;font-size: 18px;"><i class="fa fa-inr"></i> Paid Amount: <span id="paid_total_amount"><?=number_format($purchase_paid_amount,2)?></span></span></th>
                        <th></th>
                    </tr>
                </table>
            </div>
            
            
            
            <div class="col-md-6" style="padding-top: 25px;">
                <label>Amount</label>
                <input type="text" name="paid_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="<?=date("Y-m-d")?>"  class="form-control" id="payment_date" />
            </div>
            
            <!--Hidden Values Starts Here-->
            <input type="hidden" name="purchase_id" id="purchase_id" value="<?=$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="<?=$purchase_paid_amount?>" class="form-control"/>
            <input type="hidden" name="new_balance" id="new_balance" value="" class="form-control"/>
            <!--Hidden Values Ends Here-->

            
            
            <div class="col-md-6" style="padding-top: 8px;">
                <label>Payment Type</label>
                <select name="payment_type" class="form-control select2" id="payment_type" onchange="PaymentType()" style="width: 100%;">
                    <?php 
                    $statement = $pdo->prepare("SELECT * FROM `tbl_payment_type` WHERE status=1 and purchase=1");
                    $statement->execute();
                    $location_result = $statement->fetchAll(PDO::FETCH_ASSOC); 
                        foreach ($location_result as $result) { ?>
                            <option value="<?=$result['id']?>"><?=$result['name']?></option>
                    <?php } ?>
                </select>
            </div>
            
            <div id="append_sections">
                
            </div>
            
            <div class="col-md-12" style="padding-top: 8px;">
                <label>Reference</label>
                <input type="text" name="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"></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(){
        paidAmount();
    });
    
    $('#paid_amount').keyup(function(){
        paidAmount();
    });
    /* $('#discount_amount').keyup(function(){
        paidAmount();
    });*/
    
    
    function paidAmount(){
        
        var grand_total = $('#grand_total').val();
        var db_paid_amount = $('#db_paid').val();
        var discount_amount =  0;
        remaining_amount = parseFloat(grand_total)-parseFloat(db_paid_amount);
        
        
        console.log("Grand Total: "+grand_total);
        console.log("Paid Amount: "+db_paid_amount);
        console.log("Balance Amount: "+remaining_amount);
        
        
            var paid=$('#paid_amount').val() || 0;
            paidThisPayment = parseFloat(paid)+parseFloat(discount_amount);
            calculate=remaining_amount-paidThisPayment;
            
            $("#balance_amount").text(calculate.toFixed(2));
            //$("#balance_amount").text(balance_format);
            $("#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(){
    $('#add_payment_form').on('submit', function(e){
        e.preventDefault();
        var balance = $('#balance_amount').text();
        $("#submit").prop('disabled', true);
        console.log("Submitted");
                var formData = new FormData(this);
                formData.append('type', 'add_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);
                                }
                            }
                        });
                

    });
});
function PaymentType(){
    var payment_type = $("#payment_type").val();
    
    if(payment_type==9){
        var row = `<div class="col-md-3" style="padding-top: 8px;">
                        <label>Weight</label>
                        <input type="text" name="weight"  oninput="Calc()" placeholder="Weight" class="form-control"  id="weight" />
                    </div>
                    <div class="col-md-3" style="padding-top: 8px;">
                        <label>Rate</label>
                        <input type="text" name="rate" oninput="Calc()"  placeholder="Rate" class="form-control"  id="rate" />
                    </div>`;
                    
        $("#append_sections").append(row);
    }
}

function Calc(){
    var weight = $("#weight").val() || 0;
    var rate = $("#rate").val() || 0;
    cal = parseFloat(weight)*parseFloat(rate);
    $("#paid_amount").val(cal.toFixed(2));
    
    paidAmount();
}
</script>