<?php
include_once '../includes/config.php';
include_once '../includes/database.php';
include_once '../includes/check_session.php';
include_once '../includes/check_edit_page.php';
include_once '../includes/auth.php';

$auth = array('manager');
$authRes = checkAuth($auth, $user);
if(!$authRes)
{
    header('Location: ' . DOMAIN . '/auth/login.php');
    exit;
}


include_once '../includes/check_paid.php';

class Edit extends database
{
   
    public function getOrder($id, $userID, $companyID)
    {
        return $this->fetchRow('tb_order', ['cl_id' => $id, 'cl_user_id' => $userID, 'cl_company_id' => $companyID]);
    }
    
    public function getAllCategories($id)
    {
        return $this->fetchAll('tb_category', ['cl_user_id' => $id]);
    }
    
    public function getAllMenuItems($id)
    {
        return $this->fetchAll('tb_menu', ['cl_user_id' => $id]);
    }
    
    public function getAllTables($id)
    {
        return $this->fetchAll('tb_tables', ['cl_user_id' => $id]);
    }
    
}

$obj = new Edit();
$order = $obj->getOrder($id, $user['cl_id'], $user['cl_user_id']);
if(!$order)
{
    header('Location: add.php');
    exit;
}

$categories = $obj->getAllCategories($user['cl_user_id']);
 $items = $obj->getAllMenuItems($user['cl_user_id']);
 $tables = $obj->getAllTables($user['cl_user_id']);

 include '../header.php';
 ?>
<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="order-contact">
                        	<div class="row edit-user-box">
                                <div class="col-sm-12">
                                    <div class="row">
					<form method="post" id="form1" class="form" cluster-url="ajax/add_ajax.php" cluster-redirect="add.php">
                                                <div class="error-main"></div>		
                                                <?php include "template/form.php"; ?>
                                                
                                                
                                                <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>
                                            </form>				
                                        
                                    </div>
                            	</div>
                        	</div>                            
                        </div>
                    </div>
                </div>
                
                
            
            <div class="order-wraper mt-5" id="category_container">
                	<div class="col-md-12">
                    	<h1>Select One Category</h1>
                    </div>
                    <div class="clearfix"></div>
                    <div class="col-sm-12">
                    	<div class="curent-user">
                        	<div class="row">
								
                                <div class="col-sm-12">
                                    <div class="curent-user-nav">
                                        <div class="row">
                                        <?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['cl_id']) ?>">
                                            <div class="col-xs-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-12" style="text-align: center">
                                                        
                                                        <?php echo htmlspecialchars($category['cl_name']) ?>
                                                    </div>
                                                    
                                                    
                                                </div>
                                            </div>
                                        </div>
                                    <?php
                                }
                            }
                            ?>
                                        </div>
                                    </div>
                                </div>
                                </div>
                        </div>
                    </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-12 mt-5">
                                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['cl_id']) ?>" cluster-categoryID="<?php echo htmlspecialchars($item['cl_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['cl_name']) ?>
                                                    </div>
                                                    <div class="col-xs-12">
                                                        Price: <?php echo htmlspecialchars($item['cl_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>
<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.cl_price / value.cl_quantity;
            html+= '<tr><td>' + value.cl_name + '</td><td><input type="text" class="form-control quantity-edit" cluster-price="' + price + '" value="' + value.cl_quantity + '" /></td><td class="price-edit">' + value.cl_price + '</td><td><button type="button" class="btn btn-success btn-update" cluster-id="' + value.cl_id + '" style="margin-right:5px">Update</button><button type="button" class="btn btn-danger btn-delete" cluster-id="' + value.cl_id + '" cluster-href="ajax/delete_order_item.php?id=' + value.cl_id+ '" cluster-confirm="Are you sure you want to delete this item?">Delete</button><div class="error-input"></div></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.php?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 = 'add.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>

    <script>
    $(document).ready(function(){
        $('.menu-item').removeClass('active');
        $('#item-menu').addClass('active');
    }); 
</script>
<?php include '../footer.php';?>