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

if(!isset($_GET['id']) || !isset($_POST['quantity']) || !isset($_POST['itemID']))
{
    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 saveOrderItem extends database
{
    public function insertData($data)
    {
        $item = $this->getPrice($data['item_id']);
        if(!$item)
        {
            return 0;
            exit;
        }
        
        $data['price'] = $item['price'] * $data['quantity'];
        return $this->insert('order_item', $data);
    }
    
    private function getPrice($itemID)
    {
        return $this->fetchRow('menu_item', ['id' => $itemID]);
    }
}
    
$quantity = $_POST['quantity'];
$itemID = $_POST['itemID'];

    $data['order_id'] = $id;
    $data['item_id'] = $itemID;
    $data['quantity'] = $quantity;
    
    $obj = new saveOrderItem();
    $res = $obj->insertData($data);
    if(!$res)
    {
        http_response_code(500);
        echo json_encode(['error_text' => 'Something Went Wrong']);
        exit;
    }
    
    http_response_code(200);
        echo json_encode(['message' => 'Item Added Successful']);
        exit;