<?php ob_start(); session_start();  if(!isset($_SESSION['sales'])){ header('location:login.php'); die();}
// include 'dbconn.php';
// include 'inc/functions.php';
include 'xyz.php';
$_SESSION['my_branch_code'] = $my_branch_code;
   ?>
<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>myOutlet App</title>
   <?php  //include 'inc/toplinks.php';  ?>
   <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
<link href="css/sb-admin-2.min.css" rel="stylesheet">
<!-- <link href="vendor/datatables/dataTables.bootstrap4.min.css" rel="stylesheet"> -->
<script src="vendor/jquery/jquery.min.js"></script>

<script type="text/javascript" src="tab/sweetalert.min.js"></script>
<link rel="stylesheet" type="text/css" href="tab/sweetalert.css">
<link rel="shortcut icon"  href="img/shop_9253640.png">
</head>

<body id="page-top">

    <!-- Page Wrapper -->
    <div id="wrapper">

      

            <?php  include 'inc/menus.php';  ?>


        <!-- End of Sidebar -->

        <?php include 'inc/top.php';   ?>
                <!-- End of Topbar -->

                <!-- Begin Page Content -->
                <div class="container-fluid">

                    <!-- Page Heading -->
                   <?php  include 'inc/greet.php';  ?><br>
                   
                    <!-- DataTales Example -->
                    <div class="card shadow mb-4">
                        <div class="card-header bg-secondary py-3">
    <h6 class="m-0 font-weight-bold text-white ">#PRODUCT SALES</h6>
                        </div>
                        <div class="card-body">
                            <div class="col-md-10" style="box-shadow:10px 10px 40px gray;">
<input type="hidden" name="allowStatus" value="<?php echo $restrict_status;  ?>" id="MaxRent">
<?php  include 'process.php';  ?>



 <form action="" id="form20" method="POST">
<?php    
$get_recent_ID = QueryDB("SELECT id FROM payment order by id DESC LIMIT 1"); 
$rec=$get_recent_ID->fetch(PDO::FETCH_ASSOC);
 $new_cus_ID = date('y').date('m').'#'.$rec['id'].'B'.rand(100,999);
?>
<div class="row"> <div class="form-group col-md-6 mt-3"><select name="userName" class="form-control myselect" required id="CustomerName" style="height:200px !important" >
<option value="<?php echo $new_cus_ID;  ?>"><?php echo $new_cus_ID;  ?></option>
    <?php foreach(QueryDB("SELECT * FROM customers order by frm_name ASC  ") as $rows){echo '<option value="'.$rows['id'].'">'.$rows['frm_name'].' '.$rows['frm_phone'].' ('.get_branch_name($rows['branch']).')</option>'; }?></select></div>

<div class="form-group col-md-6 col-6 mt-3">
<input type="text" readonly="" name="realCost" id="showTotal" class="form-control "></div>


<!-- <div class="form-group col-md-5 mt-3"><select class="form-control" required name="eqSex" id="eqSex"><option value="">--Sex-</option>  <option value="M">Male</option> <option value="F">Female</option> </select></div> -->







<!-- <div class="form-group col-md-3"><input type="text" name="userPhone" class="form-control"  id="usphones" placeholder="Phone" onkeypress="return isNumberKey(event);" maxlength="11" minlength="11"></div> -->

<div class="form-group col-md-12"><textarea class="form-control" name="myAddr" id="myAddr">
Lokoja
</textarea></div>

<?php  $y =1;
$sql = "SELECT * FROM products WHERE tm_status = 1 AND category = 1 ORDER BY item_name ASC";
$stmt = $db->prepare($sql);
//$stmt->bindParam(':place', $place, PDO::PARAM_STR); // Adjust the parameter type as necessary
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);



?>



 <?php  for($y=1;$y<2;$y++){?> 
<div class="form-group col-md-4 col-10">
<select class="form-control myselect2 viewItem1"  name='Item[]' id="orderProd<?php echo $y;  ?>" style="height:'350px !important;'"><option value="">-Item <?php echo $y;  ?>-</option><?php foreach(QueryDB("SELECT * FROM products where tm_status=1 order by item_name ASC ")as $selProd){ echo '<option value='.$selProd['id'].'>'.$selProd['item_name'].'</option>';  }?></select></div>
<div class="form-group col-md-1 col-2">
<button id="blrBtn<?php echo $y;  ?>" class="btn btn-primary">Clear</button></div>

<div class="form-group col-md-1 col-3"><input type="number" name='QTY[]'   id="orderCount<?php echo $y;  ?>" class="form-control">
</div>
<button id="grow<?php echo $y;  ?>" type="button" name="+" class="btn btn-primary btn-xs btn-sm col-1 sub d-block d-md-none" style="height:35px;">+</button>
<span class="d-block d-md-none">&nbsp;</span> <button id="duce<?php echo $y;  ?>" type="button" name='-' class="btn btn-success btn-xs btn-sm col-1 sub d-block d-md-none" style="height:35px;">-</button>


<div class="form-group col-md-2 col-3 text-center"><input type="number" name="singleCost[]" class="form-control" readonly id="wrapCost<?php echo $y;  ?>" >
</div>
<div class="form-group col-md-2 col-3"><input type="number" class="" readonly="" id="orderCost<?php echo $y;  ?>" name="tCost[]" style="width:100%;height:100%;"></div>

<?php  } ?>
<div class="form-group col-md-2 col-3 text-center"><button type="submit" class="btn btn-primary col-md-12" id="barOrder">ADD ORDER</button></div>

</div>

<div class="row no-gutters mt-3" style="border:2px solid green;"><div class="alert alert-success alert-dismissible col-md-12" id="show1" style="height:50px;display: none;"><a href="#" class="close text-center" data-dismiss="alert" aria-label="close">&times;</a><strong>  Order  Successfully</strong></div>
<div class="col-md-12" id="selectedItems"></div>
<h4 class="text-right" style="text-align: right;"><span>Total: &#8358;</span> <span id="showTotalWine"></span></h4>



</div>








<div class="row">
    <div class="form-group col-md-4 mt-3"><input type="text" name="paying" class="form-control"  id="prod_costed" placeholder="Paid" required onkeypress="return isNumberKey(event);"></div>


<div class="form-group col-md-4 mt-3"><select name="pay_mth" id="pay_mth" class="form-control" required><option value="">-Pay Method-</option>
<?php foreach(QueryDB("SELECT * FROM paymth where status=1 and (branch_c='$my_branch_code' || branch_c='' )")as $item){
echo '<option value='.$item['id'].'>'.$item['mth_name'].'</option>'; }?></select></div>



<div class="form-group col-md-4 mt-3"><button id="finalSubmit" type="submit" class="btn btn-info col-md-12" >Pay</button>
</div></div>

</form>                               



   





                            </div>
                        </div>
                    </div>

                </div>
                <!-- /.container-fluid -->

            </div>
            <!-- End of Main Content -->

           
              <?php include 'inc/foot.php';  ?>
            

        </div>
        <!-- End of Content Wrapper -->

    </div>

<a class="scroll-to-top rounded" href="#page-top"><i class="fas fa-angle-up"></i>
    </a>

  

<?php  //include 'inc/bottom.php';  
 include 'inc/modals.php';?>

 <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="vendor/jquery-easing/jquery.easing.min.js"></script>
    <script src="js/sb-admin-2.min.js"></script>
   <!--  <script src="vendor/datatables/jquery.dataTables.min.js"></script>
    <script src="vendor/datatables/dataTables.bootstrap4.min.js"></script> -->
    <script type="text/javascript" src="js/select2.min.js"></script>
    <link rel="stylesheet" type="text/css" href="js/select2.min.css">
    <!-- <script src="js/demo/datatables-demo.js"></script> -->
     
    <script type="text/javascript" src="js/select2.min.js"></script>
    <link rel="stylesheet" type="text/css" href="js/select2.min.css">
    <script type="text/javascript" src="js/keyreturned.js"></script>
     <script type="text/javascript" src="js/lga.min.js"></script>
     <script src="js/js_funcs.js"></script>
 <script>
     


$(document).ready(function() {
    $('#finalSubmit').attr('disabled', true);
    var selectedItems = []; 
    var quantities = []; // Array to store quantities
    var singleCosts = []; // Array to store single costs
    var itemCosts = []; // Array to store item costs

/**********Make Payment****/
        $('#barOrder').click(function(e) { e.preventDefault(); //alert('Fine');
            var selectedItemsHtml = $('#selectedItems').html(); // Get the existing selected items HTML

           
            var newSelectionHtml = '';
            var selectionCount = $('#selectedItems p').length + 1; // Get the count of existing selections
            $('.viewItem1').each(function(index) {
                var selectedOption = $(this).find('option:selected');
                if (selectedOption.val() !== "") {
                    var itemID = $(this).val();
                    var itemName = selectedOption.text();
                    var quantity = $('#orderCount' + (index + 1)).val() || 0;
                    var singleCost = parseFloat($('#wrapCost' + (index + 1)).val()) || 0;
                    var itemCost = singleCost * quantity;
                selectedItems.push(itemID); 
                quantities.push(quantity); 
                singleCosts.push(singleCost); 
                itemCosts.push(itemCost); 
                    newSelectionHtml += '<p>Item ' + selectionCount + ': <br/> <span style="font-size:3px" class="itemID">' + itemID + '</span>' + removeDashPart(itemName) + ' - <b>qty:</b> <span class="quantity">' + quantity + '</span> &nbsp;&nbsp; #<span class="singleCost">' + singleCost + '</span> - tt: &#8358;<span class="itemCost">' + itemCost + '</span> <button class="delete-btnBar" data-index="' + selectionCount + '"><i class="fas fa-trash text-danger"></i></button></p>';
                }
            });
            selectedItemsHtml += newSelectionHtml;
            // Update the selected items display
            $('#selectedItems').html(selectedItemsHtml);

if (selectedItems.length > 0) {$('#finalSubmit').prop('disabled', false);
} else {$('#finalSubmit').prop('disabled', true); }

        });
/******************************END*******************************/

        
function updateSelectedData() {
selectedItems = [];quantities = [];singleCosts = [];itemCosts = [];
$('#selectedItems p').each(function() {
        var itemID = $(this).find('.itemID').text();
        var quantity = $(this).find('.quantity').text();
        var singleCost = $(this).find('.singleCost').text();
        var itemCost = $(this).find('.itemCost').text();
        selectedItems.push(itemID);
        quantities.push(quantity);
        singleCosts.push(singleCost);
        itemCosts.push(itemCost);
    });
if (selectedItems.length > 0) {$('#finalSubmit').prop('disabled', false);
    } else {$('#finalSubmit').prop('disabled', true);}
}


 document.getElementById('finalSubmit').addEventListener('click', function(e) {
    e.preventDefault();
  var mergedArrays = mergeDuplicates(selectedItems, quantities, singleCosts, itemCosts);
  if($('#pay_mth').val()==''){alert('Choose a Payment Method');}else{
    $.ajax({
        url: 'get_selected_order',
        type: 'POST',
        dataType: 'html',
        data: {mergedArrays:mergedArrays,type:1,serveWine:'wine',selCusName:$('#CustomerName').val(),paying:$('#prod_costed').val(),pay_mth:$('#pay_mth').val(),realCost:$('#showTotal').val(),myAddr:$('#myAddr').val()},
        success: function(response) {  $('#show1').show();$('#finalSubmit').attr('disabled', true);

        // alert(response);
if(response=='nil'){
swal({text:'Amount Exceed Bill',type:'warning',title:'Excess Payment'},function(){ 
    });     
}else{
swal({text:'Payment was successful',type:'success',title:'Approved'},function(){ 
    window.location = 'receeipts?no='+response;}); 
}

        },
        error: function(xhr, status, error) {
            // Handle error response
            console.error(error);
            alert("Error occurred. Please try again later.");
        }
    });

}

});










        // Delete selected item when delete button is clicked
        $(document).on('click', '.delete-btnBar', function() {
            var index = $(this).data('index');
            $('#selectedItems p:nth-child(' + index + ')').remove();
            updateSelectedData();
        });
    });



//Add up Total Purchase
setInterval(function() {
    var totalCost = 0; getWineTotal=0; getShishaTotal =0; getFoodTotal =0;
$('#selectedItems p').each(function() {
var itemCost = parseFloat($(this).find('.itemCost').text());
getWineTotal +=itemCost;
totalCost += itemCost;});
$('#showTotalWine').text(getWineTotal); 
 $('#showTotal').val(totalCost.toFixed(2));  
$('#prod_costed').val(totalCost.toFixed(2));
 //show at the top
}, 1000);



 </script>

    <script type="text/javascript">
$(".myselect").select2({width:'100%',height:'1000px !important',theme: "classic",tags:true});
$(".myselect2").select2({width:'100%',height:'1000px !important',theme: "classic",tags:false});


    </script>


  <?php include 'js/foot_links.php';   ?>
 
<script>
$(window).on('load', function() { $('#showPay').modal('show');});

   setwhere =1;

$('#getInfo').change(function(e){$.ajax({data: {getProductInfo:$(this).val()},type:"post",dataType:'html',url: "processor",success: function(data){  
// alert(data);

  $('#showProdInfo').html(data);
},error: function(jqXHR, textStatus, errorThrown) { alert('Error');}
    });
})

status = $('#MaxRent').val();
if(status==0){ $('[id^=wrapCost]').prop('readonly',true);
$('#prod_costed').prop('readonly',true);

}else{ $('[id^=wrapCost]').prop('readonly',false);
$('#prod_costed').prop('readonly',true);

}

// $('[id^=orderCount]').bind('keyup change', function (e) {
// id = $(this).prop('id'); lcard=id.slice(10);
// $calcPrice = $('#wrapCost'+lcard).val();  getCount =$('#'+id).val();
// if(getCount<1){ $(this).val(1); }else{
//   $newCalc =$calcPrice*getCount;
// $('#orderCost'+lcard).val($newCalc);
// }

//   });


</script>
</body>

</html>