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

if(!isset($_GET['id']) || !isset($_POST['quantity']))
{
    http_response_code(500);
            echo json_encode(['error_text' => 'Something Went Wrong']);
            exit;
}
$id = $_GET['id'];

session_start();
require_once "../check_admin.php";
require_once '../database.php';

if(!isset($_SESSION['user_type']) || $_SESSION['user_type'] !='staff')
{
        http_response_code(403);
        echo json_encode(['error_text' => 'Authentication Error']);
        exit;
}

class updateOrderItem extends database
{
    public function updateData($quantity, $id)
    {
        $orderItem = $this->getOrderItem($id);
        if(!$orderItem)
        {
            return 0;
            exit;
        }
        
        $item = $this->getItem($orderItem['item_id']);
        if(!$item)
        {
            return 0;
            exit;
        }
        
        $price = $item['price'] * $quantity;
        
        return $this->update('order_item', ['quantity' => $quantity, 'price' => $price], ['id' => $id]);
    }
    
    private function getOrderItem($id)
    {
        return $this->fetchRow('order_item', ['id' => $id]);
    }
    
    private function getItem($id)
    {
        return $this->fetchRow('menu_item', ['id' => $id]);
    }
}

$quantity = $_POST['quantity'];

$obj = new updateOrderItem();
$res = $obj->updateData($quantity, $id);
if(!$res)
    {
        http_response_code(500);
        echo json_encode(['error_text' => 'Something Went Wrong']);
        exit;
    }
    
    http_response_code(200);
        echo json_encode(['message' => 'Item Updated Successful']);
        exit;