<?php
error_reporting(E_ALL);
ini_set('display_errors',1);

if(!isset($_GET['id']))
{
    header('Location: ../admin/');
            exit;
}
$id = $_GET['id'];

session_start();
require_once "check_admin.php";
require_once 'database.php';
if(!isset($_SESSION['user_type']) || $_SESSION['user_type'] !='staff')
    {
            header('Location: ../admin/');
            exit;
    }
    
    
    
    class editRestaurantOrder extends database
    {
        public function getAllCategories()
        {
            return $this->fetchAll('menu_category');
        }
        
        public function getAllMenuItems()
        {
            return $this->fetchAll('menu_item');
        }
    }
    
    
    $obj = new editRestaurantOrder();
    $categories = $obj->getAllCategories();
    $items = $obj->getAllMenuItems();
    
require_once 'database.php';


 include 'header.php';
 ?>
 
 <style>
     .box-container
     {
         cursor: pointer;
     }
 </style>
<div class="content-wrapper">
            <!-- Content -->

            <div class="container-xxl flex-grow-1 container-p-y">
              <h4 class="fw-bold py-3 mb-4">Edit Order</h4>

              <!-- Basic Layout -->
              <div class="row">
                    <div class="col-sm-12">
                        <div class="row">
                            <h2 class="col-12">
                                All Items in Order
                            </h2>
                            <table class="table table-striped" id="menu-table" style="margin-top: 5px">
                                <thead>
                                    <tr>
                                        <th>
                                            Item
                                        </th>
                                        <th>
                                            Quantity
                                        </th>
                                        <th>
                                            Price
                                        </th>
                                        <th>
                                            
                                        </th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td colspan="4">
                                            Loading....
                                        </td>
                                    </tr>
                                </tbody>
                                <tfoot>
                                    
                                </tfoot>
                            </table>
                            <div class="error-main-confirm col-12">
                                
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-12" id="category_container">
                        <div class="row">
                            <h2 class="col-12">
                                Select One Category
                            </h2>
                            <?php
                            if(!empty($categories))
                            {
                                foreach($categories AS $category)
                                {
                                    ?>
                                        <div class="col-6 col-md-3 category-box" style="padding-left:5px;padding-right:5px" cluster-id="<?php echo htmlspecialchars($category['id']) ?>">
                                            <div class="col-12  box-container" style="height:70px">
                                                <div class="row">
                                                    <img class="col-3" src="/images/<?php echo $category['image'] ?>" style="padding-left: 7px;padding-right:7px"/>
                                                    <div class="col-9">
                                                        
                                                        <?php echo htmlspecialchars($category['name']) ?>
                                                    </div>
                                                    
                                                    
                                                </div>
                                            </div>
                                        </div>
                                    <?php
                                }
                            }
                            ?>
                        </div>
                    </div>
                    
                    <div class="col-sm-12" id="item_container" style="display:none">
                        <div class="row">
                            <div class="col-12">
                                <a href="#" id="back_button" class="btn btn-primary">
                                    < Back to Categories
                                </a>
                            </div>
                            <h2 class="col-12 mt-3">
                                Add item to cart
                            </h2>
                            <?php
                            if(!empty($items))
                            {
                                foreach($items AS $item)
                                {
                                    ?>
                                        <div class="col-6 col-md-3 item-box mt-5" style="display:none" cluster-id="<?php echo htmlspecialchars($item['id']) ?>" cluster-categoryID="<?php echo htmlspecialchars($item['cat_id']) ?>">
                                            <div class="col-12  box-container">
                                                
                                                <div class="row">
                                                    <div class="error-main">
                                                        
                                                    </div>
                                                    <div class="col-12">
                                                        <?php echo htmlspecialchars($item['name']) ?>
                                                    </div>
                                                    <div class="col-12">
                                                        Price: <?php echo htmlspecialchars($item['price']) ?>
                                                    </div>
                                                    <div class="col-12">
                                                        <div class="row">
                                                            <div class="col-12">
                                                                <input type="text" value="1" class="form-control quantity" placeholder="Enter Quantity" style="margin-top: 5px" />
                                                            </div>
                                                            <div class="col-12" style="margin-top:5px">
                                                                <button type="button" class="col-12 btn btn-primary btn-submit">Add Item</button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    
                                                </div>
                                            </div>
                                        </div>
                                    <?php
                                }
                            }
                            ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    

<script>

function findTotal()
{
    totalPrice = 0;
    $('#menu-table tbody tr').each(function(i, value){
       var price = $(value).find('.price-edit').text().trim(); 
       console.log(price);
       totalPrice+= Number(price);
    });
    $('#menu-table tfoot').html('<tr><td colspan="3" style="text-align:right">Total: ' + totalPrice + '</td><td><button type="button" class="btn btn-primary" id="confirm_order">Confirm this order</button></td></tr>');
}

function setItems(html, price)
{
    $('#menu-table tbody').html(html);
    var totalPrice = 0;
    findTotal();
    
}
function getAllItems()
{
    var html = '';
    $.get('ajax/getItems.php?id=<?php echo htmlspecialchars($id) ?>', function(res){
        var price =0;
        $(res).each(function(i, value){
            var price = value.price / value.quantity;
            html+= '<tr><td>' + value.name + '</td><td><input type="text" class="form-control quantity-edit" cluster-price="' + price + '" value="' + value.quantity + '" /></td><td class="price-edit">' + value.price + '</td><td><button type="button" class="btn btn-primary btn-update" cluster-id="' + value.id + '">Update</button><button type="button" class="btn btn-danger btn-delete" cluster-id="' + value.id + '">Delete</button></td></tr>';
            //price+= value.pric;
            
        })
        setItems(html);
    },'json');
    
    
}

$(document).on('click', '#confirm_order', function(){
    $('#confirm_order').attr('disabled', 'disabled');
    $('.error-main-confirm').html('<div class="alert alert-warning col-12">Confirmaing order</div>');
    $.get('ajax/confirm_order.php?id=<?php echo htmlspecialchars($id) ?>', function(){
        $('.error-main-confirm').html('<div class="alert alert-success col-12">Order Confirmed</div>');
        window.location.href = 'create_order.php';
    }, 'json')
    .fail(function(xhr) {
                $('#confirm_order').removeAttr('disabled');
                $('.error-main-confirm').html('<div class="alert alert-danger col-12">Something Went Wrong</div>');
              },'json');;
})

$(document).on('click', '.btn-update', function(){
    var id = $(this).attr('cluster-id');
    var parent = $(this).parents('tr').first(); 
    var quantity = $(parent).find('.quantity-edit').val();
    
    var current = $(this);
    $(current).attr('disabled', 'disabled');
    
    $.post('ajax/update_order_item.php?id=' + id, {quantity:quantity}, function(res){
               $(current).removeAttr('disabled');
               alert(res.message);
               getAllItems();
           }, 'json')
           .fail(function(xhr) {
                $(current).removeAttr('disabled');
                alert('Somethong Went Wrong');
              },'json');;
})

$(document).on('click', '.btn-delete', function(){
    var id = $(this).attr('cluster-id');
    var parent = $(this).parents('tr').first(); 
    
    var current = $(this);
    $(current).attr('disabled', 'disabled');
    
    $.post('ajax/delete_order_item.php?id=' + id,  function(res){
              
               alert(res.message);
               getAllItems();
           }, 'json')
           .fail(function(xhr) {
                $(current).removeAttr('disabled');
                alert('Somethong Went Wrong');
              },'json');;
})
    



$(document).on('change', '.quantity-edit', function(){
           var price = $(this).attr('cluster-price');
           var parent = $(this).parents('tr').first();
           var totalPrice = $(this).val() * price;
           $(parent).find('.price-edit').text(totalPrice);
           findTotal();
       })

    $(document).ready(function(){
        getAllItems();
       $('.category-box').click(function(){
           var categoryID = $(this).attr('cluster-id');
           $('#category_container').hide();
           $('#item_container').show();
           $('.item-box[cluster-categoryID="' + categoryID + '"]').show();
       });
       
       $('#back_button').click(function(){
            $('#category_container').show();
           $('#item_container').hide();
           $('.item-box').hide();
       });
       
       
       
       $('.btn-submit').click(function(){
           var parent = $(this).parents('.item-box').first();
           var id = $(parent).attr('cluster-id');
           var quantity = $(parent).find('.quantity').val();
           var current = $(this);
           var parent = $(this).parents('.item-box').first();
           
           $(parent).find('.btn-submit').attr('disabled', 'disabled');
           $.post('ajax/save_order_item.php?id=<?php echo htmlspecialchars($id) ?>', {itemID: id,quantity:quantity}, function(res){
               $(parent).find('.btn-submit').removeAttr('disabled');
               $('#category_container').show();
               $('.item-box').hide();
           $('#item_container').hide();
              // alert(res.message);
               getAllItems();
           }, 'json')
           .fail(function(xhr) {

                $(parent).find('.btn-submit').removeAttr('disabled');
                $(parent).find('.error-main').html('<div class="alert alert-danger col-12">Following errors are listed. Please check errors and resubmit the form.</div>').show();
                
                  var html = '';
                  var res = xhr.responseJSON;
                  console.log(xhr);
                  if (typeof res === 'undefined') {
                  	$(parent).find('.error-main').html('<div class="alert alert-danger col-12">Something went wrong</div>').show();
                  }
                  if (typeof res.error_description === 'undefined') {
                  	if(typeof res.error_text === 'undefined')
                  	{
                    	$(parent).find('.error-main').html('<div class="alert alert-danger col-12">Something went wrong</div>').show();
                    	window.location.href = '#body_part';
                    	return;
                    }
                    else
                    {
                    	$(parent).find('.error-main').html('<div class="alert alert-danger  col-12">' + res.error_text + '</div>').show();
                    	window.location.href = '#body_part';
                    	return;
                    }
                  }
                
                  
                  
                  window.location.href = '#body_part';
              },'json');;
       })
    });
    
     $(document).ready(function(){
        $('.menu-item').removeClass('active');
        $('#order-menu').addClass('active');
        
        
        
    }); 
</script>
 
 <?php
  include 'footer.php';