<?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');
        }
        
        public function getOrder($id)
        {
            return $this->fetchRow('orders', ['id' => $id]);
        }
    }
    
    
    $obj = new editRestaurantOrder();
    $categories = $obj->getAllCategories();
    $items = $obj->getAllMenuItems();
    $order = $obj->getOrder($id);
    if(!$order)
    {
        exit;
    }
    
require_once 'database.php';


 include 'header.php';
 ?>
 
 <div class="ordes-content">
    <div class="container midle-order">
        <div class="row">
        	<?php include 'menu.php';?>
            <div class="col-md-9">
                
                <div class="order-wraper">
                	<div class="col-md-12">
                    	<h1>Edit Order</h1>
                    </div>
                    <div class="clearfix"></div>
                    <div class="col-sm-12">
                        <div class="row">
                            <h2 class="col-xs-12">
                                All Items in Order
                            </h2>
                            <label>
                                Select Table
                            </label>
                            <select class="form-control" id="table_no">
                                <option value="0">---Select---</option>
                                <option value="1" <?php if($order['table_no'] == 1){echo 'selected';} ?>>1</option>
                                <option value="2" <?php if($order['table_no'] == 2){echo 'selected';} ?>>2</option>
                                <option value="3" <?php if($order['table_no'] == 3){echo 'selected';} ?>>3</option>
                                <option value="4" <?php if($order['table_no'] == 4){echo 'selected';} ?>>4</option>
                                <option value="5" <?php if($order['table_no'] == 5){echo 'selected';} ?>>5</option>
                                <option value="6" <?php if($order['table_no'] == 6){echo 'selected';} ?>>6</option>
                                <option value="7" <?php if($order['table_no'] == 7){echo 'selected';} ?>>7</option>
                            </select>
                            <div class="table_error">
                                
                            </div>
                            <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-xs-12">
                                Select One Category
                            </h2>
                            <?php
                            if(!empty($categories))
                            {
                                foreach($categories AS $category)
                                {
                                    ?>
                                        <div class="col-xs-6 col-md-3 category-box" style="padding-left:5px;padding-right:5px" cluster-id="<?php echo htmlspecialchars($category['id']) ?>">
                                            <div class="col-xs-12  box-container" style="height:70px">
                                                <div class="row">
                                                    <img class="col-xs-3" src="/images/<?php echo $category['image'] ?>" style="padding-left: 7px;padding-right:7px"/>
                                                    <div class="col-xs-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-xs-12">
                                <a href="#" id="back_button" class="btn btn-success">
                                    < Back to Categories
                                </a>
                            </div>
                            <h2 class="col-xs-12">
                                Add item to cart
                            </h2>
                            <?php
                            if(!empty($items))
                            {
                                foreach($items AS $item)
                                {
                                    ?>
                                        <div class="col-xs-6 col-md-3 item-box" style="display:none" cluster-id="<?php echo htmlspecialchars($item['id']) ?>" cluster-categoryID="<?php echo htmlspecialchars($item['cat_id']) ?>">
                                            <div class="col-xs-12  box-container">
                                                
                                                <div class="row">
                                                    <div class="error-main">
                                                        
                                                    </div>
                                                    <div class="col-xs-12">
                                                        <?php echo htmlspecialchars($item['name']) ?>
                                                    </div>
                                                    <div class="col-xs-12">
                                                        Price: <?php echo htmlspecialchars($item['price']) ?>
                                                    </div>
                                                    <div class="col-xs-12">
                                                        <div class="row">
                                                            <div class="col-xs-12">
                                                                <input type="text" value="1" class="form-control quantity" placeholder="Enter Quantity" style="margin-top: 5px" />
                                                            </div>
                                                            <div class="col-xs-12" style="margin-top:5px">
                                                                <button type="button" class="col-xs-12 btn btn-success btn-submit">Add Item</button>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    
                                                </div>
                                            </div>
                                        </div>
                                    <?php
                                }
                            }
                            ?>
                        </div>
                    </div>
                </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-success 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('change', '#table_no', function(){
    var tableNo = $(this).val();
    $('.table_error').html('<div class="alert alert-warning col-12">Updating table</div>');
    $.post('ajax/save_table_number?id=<?php echo htmlspecialchars($id) ?>', {tableNo:tableNo}, function(){
        $('.table_error').html('<div class="alert alert-success col-12">Table Updated Successfully</div>');
    }, 'json')
    .fail(function(xhr) {
                
                $('.table_error').html('<div class="alert alert-danger col-12">Something Went Wrong</div>');
              },'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');;
       })
    });
</script>
 
 <?php
  include 'footer.php';