<?php  include "header.php"; ?>


<div class="content-wrapper">
    
<?php if($session_id==1 || $session_user_type==1 || $allPermissions['advance_voucher']['create']==1){ ?>
        <section class="content-header">
            <h1>Add Advance Voucher</h1>
            <ol class="breadcrumb">
                <li><a href="index.php"><i class="fa fa-dashboard"></i> Home</a></li>
                <li class="active">Add Advance Voucher</li>            
            </ol>
        </section>


        <div class="col-lg-12 alerts">
            <div id="custom-alerts" style="display:none;">
                <div class="alert alert-dismissable">
                    <div class="custom-msg"></div>
                </div>
            </div>
            
            <?php if ($error)  { ?>
            <div class="alert alert-danger alert-dismissable">
                <button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
                <h4><i class="icon fa fa-ban"></i> Error</h4>
                <?= $error; ?>
            </div>
            <?php $error=0;} if ($warning) { ?>
            <div class="alert alert-warning alert-dismissable">
                <button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
                <h4><i class="icon fa fa-warning"></i> Warning</h4>
                <?= $warning; ?>
            </div>
            <?php  $warning=0;} if ($message) { ?>
            <div class="alert alert-success alert-dismissable">
                <button aria-hidden="true" data-dismiss="alert" class="close" type="button">×</button>
                <h4>    <i class="icon fa fa-check"></i> Success</h4>
                <?= $message; ?>
            </div>
            <?php $message=0; } ?>
        </div>
        <div class="clearfix"></div>







<section class="content">
    

    <div class="row">
        <div class="col-xs-12">
            <div class="box box-primary" style="box-shadow: rgba(0, 0, 0, 0.16) 0px 3px 6px, rgba(0, 0, 0, 0.23) 0px 3px 6px;">


                <div class="box-body">
                    
                    
                <div id="content-div">
                    
                    <div class="col-lg-12">

                        <form id="form_details" autocomplete="off">
                                                                 
                        <div class="row">
                            
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label class="required" for="customer_id">Customer Details</label>                                   
                                    <select name="customer_id" class="form-control select2" style="width:100%" id="customer_id" required="required">
                                        <option value="">Select Customer</option>
                                        <?php $statement = $pdo->prepare("SELECT * FROM `tbl_customers` where status=1");
                                            $statement->execute();
                                            $resultsss = $statement->fetchAll(PDO::FETCH_ASSOC); 
                                            foreach ($resultsss as $ress) { ?>
                                                <option value="<?=$ress['id']?>"><?=$ress['customer_name']?> - <?=$ress['mobile_no']?></option>
                                        <?php  }  ?>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="col-md-2">
                                <div class="form-group">
                                    <label class="required" for="date">Date</label>                                   
                                    <input type="date" name="date" class="form-control" style="width:100%" id="date" value="<?=date('Y-m-d')?>" required="required">
                                </div>
                            </div>
                            
                            <div class="col-md-2">
                                <div class="form-group">
                                    <label class="required" for="product_type">Type</label>                                   
                                    <select name="product_type" class="form-control select2" style="width:100%" id="product_type" required="required">
                                        <option value="1">Order</option>
                                        <option value="2">Stock</option>
                                    </select>
                                </div>
                            </div>
                            
                            
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label class="required" for="created_user_id">Created Employees</label>                                   
                                    <select name="created_user_id" class="form-control select2" style="width:100%" id="created_user_id" required="required">
                                        <?php $statement = $pdo->prepare("SELECT * FROM `tbl_users` where status=1");
                                            $statement->execute();
                                            $location_result = $statement->fetchAll(PDO::FETCH_ASSOC); 
                                            foreach ($location_result as $result) { ?>
                                                <option value="<?=$result['id']?>" <?php if($session_id==$result['id']){echo "selected";}?>><?=$result['name']?> - <?=$result['emp_code']?></option>
                                        <?php  }  ?>
                                    </select>
                                </div>
                            </div>
                            
                            
                            
                            
                            
                    </div>
                    
                    <div class="row">
                            
                            <div class="col-md-2">
                                <div class="form-group">
                                    <label class="required" for="product_ids">Products</label>                                   
                                    <select name="product_ids" class="form-control select2" style="width:100%" onchange="productKarat()" id="product_ids" required="required">
                                        <option value="">Select Product</option>
                                        <?php $statement = $pdo->prepare("SELECT * FROM `tbl_ids_products` WHERE status=1");
                                            $statement->execute();
                                            $resultsss = $statement->fetchAll(PDO::FETCH_ASSOC); 
                                            foreach ($resultsss as $ress) { ?>
                                                <option value="<?=$ress['id']?>"><?=$ress['name']?></option>
                                        <?php  }  ?>
                                    </select>
                                </div>
                            </div>
                            
                            
                            
                            
                            
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label class="required" for="product_variant_id">Product Details</label>                                   
                                    <select name="product_variant_id" class="form-control select2" style="width:100%" id="product_variant_id">
                                        <option value="">Select Product</option>
                                        <?php $statement = $pdo->prepare("SELECT tbl_product_variants.*, tbl_products_name.name as products_name 
                                                                        FROM `tbl_product_variants` 
                                                                        LEFT JOIN tbl_products_name ON tbl_products_name.id=tbl_product_variants.product_name
                                                                        WHERE tbl_product_variants.sales_status=1");
                                            $statement->execute();
                                            $resultsss = $statement->fetchAll(PDO::FETCH_ASSOC); 
                                            foreach ($resultsss as $ress) { ?>
                                                <option value="<?=$ress['id']?>"><?=$ress['products_name']?> - <?=$ress['hsn_code']?></option>
                                        <?php  }  ?>
                                    </select>
                                </div>
                            </div>
                            
                            
                            <div class="col-md-2">
                                <div class="form-group">
                                    <label class="required" for="purity">Purity</label>                                   
                                    <select name="purity" class="form-control select2" onchange="GetTodayAmount()" style="width:100%" id="purity" required="required">
                                        <option value="">Select Purity</option>
                                        <?php $statement = $pdo->prepare("SELECT tbl_ids_purity.*,tbl_ids_products.name as product_name 
                                        FROM `tbl_ids_purity`
                                        LEFT JOIN tbl_ids_products ON tbl_ids_products.id=tbl_ids_purity.product_ids WHERE tbl_ids_purity.status=1");
                                            $statement->execute();
                                            $resultsss = $statement->fetchAll(PDO::FETCH_ASSOC); 
                                            foreach ($resultsss as $ress) { ?>
                                                <option value="<?=$ress['id']?>"><?=$ress['name']?> - <?=$ress['product_name']?></option>
                                        <?php  }  ?>
                                    </select>
                                </div>
                            </div>
                            
                            
                            <div class="col-md-2">
                                <div class="form-group">
                                    <label class="required" for="per_product_gram_amount">Per Gram Amount</label>                                   
                                    <input type="text" name="per_product_gram_amount" class="form-control" style="width:100%" id="per_product_gram_amount" value="" required="required">
                                </div>
                            </div>
                            
                            
                            
                            
                            <div class="col-md-2">
                                <div class="form-group">
                                    <label class="required" for="weight_gram">Weight</label>                                   
                                    <input type="text" name="weight_gram" class="form-control weight" oninput="AmountCalc()" style="width:100%" id="weight_gram" value="" required="required"  onkeypress="return isNumberKey(this, event);">
                                </div>
                            </div>
                            
                            <div class="col-md-2">
                                <div class="form-group">
                                    <label class="required" for="total_amount">Total Amount</label>                                   
                                    <input type="text" name="total_amount" class="form-control" style="width:100%" id="total_amount" value="" required="required"  onkeypress="return isNumberKey(this, event);">
                                </div>
                            </div>
                            
                            
                            <div class="col-md-2">
                                <div class="form-group">
                                    <label class="optional" for="order_size">Size</label>                                   
                                    <input type="text" name="order_size" class="form-control" style="width:100%" id="order_size" value="">
                                </div>
                            </div>
                            
                            
                            <div class="col-md-2">
                                <div class="form-group">
                                    <label class="optional" for="order_length">Length</label>                                   
                                    <input type="text" name="order_length" class="form-control" style="width:100%" id="order_length" value="">
                                </div>
                            </div>
                            
                            
                            
                            
                            
                            
                            
                            
                            
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label class="required" for="advance_policy">Advance Policy</label>                                   
                                    <select name="advance_policy" class="form-control select2" onchange="DateCalc()" style="width:100%" id="advance_policy" required="required">
                                        <option value="">Select Advance Policy</option>
                                        <?php $statement = $pdo->prepare("SELECT * FROM `tbl_advance_policy` WHERE status=1");
                                            $statement->execute();
                                            $resultsss = $statement->fetchAll(PDO::FETCH_ASSOC); 
                                            foreach ($resultsss as $ress) { ?>
                                                <option value="<?=$ress['id']?>" data-days="<?=$ress['days']?>" data-percentage="<?=$ress['percentage']?>"><?=$ress['name']?></option>
                                        <?php  }  ?>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="col-md-2">
                                <div class="form-group">
                                    <label class="required" for="advance_amount">Advance Amount</label>                                   
                                    <input type="text" name="advance_amount" class="form-control" oninput="NewAdvCalc()" style="width:100%" id="advance_amount" value="" required="required"  onkeypress="return isNumberKey(this, event);">
                                    <input type="hidden" id="advance_amount_db">
                                </div>
                            </div>
                            
                            <div class="col-md-2">
                                <div class="form-group">
                                    <label class="required" for="advance_total_weight">Advance Total Weight</label>                                   
                                    <input type="text" name="advance_total_weight" class="form-control" style="width:100%" id="advance_total_weight" value="" required="required"  onkeypress="return isNumberKey(this, event);">
                                </div>
                            </div>
                            
                            <div class="col-md-2">
                                <div class="form-group">
                                    <label class="required" for="expected_purchase_date">Expected Purchase Date</label>                                   
                                    <input type="date" name="expected_purchase_date" class="form-control" style="width:100%" id="expected_purchase_date" value="" required="required">
                                </div>
                            </div>
                            
                            
                            
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label class="optional" for="expected_purchase_date">Remarks</label>     
                                    <textarea name="remarks" id="remarks" placeholder="Remarks" rows="3" class="form-control"></textarea>
                                </div>
                            </div>
                            
                            
                            
                            <div class="col-md-2">
                                 <span class="btn btn-primary btn-xs" id="add_new_row" style="margin-top: 20px;"><i class="fa fa-plus"></i> Add Payment</span>
                            </div>
                            
                           
                        </div>
                        
                        
                        <div class="row porow" style="margin-top: 20px;">
                            
                            
                            
                            
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label class="required" for="paid_amount">Amount</label>        
                                    <input type="hidden" name="payment_id[]" value="0">
                                    <input type="text" name="paid_amount[]"  placeholder="Enter the Amount" class="form-control paid_amount" required="required" id="paid_amount" />
                                </div>
                            </div>
                            
                            
                            
                            <div class="col-md-2">
                                <div class="form-group">
                                     <label class="required" for="payment_type">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']?>"><?=$result['name']?></option>
                                        <?php } ?>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label class="optional" for="reference">Reference</label>                                   
                                    <input type="text" name="reference[]"  placeholder="Reference No" class="form-control"  id="reference" />
                                </div>
                            </div>
                            
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label class="optional" for="notes">Notes</label>                                   
                                    <textarea name="notes[]" id="notes" placeholder="Notes" rows="3" class="form-control"></textarea>
                                </div>
                            </div>
                            
                            <div class="col-md-1">
                            </div>
                            
                            
                           
                        </div>
                        
                        <div id="append_sections"></div>
                        

                        <div class="form-group" style="text-align:center; margin-top: 20px;">
                            <input type="submit"  id="submit" value="Add Advance Voucher" class="btn btn-success" />
                        </div>
                        
                        </form>

                    </div>
                    
                    
                        <div class="form-group" style="text-align:center; margin-top: 20px;">
                            <a href="advance-voucher-add.php"><button class="btn btn-primary" ><i class="fa fa-refresh"></i> Reset Form</button></a>
                            <a href="advance-voucher-list.php"><button class="btn btn-warning" ><i class="fa fa-chevron-left"></i> Back to List</button></a>
                        </div>
                        
                </div>
                
                
<div class="container" id="loading-div" style="display: none; margin-top: 40px; margin-bottom: 40px;">
        <center> <img src="img/loading.gif" style="width: 250px;"><br><b class="blinking">Processing Please Wait...</b></center>
</div>
                    
                    
                    
                    
                    <div class="container" id="success-div" style="display: none; margin-top: 40px; margin-bottom: 40px;">
                        <center><b class="blinking" style="font-size:22px;">Advance Voucher Added Successfully...</b><br>
                            <img src="img/success.gif" style="width: 250px;">
                            <br><br>
                            <a href="advance-voucher-add.php"><button class="btn btn-info"><i class="fa fa-refresh"></i> Reset Form</button></a>
                            &nbsp;&nbsp;
                            <a href="advance-voucher-list.php"><button class="btn btn-warning"><i class="fa fa-chevron-left"></i> Back to List</button></a>
                        </center>
                    </div>
                        
                        
                        
                    <div class="clearfix"></div>
                </div>
            </div>
        </div>
    </div>


</section>

<?php }else{ ?>

<?=$page_not_access?>

<?php } ?>

<?php include "footer.php"; ?>


<script>
$(document).ready(function() {
   $('#form_details').on('submit', function(e){
                e.preventDefault();
                $('#loading-div').show();
                $('#content-div').hide();
                $("#submit").prop('disabled', true);
                var formData = new FormData(this);
                formData.append('type', 'add_advance_voucher');
                    $.ajax({
                            url: 'apis/advance_voucher.php',
                            type: 'post',
                            dataType: 'json',
                            data: formData,
                            cache: false,
                            contentType: false,
                            processData: false,
                            enctype: 'multipart/form-data',
                            success: function (response) {
                                console.log(response);
                                if(response['status']==200){
                                     alert(response['message']);
                                     $('#form_details').trigger("reset");
                                     $("#submit").prop('disabled', false);
                                     $('#success-div').show();
                                     $('#loading-div').hide();
                                }else{
                                    alert(response['message']);
                                    $("#submit").prop('disabled', false);
                                    $('#loading-div').hide();
                                    $('#content-div').show();
                                }
                            }
                        });
   });
});
</script>


<style>
    .porow{
        margin-top: 20px;
    background: aliceblue;
    padding: 10px 0px 10px 0px;
    box-shadow: rgba(0, 0, 0, 0.02) 0px 1px 3px 0px, rgba(27, 31, 35, 0.15) 0px 0px 0px 1px
    }
</style>

<script>

$(document).on('click', '.remove_row', function() {
        $(this).closest('.porow').remove();
        grand_total();
});


function AmountCalc(){
    var weight = $("#weight_gram").val() || 0;
    var per_gm_rate = $("#per_product_gram_amount").val() || 0;
    
    Calc = parseFloat(weight)*parseFloat(per_gm_rate);
    
    $("#total_amount").val(Calc.toFixed(2));
}

function DateCalc(){
    var TotalAmount = $("#total_amount").val();
    var PerGramAmount = $("#per_product_gram_amount").val();
    var selectedOption = $("#advance_policy").find("option:selected");
    var days = selectedOption.data("days");
    var percentage = selectedOption.data("percentage");
    var todayDate = new Date($("#date").val());
    var weight = $("#weight_gram").val();
    
    AdvanceAmount = parseFloat(TotalAmount)*parseFloat(percentage)/100;
    
    $("#advance_amount").val(AdvanceAmount.toFixed(2));
    $("#advance_amount_db").val(AdvanceAmount.toFixed(2));
    
    var EnterAdvanceAmount= $("#advance_amount").val();
    Advance_Pro_Weight = parseFloat(EnterAdvanceAmount)/parseFloat(PerGramAmount);
    $("#advance_total_weight").val(weight);
    
    if (!isNaN(todayDate.getTime()) && !isNaN(days)) {
            var finalDate = new Date(todayDate.getTime() + (days * 24 * 60 * 60 * 1000));

            var finalDateString = finalDate.toISOString().split('T')[0];
            
            $("#expected_purchase_date").val(finalDateString);
            
            console.error("Date: "+finalDateString);
        } else {
            
            console.error("Invalid date or days.");
        }
        
        
}

function NewAdvCalc(){
    
    var advance_amount_db = $("#advance_amount_db").val();
    var EnterAdvanceAmount= $("#advance_amount").val();
    var PerGramAmount = $("#per_product_gram_amount").val();
    var weight = $("#weight_gram").val();
    
    BalanceAmount = parseFloat(EnterAdvanceAmount)-parseFloat(advance_amount_db);
    
    
    console.log("Advance DB Amount: "+advance_amount_db);
    console.log("Advance Enter Amount: "+EnterAdvanceAmount);
    console.log("Balance Amount: "+BalanceAmount);
    console.log("Per Gram Amount: "+PerGramAmount);
    
    BalanceGramWeight = BalanceAmount/PerGramAmount;
    console.log("Balance Gram Weight: "+BalanceGramWeight);
    
    Advance_Pro_Weight = parseFloat(EnterAdvanceAmount)/parseFloat(PerGramAmount);
    
    console.log("Total Amount: "+EnterAdvanceAmount+" Per Gram Amount: "+PerGramAmount+" Calculation: "+Advance_Pro_Weight);
    cal = parseFloat(weight) + parseFloat(BalanceGramWeight);
    $("#advance_total_weight").val(cal.toFixed(2));
}

$(document).ready(function() {
    
var count = 1;
$("#add_new_row").click(function(){
    
    var row=`<div class="row porow" style="margin-top: 20px;">
                            
                            
                            
                            
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label class="required" for="paid_amount">Amount</label>                      
                                    <input type="hidden" name="payment_id[]" value="0">
                                    <input type="text" name="paid_amount[]"  placeholder="Enter the Amount" class="form-control paid_amount" required="required" id="paid_amount" />
                                </div>
                            </div>
                            
                            
                            
                            <div class="col-md-2">
                                <div class="form-group">
                                     <label class="required" for="payment_type">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']?>"><?=$result['name']?></option>
                                        <?php } ?>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label class="optional" for="reference">Reference</label>                                   
                                    <input type="text" name="reference[]"  placeholder="Reference No" class="form-control"  id="reference" />
                                </div>
                            </div>
                            
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label class="optional" for="notes">Notes</label>                                   
                                    <textarea name="notes[]" id="notes" placeholder="Notes" rows="3" class="form-control"></textarea>
                                </div>
                            </div>
                            
                            <div class="col-md-1">
                                <span class="btn btn-danger btn-sm remove_row" style="margin-top: 25px;"><i class="fa fa-times"></i></span>
                            </div>
                           
                        </div>`;
        
        $("#append_sections").append(row);
        $(".select2").select2();
        count++;
});
});

function productKarat(){
    
    $('#purity').empty();  
    var product_ids = $("#product_ids").val();
    $.ajax({
            url: 'api/get-values-api.php',
            type: 'post',
            dataType: 'json',
            data: {type:'get_purity',product_ids:product_ids},
            success: function (response) {
                console.log(response);
                if(response['error']==false){
                    var m='';
                    for(var n=0;n<response['data'].length;n++){
                        m+='<option value='+response['data'][n]['id']+'>'+response['data'][n]['name']+'</option>';
                    }
                 $('#purity').append(m);  
                 $('#purity').trigger('change');
                 
                 GetTodayAmount();
                }
            }
        });
    
}

function GetTodayAmount(){
    console.log("Get Today Amount Changed");
    var product_ids = $("#product_ids").val();
    var purity_ids = $('#purity').val(); 
   
    $.ajax({
            url: 'api/get-values-api.php',
            type: 'post',
            dataType: 'json',
            data: {type:'get_today_rates',product_ids:product_ids, purity_ids:purity_ids},
            success: function (response) {
                console.log(response);
                if(response['error']==false){
                    console.log(response);
                    $("#per_product_gram_amount").val(response['today_rate']);
                }else{
                    $("#per_product_gram_amount").val("0");
                }
            }
        });
}
</script>