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

session_start();
require_once "check_admin.php";
if(!isset($_SESSION['user_type']) || $_SESSION['user_type'] !='staff')
    {
            header('Location: ../admin/');
            exit;
    }
require_once 'database.php';
class new_category extends database
{
   

	public function GetAll()
    {
        
        return $this->fetchAll('menu_item');
    }
   	public function GetAllorders()
    {
        $sql = 'SELECT o.*, GROUP_CONCAT("<div >",mi.name, " ", "<br/> Quantity: " , oi.quantity, "<br/> Price:", oi.price, "</div>","<br/>") AS items, SUM(oi.price) AS total_price FROM orders o inner join order_item oi ON o.id=oi.order_id INNER JOIN menu_item mi ON oi.item_id=mi.id WHERE o.deleted_at IS NULL AND oi.deleted_at IS NULL GROUP BY o.id ORDER BY o.created_at DESC LIMIT 0, 50';
        return $this->callQuery($sql);
        //return $this->fetchAll('orders');
    }
   	public function OrderItems($id)
    {
        $where['order_id'] = $id;
        return $this->fetchAll('order_item',$where);
    }
    public function ItemData($id)
    {
        $where['id'] = $id;
        return $this->fetchRow('menu_item',$where);
    }
    
    public function insertData()
    {
        return $this->insert('orders', ['order_status' => 'New']);
    }
   
}

$cat = new new_category();
if(isset($_POST['submit']))
{
    $orderID = $cat->insertData();
    if($orderID)
    {
        header('Location: edit_restaurant_order.php?id=' . $orderID);
    }
}



 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>Create Order</h1>
                    </div>
                    <div class="clearfix"></div>
                    <div class="col-sm-12">
                        <div class="row">
                            <form method="post" class="col-12 hcenter">
                                <button type="submit" name="submit" class="btn btn-success ">Create a New Order</button>
                            </form>
                        </div>
                    	
                    </div>
                </div>
                
                
            </div>
        </div>
	</div>
</div>
    <script>
     $(document).ready(function(){
        $('#remove').click(function(){
            var parent = $(this).parents('tr').first();
            var conf = confirm("Are you sure, you want to delete this order?");
            if(conf)
            {
                var href = $(this).attr('data-href');
                $.post(href, function(res){
                    alert("Deletion Successful");
                    $(parent).remove();
                },'json').fail(function(xhr){
                   alert(xhr.responseJSON);
                },'json');
            }
        });
        
        $('.complete').click(function(){
          
            var conf = confirm("Are you sure, you want to complete this order?");
            if(conf)
            {
                var href = $(this).attr('data-href');
                $.post(href, function(res){
                    alert("Completion Successful");
                   location.reload();
                },'json').fail(function(xhr){
                   alert(xhr.responseJSON);
                },'json');
            }
        });
        
         $('.pending').click(function(){
          
            var conf = confirm("Are you want to make this order pending?");
            if(conf)
            {
                var href = $(this).attr('data-href');
                $.post(href, function(res){
                    alert("Change to pending stage");
                   location.reload();
                },'json').fail(function(xhr){
                   alert(xhr.responseJSON);
                },'json');
            }
        });
    });
	
    
    $(document).ready(function(){
        $('.btn-add').click(function(){
            var html='<tr>'+
												'<td>'+
												'<select class="form-control item_id">'+
												    '<option value="">---Select----</option>'+
												    <?php
                											 $items = $cat->GetAll();
                											 foreach($items as $u)
                											 {
                											 
                											?>
                											'<option cluster-price="<?php echo htmlspecialchars($u['price']) ?>" value="<?php echo htmlspecialchars($u['id']);?>"><?php echo htmlspecialchars($u['name']) . ' Price:' . htmlspecialchars($u['price']);?></option>'+	
                												<?php
            											
            											 }
            											?>
												'</select>'+
												'</td>'+
												
												
												'<td width="20%"><input type="text" class="form-control quantity"  value="0"/></td>'+
												'<td class="price">	</td>' +
											    '<td><button class="btn btn-danger btn-remove">-</button></td>'+
											'</tr>';
			$('.order-table tbody').append(html);
        });
    });
    $(document).on('click','.btn-remove',function(){
       var parent=$(this).parents('tr').first();
       $(parent).remove();
    });
    </script>

    <script>
      function submitOrder(data)
      {
          $('.btn-save').attr('disabled', 'disabled');
          $.post('save_order.php',{data:data},function(){
              location.reload();
          },'json')
         .fail(function(xhr) {
              alert('SOmething went wrong. Please try again');
              $('.btn-save').removeAttr('disabled');
          });
      }
      $(document).ready(function(){
          $('.btn-save').click(function(){
              var data = new Object();
              var count =0;
              $('.order-table tbody tr').each(function(i,value){
                  data[count] = new Object();
                  data[count]['item_id'] = $(value).find('.item_id').val();
                  data[count]['quantity'] = $(value).find('.quantity').val();
                  count++;
              });
              submitOrder(data);
          });
          
      });
      
    $(document).ready(function(){
        $('.activ-cat').removeClass('activ-cat');
        $('#order-menu').addClass('activ-cat');
        
        
        
    }); 
    
    function findTotalSum()
    {
        var total_price = 0;
        
        $('.price').each(function(i, value){
            var parent = $(value).parents('tr').first();
            var quantity = $(parent).find('.quantity').val();
            var price = $(parent).find('.item_id option:selected').attr('cluster-price');
            $(parent).find('.price').text(quantity * price);
            total_price+= Number(quantity * price);
        });
        
        $('#total_sum').text(total_price);
    }
    
    $(document).on('change','.item_id', function(){
            var parent = $(this).parents('tr').first();
            var value = $(this).find('option:selected').attr('cluster-price');
            var quantity = $(parent).find('.quantity').val();
            console.log(value);
            $(parent).find('.price').text(value * quantity);
            
            findTotalSum();
        })
        
        $(document).on('change','.quantity', function(){
            findTotalSum();
        });
</script>
<?php include 'footer.php';?>