<?php
define('DOCUMENT_ROOT_CLASS','../');
define('DOCUMENT_ROOT_INC_FOLDER','');
$filepath = realpath(dirname(__FILE__));
require "../inc/header.php";
$msg = Session::get('msg');
Session::set("msg", NULL);
?>
<style type="text/css">
	.select2-container{
		width: 100% !important;
	}
</style>
    
    <div class="row">
        <div class="col-sm-12">
            <div class="page-title-box">
                <div class="row">
                    <div class="col">
                        <h4 class="page-title"><?php echo ($_GET['state'] != "list")?"Receipt # 00001":" Receipt List "; ?></h4>
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item"><a href="javascript:void(0);">Generate Receipt</a></li>
                            <li class="breadcrumb-item"><a href="javascript:void(0);"><?php echo ($_GET['state'] != "list")?"Receipt":"Receipt"; ?></a></li>
                        </ol>
                    </div><!--end col-->
                    <div class="col-auto align-self-center">
                    	
                    </div><!--end col-->  
                </div><!--end row-->                                                              
            </div><!--end page-title-box-->
        </div><!--end col-->
    </div><!--end row-->
    <!-- end page title end breadcrumb -->
    <?php if(@$_GET['state'] == "list"): ?>
    <div class="row">
        <div class="col-12">
            <div class="row justify-content-center">
                <div class="col-md-6 col-lg-3">
                    <div class="card report-card">
                        <div class="card-body">
                            <div class="row d-flex justify-content-center">
                                <div class="col">
                                    <p class="text-dark mb-0 font-weight-semibold">Receipt Created</p>
                                    <h3 class="m-0"><?php echo $commonFunctions->getRowDataCount('sys_receipts',''); ?></h3>
                                    <p class="mb-0 text-truncate text-muted"><span class="text-success"><i class="mdi mdi-trending-up"></i> </span>  </p>
                                </div>
                                <div class="col-auto align-self-center">
                                    <div class="report-main-icon bg-light-alt">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-users align-self-center text-muted icon-sm"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path><circle cx="9" cy="7" r="4"></circle><path d="M23 21v-2a4 4 0 0 0-3-3.87"></path><path d="M16 3.13a4 4 0 0 1 0 7.75"></path></svg>  
                                    </div>
                                </div>
                            </div>
                        </div><!--end card-body--> 
                    </div><!--end card--> 
                </div> <!--end col--> 
                <div class="col-md-6 col-lg-3">
                    <div class="card report-card">
                        <div class="card-body">
                            <div class="row d-flex justify-content-center">                                                
                                <div class="col">
                                    <p class="text-dark mb-0 font-weight-semibold">Amount</p>
                                    <h3 class="m-0"><?php $amount = $commonFunctions->getName('0','sys_receipts','SUM(Amount)','Flag');echo !empty($amount)?$amount:0;?></h3>
                                    <p class="mb-0 text-truncate text-muted"><span class="text-success"><i class="mdi mdi-trending-up"></i></span></p>
                                </div>
                                <div class="col-auto align-self-center">
                                    <div class="report-main-icon bg-light-alt">
                                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-clock align-self-center text-muted icon-sm"><circle cx="12" cy="12" r="10"></circle><polyline points="12 6 12 12 16 14"></polyline></svg>  
                                    </div>
                                </div> 
                            </div>
                        </div><!--end card-body--> 
                    </div><!--end card--> 
                </div> <!--end col--> 
                <div class="col-md-6 col-lg-3">
                </div>
                <div class="col-md-6 col-lg-3">
                </div>                          
            </div>
            <div class="card">
                <div class="card-header">
                    <h4 class="card-title"> 
                        <div class="form-row">
                             
                            <div class="form-group searchForm col-md-6">
                                <?php if(@$_GET['state'] == "list"){ ?>
                            		<a href="receipt-create.php?state=add" role="button" ><button type="button" class="btn btn-outline-dark"><i class="fas fa-plus mr-2"></i> Create Receipt</button> </a>
                                
                                <?php }else{ ?>
                                    <!-- <a href="Receipt.php?state=list"><button type="button" class="btn btn-outline-secondary">Back to Receipt List </button></a> -->
                                <?php } ?>
                            </div>
                            <div class="form-group searchForm col-md-6">
                            	<?php if(empty($_GET['state']) OR (!empty($_GET['state']) and $_GET['state'] == "list")): ?>
                                    <form action="" id="searchForm" method="GET">
                                        <div class="form-row">
                                            <div class="form-group searchForm col-md-8">
                                                <input type="text" name="search" id="search" placeholder="Search" class="form-control" value="<?php echo @$_GET['search']; ?>">
                                                <input type="hidden" name="state" value="<?php echo @$_GET['state']; ?>">
                                                <input type="hidden" name="page" value="<?php echo @$_GET['page']; ?>">
                                            </div>
                                            <div class="form-group searchForm col-md-4">
                                                <button type="submit" id="searchbtn" class="btn btn-primary"> <i class="fa fa-search"></i> Search</button>
                                                <button type="button" id="clearbtn" class="btn btn-danger"> <i class="fa fa-trash"></i> Clear</button>
                                            </div>
                                        </div>
                                    </form>
                                <?php endif; ?>
                            </div>
                        </div>
                    </h4>
                    <?php echo !empty($msg)?$msg:''; ?>        
                </div>
                   
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-12"> 
                            <style type="text/css">
                                tr {cursor: pointer;}
                            </style>
                            <?php 
                            $targetpage = "receipt.php?state=list";
                            $limit1 = 50;
                            $limit = 50;
                            $total_pages = $commonFunctions->getData('sys_receipts','');
                            $total_pages = count($total_pages);
                            $stages = 1;
                            $page = @$_GET['page'];
                            if($page){
                                $start = ($page - 1) * $limit; 
                            }else{
                                $start = 0; 
                            } 
                            $search_con = "";
                            if(!empty($_GET['search'])){
                                $search_con = " AND ReceiptNo LIKE '%".$_GET['search']."%' OR CustomerName LIKE '%".$_GET['search']."%' OR CustomerMobileNumber LIKE '%".$_GET['search']."%' OR Amount LIKE '%".$_GET['search']."%' OR PaymentType LIKE '%".$_GET['search']."%' OR ServiceType LIKE '%".$_GET['search']."%' OR AppointmentDate LIKE '%".$_GET['search']."%' ";
                            }
                            $where = " WHERE id ".$search_con." ORDER BY id DESC LIMIT $start, $limit ";
                            // Initial page num setup
                            if ($page == 0){ $page = 1; }
                            $prev = $page - 1;  
                            $next = $page + 1;  
                            $lastpage = ceil($total_pages/$limit);  
                            $LastPagem1 = $lastpage - 1;    
                            $paginate = '';
                            if($lastpage > 1)
                            {       
                                $paginate .= "<div class='paginate'>";
                                // Previous

                                if ($page > 1){
                                    $paginate.= "<a href='$targetpage&page=$prev'>Previous</a>";
                                }else{
                                    $paginate.= "<span class='disabled'>Previous</span>";   }
                                // Pages    
                                if ($lastpage < 2 + ($stages * 2))  // Not enough pages to breaking it up
                                {   
                                    for ($counter = 1; $counter <= $lastpage; $counter++)
                                    {
                                        if ($counter == $page){
                                            $paginate.= "<span class='current'>$counter</span>";
                                        }else{
                                            $paginate.= "<a href='$targetpage&page=$counter'>$counter</a>";}    
                                    }
                                }
                                elseif($lastpage > 2 + ($stages * 2))   // Enough pages to hide a few?
                                {
                                    // Beginning only hide later pages
                                    if($page < 1 + ($stages * 2))   
                                    {
                                        for ($counter = 1; $counter < 4 + ($stages * 2); $counter++)
                                        {
                                            if ($counter == $page){
                                                $paginate.= "<span class='current'>$counter</span>";
                                            }else{
                                                $paginate.= "<a href='$targetpage&page=$counter'>$counter</a>";}    
                                        }
                                        $paginate.= "...";
                                        $paginate.= "<a href='$targetpage&page=$LastPagem1'>$LastPagem1</a>";
                                        $paginate.= "<a href='$targetpage&page=$lastpage'>$lastpage</a>";
                                    }
                                    // Middle hide some front and some back
                                    elseif($lastpage - ($stages * 2) > $page && $page > ($stages * 2))
                                    {
                                        $paginate.= "<a href='$targetpage&page=1'>1</a>";
                                        $paginate.= "<a href='$targetpage&page=2'>2</a>";
                                        $paginate.= "...";
                                        for ($counter = $page - $stages; $counter <= $page + $stages; $counter++)
                                        {
                                            if ($counter == $page){
                                                $paginate.= "<span class='current'>$counter</span>";
                                            }else{
                                                $paginate.= "<a href='$targetpage&page=$counter'>$counter</a>";}    
                                        }
                                        $paginate.= "...";
                                        $paginate.= "<a href='$targetpage&page=$LastPagem1'>$LastPagem1</a>";
                                        $paginate.= "<a href='$targetpage&page=$lastpage'>$lastpage</a>";
                                    }
                                    // End only hide early pages
                                    else
                                    {
                                        $paginate.= "<a href='$targetpage&page=1'>1</a>";
                                        $paginate.= "<a href='$targetpage&page=2'>2</a>";
                                        $paginate.= "...";
                                        for ($counter = $lastpage - (2 + ($stages * 2)); $counter <= $lastpage; $counter++)
                                        {
                                            if ($counter == $page){
                                                $paginate.= "<span class='current'>$counter</span>";
                                            }else{
                                                $paginate.= "<a href='$targetpage&page=$counter'>$counter</a>";}
                                        }
                                    }       
                                }       
                                        // Next
                                if ($page < $counter - 1){ 
                                    $paginate.= "<a href='$targetpage&page=$next'>Next</a>";
                                }else{
                                    $paginate.= "<span class='disabled'>Next</span>";
                                    }
                                $paginate.= "</div>";   
                            }
                            $invtData = $commonFunctions->getData('sys_receipts',$where);

                            $startP = $limit + $start;
                            if($startP > @count($invtData) ){
                                $startP = @count($invtData) + $start;
                            }
                            echo "<div style='float: right;'>".$paginate."</div>";?>
                            <table style="margin-top: 10px;width: 100% !important;" class="table datatable_t table-hover table-striped table-bordered">
                                <thead>
                                    <tr>
                                        <th class="text-center">Receipt No#</th>
                                        <th class="text-center">Customer Name</th>
                                        <th class="text-center">Receipt Date</th>
                                        <th class="text-center">Amount</th> 
                                        <th class="text-center">Created By</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                    foreach ($invtData as $row) { ?>
                                        <tr onclick="redirect_('view-receipt.php?state=view&receipt_id=<?php echo $row['ReceiptNo'];?>')">
                                            <th class="text-center">
                                                <?php echo $row['ReceiptNo']; ?>
                                            </th>
                                            <th class="text-center">
                                                <?php echo $row['CustomerName']; ?>
                                            </th>
                                            <th class="text-center">
                                                <?php echo $row['CreatedDate']; ?>
                                            </th>
                                            <th class="text-center">
                                                <?php echo $row['Amount']; ?>
                                            </th>
                                             
                                            <th class="text-center">
                                                <?php echo $commonFunctions->getname($row['CreatedBy'],"sys_users","first_name","id")." ".$commonFunctions->getname($row['CreatedBy'],"sys_users","father_name","id")." ".$commonFunctions->getname($row['CreatedBy'],"sys_users","last_name","id");
                                                ?>
                                            </th>
                                        </tr>
                                    <?php } ?>
                                </tbody>
                            </table>
                        </div>                    
                    </div>
                </div>
            </div>
        </div> <!-- end col -->
    </div> <!-- end row -->
<?php endif; ?>
        

<div class="modal fade" id="exampleModalDefault" tabindex="-1" role="dialog" aria-labelledby="exampleModalDefaultLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <form class="form-group save_popup_form" id="save_popup_form">
                <div class="modal-header">
                    <h6 class="modal-title m-0" id="exampleModalDefaultLabel">Do you want to create delivery note ?</h6>
                    <button type="button" class="close " data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true"><i class="la la-times"></i></span>
                    </button>
                </div><!--end modal-header-->
                <div class="modal-body">
                    <div class="row">
                        <div class="col-lg-3"></div>
                        <div class="col-lg-9">
                            <div class="form-check form-check-inline" style="margin-top: 15px;">
                              <input name="delivery_note_flag" class="delivery_note_flag form-check-input" type="radio" id="inlineCheckbox1" value="1" required="">
                              <label class="form-check-label" for="inlineCheckbox1"><b>I want to make delivery note now.</b></label>
                            </div>             
                        </div><!--end col-->
                        <div class="col-lg-3"></div>
                        <div class="col-lg-9">
                            <div class="form-check form-check-inline" style="margin-top: 15px;">
                              <input name="delivery_note_flag" class="delivery_note_flag form-check-input" type="radio" id="inlineCheckbox2" value="2" required="">
                              <label class="form-check-label" for="inlineCheckbox2"><b>I want to make delivery note later.</b></label>
                            </div>             
                        </div><!--end col-->
                        <div class="col-lg-3"></div>
                        <div class="col-lg-9">
                            <div class="form-check form-check-inline" style="margin-top: 15px;">
                              <input name="delivery_note_flag" class="delivery_note_flag form-check-input" type="radio" id="inlineCheckbox3" value="3" required="">
                              <label class="form-check-label" for="inlineCheckbox3"><b>I don`t want to make delivery note.</b></label>
                            </div>             
                        </div><!--end col-->
                        <div class="col-lg-3"></div>
                        <div class="col-lg-9">
                            <br>
                            <label id="delivery_note_flag-error" class="error" for="delivery_note_flag" style=""></label>
                        </div> 
                    </div><!--end row-->                                                      
                </div><!--end modal-body-->
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Close</button>
                    <button type="button" id="save_popup_form_btn" class="btn btn-primary btn-sm">Save changes</button>
                </div><!--end modal-footer-->
            </form>
        </div><!--end modal-content-->
    </div><!--end modal-dialog-->
</div><!--end modal-->
<?php require "../inc/footer.php"; ?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.1/jquery.validate.min.js"></script>
<script type="text/javascript">
    $("#Receipt_form").validate({
        ignore: [],
    });
    $(".save_form").click(function(){
        if($("#Receipt_form").valid()){
            $("#exampleModalDefault").modal("show");
        }else{
        	Swal.fire('Warning', 'Please fill all required fields!', 'error');
        }
    });
    $("#save_popup_form_btn").click(function(){
        if($("#save_popup_form").valid()){
            var delivery_note_flag = $(".delivery_note_flag:checked").val();
            $.ajax({
                type: 'POST',
                url: "",
                data: $('#Receipt_form').serialize()+"&action=ajax_call_2&delivery_note_flag="+delivery_note_flag,
                success: function(response) { 
                    window.location.href = response;
                }
            });
        }
    });
    $("#payment_modes").change(function(){
        $("#payment_modes-error").html("");
        var payment_modes = $("#payment_modes option:selected").text();
        $(".paymode").html(payment_modes);
        if(payment_modes == "Cheque"){
            $(".cheque_div").css("display","");
            /*$("#cheque_name").attr("required","");
            $("#cheque_no").attr("required","");
            $("#cheque_date").attr("required","");
            $("#cheque_bank").attr("required","");*/
        }else{
            $(".cheque_div").css("display","none");
            $("#cheque_name").removeAttr("required","");
            $("#cheque_no").removeAttr("required","");
            $("#cheque_date").removeAttr("required","");
            $("#cheque_bank").removeAttr("required","");
        }
        if(payment_modes == "Bank Transfer"){
            $(".bank_transfer_div").css("display","");
            $("#holder_name").attr("required","");
            $("#trans_date").attr("required","");
            $("#bank").attr("required","");
            $("#transfer_bank").attr("required","");
        }else{
            $(".bank_transfer_div").css("display","none");
            $("#holder_name").removeAttr("required","");
            $("#trans_date").removeAttr("required","");
            $("#bank").removeAttr("required","");
            $("#transfer_bank").removeAttr("required","");
        }
    });    
    $("#payment_terms").change(function(){
        var payment_terms = $("#payment_terms option:selected").text();
        $(".paytype").html(payment_terms);
        $("#payment_terms-error").html("");
    });
    $("#ship_to").change(function(){
        var ship_to = $("#ship_to option:selected").text();
        $(".custAddress").html(ship_to);
        $("#ship_to-error").html("");
    });    
    $("#cust_po").keyup(function(){
        var cust_po = $("#cust_po").val();
        $(".cust_po").val(cust_po);
        $(".cust_po").html(cust_po);
    });
    $("#project").keyup(function(){
        var project = $("#project").val();
        $(".project_id_label").html(project);
    });
    $("#bill_to").change(function(){
        $("#bill_to-error").html("");
    });
    $(".product_id1").change(function(){
        var warehouse_id = $("#warehouse_id option:selected").val();
        var product_id = $(".product_id1 option:selected").val();
        $.ajax({
            type: 'POST',
            url: "",
            data: {"warehouse_id":warehouse_id,"product_id":product_id,"action":"ajax_call_1"},
            success: function(response) { 
                obj = JSON.parse(response);
                $(".quantity1").attr("max",obj.stock_count);
                $(".unit_price1").val(obj.price);
                $(".product_desc1").val(obj.product_desc);
            }
        });
    });
    $("#warehouse_id").change(function(){
        var warehouse_id = $("#warehouse_id option:selected").val();
        var product_id = $(".product_id1 option:selected").val();
        $.ajax({
            type: 'POST',
            url: "",
            data: {"warehouse_id":warehouse_id,"product_id":product_id,"action":"ajax_call_1"},
            success: function(response) { 
                obj = JSON.parse(response);
                $(".product_id1").html("<option value=''>Select</option>"+obj.option);
                $(".quantity1").attr("max",obj.stock_count);
                $(".unit_price1").val(obj.price);
                $(".product_desc1").val(obj.product_desc);
            }
        });
    });
    $(".quantity1").keyup(function(){
        var quantity = parseInt($(".quantity1").val());
        if(quantity != ''){    
            var unit_price = parseInt($(".unit_price1").val());
            $(".total_pro_amt1").val(unit_price * quantity);

            var total_pro_amt = parseInt($(".total_pro_amt1").val());
            var sub_total_amt = parseInt($(".sub_total_amt").val());
            total_pro_amt = 0;
            $(".total_pro_amt").each(function() {
                total_pro_amt = total_pro_amt + parseInt(this.value);
                $(".sub_total_amt").val(total_pro_amt);
                $(".sub_total_amt").html(total_pro_amt);
                $("#discount").attr("max",total_pro_amt);
                var discount = parseInt($("#discount").val());
                if(discount == ""){ discount = 0; }
                $(".total_amt").html(total_pro_amt - discount);
            });
        }
    });
    $("#bill_to").change(function(){
        var bill_to = $("#bill_to option:selected").val();
        $.ajax({
            type: 'POST',
            url: "",
            data: {"bill_to":bill_to,"action":"ajax_call"},
            success: function(response) { 
                obj = JSON.parse(response);

                $("#ship_to").html("<option value=''>Select</option>"+obj.option);
                $(".email").html(obj.email);
                $(".contact").html(obj.contact);

            }
        });
    });
    $(".btn-step-1").click(function(){
        var warehouse_id = $("#warehouse_id option:selected").val();
        var bill_to = $("#bill_to option:selected").val();
        var ship_to = $("#ship_to option:selected").val();
        var payment_modes = $("#payment_modes option:selected").val();
        var payment_terms = $("#payment_terms option:selected").val();
        if(warehouse_id != '' && bill_to != '' && ship_to != '' && payment_modes != '' && payment_terms != '' ){
            $("#warehouse_id-error").html("");
            $("#bill_to-error").html("");
            $("#ship_to-error").html("");
            $("#payment_modes-error").html("");
            $("#payment_terms-error").html("");

            $(".step-1").css("display","none");
            $(".step-2").css("display","block");
        }else{
            if(warehouse_id == ''){ $("#warehouse_id-error").html("Please enter warehouse name."); }
            if(bill_to == ''){ $("#bill_to-error").html("Please enter bill to."); }
            if(ship_to == ''){ $("#ship_to-error").html("Please enter ship to."); }
            if(payment_modes == ''){ $("#payment_modes-error").html("Please enter payment modes."); }
            if(payment_terms == ''){ $("#payment_terms-error").html("Please enter payment terms."); }
        }
    });
    $(".back_to_first").click(function(){
        $(".step-1").css("display","block");
        $(".step-2").css("display","none");
    });
    $("#discount").keyup(function(){
        var discount = parseInt($("#discount").val());
        if(discount == ""){ discount = 0; }
        var sub_total_amt = parseInt($(".sub_total_amt").val());
        $(".total_amt").html(sub_total_amt - discount);
    });
$(document).ready(function() {
    var i = 2;
    $("body").on("click",".add-more",function(){ 
        //var html = $(".after-add-more").first().clone();
        var html = '<tr class="after-add-more">\
          <td>\
            <select name="product_id[]" class="product_id form-control product_id'+i+'">\
                <option value="0">Select</option>\
            </select>\
          </td>\
          <td>\
          <input type="text" class="form-control product_desc'+i+'" name="product_desc[]" placeholder="Enter Product Description" value="">\
          </td>\
          <td>\
            <input type="text" name="unit_price[]" class="form-control unit_price'+i+'" readonly="">\
          </td>\
          <td>\
            <input type="text" name="quantity[]" class="form-control quantity'+i+'" onkeyup="check_quantity('+i+')">\
          </td>\
          <td>\
            <input type="text" name="total_pro_amt[]" class="total_pro_amt form-control total_pro_amt'+i+'" readonly="">\
          </td>\
          <td class="change"><button type="button" class="btn btn-soft-danger btn-icon-circle btn-icon-circle-sm align-self-center remove"><i class="fas fa-times font-16"></i></button></td>\
       </tr>';
        $(html).find(".change").html("<button type='button' class='btn btn-soft-danger btn-icon-circle btn-icon-circle-sm align-self-center remove'><i class='fas fa-times font-16'></i></button><a style='width: 100px;display:none;' class='btn btn-secondary move_stack"+i+"' href='javascript:void(0)' onclick='redirect_stock_movement("+i+")' >Move Stock</a>");      
        $(".after-add-more").last().after(html);
        var j = i;
        
        $('.product_id'+i).select2();

        var warehouse_id = $("#warehouse_id option:selected").val();
        var product_id = $(".product_id"+j+" option:selected").val();
        var value = [];
        $(".product_id option:selected").each(function() {
            value.push(this.value);
            //$(".product_id"+j+" option:[value='"+value+"']").prop('disabled', true);
        });
        $.ajax({
            type: 'POST',
            url: "",
            data: {"warehouse_id":warehouse_id,"product_id":product_id,"action":"ajax_call_1","already_selected":value},
            success: function(response) { 
                obj = JSON.parse(response);
                $(".product_id"+j).html("<option value=''>Select</option>"+obj.option);
                $(".quantity"+j).attr("max",obj.stock_count);
                $(".unit_price"+j).val(obj.price);
                $(".product_desc"+j).val(obj.product_desc);
            }
        });

        $(".product_id"+j).change(function(){
            var warehouse_id = $("#warehouse_id option:selected").val();
            var product_id = $(".product_id"+j+" option:selected").val();
            $.ajax({
                type: 'POST',
                url: "",
                data: {"warehouse_id":warehouse_id,"product_id":product_id,"action":"ajax_call_1"},
                success: function(response) { 
                    obj = JSON.parse(response);
                    $(".quantity"+j).attr("max",obj.stock_count);
                    $(".unit_price"+j).val(obj.price);
                    $(".product_desc"+j).val(obj.product_desc);
                }
            });
        });
        $(".quantity"+j).keyup(function(){
            var quantity = parseInt($(".quantity"+j).val());
            if(quantity != ''){    
                var unit_price = parseInt($(".unit_price"+j).val());
                $(".total_pro_amt"+j).val(unit_price * quantity);

                var total_pro_amt = parseInt($(".total_pro_amt"+j).val());
                var sub_total_amt = parseInt($(".sub_total_amt").val());
                total_pro_amt = 0;
                $(".total_pro_amt").each(function() {
                    total_pro_amt = total_pro_amt + parseInt(this.value);
                    $(".sub_total_amt").val(total_pro_amt);
                    $(".sub_total_amt").html(total_pro_amt);
                    $("#discount").attr("max",total_pro_amt);
                    var discount = parseInt($("#discount").val());
                    if(discount == ""){ discount = 0; }
                    $(".total_amt").html(total_pro_amt - discount);
                });
                
            }
        });
        i++;
    });

    $("body").on("click",".remove",function(){ 
        $(this).parents(".after-add-more").remove();
    });
});
</script>
<script>
    $( function() {
        $( "#cheque_date,#trans_date" ).datepicker();
    } );
    function redirect_(uri){
        window.location.href = uri;
    }
</script>
<script type="text/javascript">
    //var table = $(".datatableCust").dataTable();
	$(".bill_to_btn").click(function(){
		$.ajax({
            type: 'POST',
            url: "",
            data: {"action":"ajax_call_3"},
            success: function(response) { 
                $("#bill_to_tbody").html(response);
                $(".datatableCust").dataTable();
            }
        });
	});
	function set_bill_to_data(id){
		var bill_to_ = $("#bill_to_"+id).val();
		$(".custAddressBillTo").html(bill_to_);
		$("#bill_to").val(id);
		$("#billToModal").modal("hide");
		$(".bill_to_btn").html("Edit");
	}

	$(".ship_to_btn").click(function(){
		var bill_to = $("#bill_to").val();
		if(bill_to != ''){	
			$.ajax({
	            type: 'POST',
	            url: "",
	            data: {"action":"ajax_call_4","bill_to":bill_to},
	            success: function(response) { 
	                $(".ship_to_tbody").html(response);
	                $(".datatableCust").dataTable();
	            }
	        });
	    }else{
	    	$("#ship_to_modal").modal("hide");
	    	alert("Please select bill to first!");
	    }
	});

	
	function set_ship_to_data(id){
		var ship_to_ = $("#ship_to_"+id).val();
		$(".custAddressShipTo").html(ship_to_);
		$("#ship_to").val(id);
		$("#ship_to_modal").modal("hide");
		$(".ship_to_btn").html("Edit");
	}
	$(".cust_po_btn").click(function(){
		$("#cust_po_modal").modal("show");
	});
	$(".paymode_btn").click(function(){
		$("#paymode_modal").modal("show");
	});
	$(".paytype_btn").click(function(){
		$("#paytype_modal").modal("show");
	});
	$(".project_id_label_btn").click(function(){
		$("#project_id_label_modal").modal("show");
	});
	$(".add_warehose").click(function(){
		var text = $("#warehouse_id option:selected").text();
		$(".branch_name").html("<br>"+text);
		$(".wharehouse_btn").html("Edit");
		$("#wharehouseModal").modal("hide");
	});
	function change_label(class_n,modal_id){
		$("."+class_n).html("Edit");
		$("#"+modal_id).modal("hide");
	}
	function redirect_stock_movement(i){
		var product_id = $(".product_id"+i+" option:selected").val();
		var warehouse_id = $("#warehouse_id option:selected").val();
		if(product_id != "undefined" && product_id != ''){
			var url = "<?php echo DOCUMENT_ROOT_CLASS;?>product-services/inventory/stock-movements.php?state=add&warehouse_id="+warehouse_id+"&product_id="+product_id;
			
			$("<a>").prop({
	            target: "_blank",
	            href: url
	        })[0].click();
			//$('a').attr('target', '_blank').attr('href', "<?php echo DOCUMENT_ROOT_CLASS;?>product-services/inventory/stock-movements.php?state=add&warehouse_id="+warehouse_id+"&product_id="+product_id).trigger('click');
		}else{
			Swal.fire('Warning', 'Please select product!', 'error');			
		}
	}

$("#warehouse_id").change();
function check_quantity(inc){
    var quantity = $(".quantity"+inc).val();
    var maxquantity = $(".quantity"+inc).attr("max");
    if(parseInt(quantity) > parseInt(maxquantity)){
        Swal.fire('Warning', 'Sorry stock not available please request for stock movement by clicking on move stock...', 'error');
        $(".move_stack"+inc).css("display","block");
    }else{
        $(".move_stack"+inc).css("display","none");
    }
}
</script>
