<?php
include_once "../../includes/config.php";
include_once "../../includes/database.php";
include_once "../../includes/validation.php";
include_once "../../includes/Helper.php";
include_once "../../includes/ajax/check_session_ajax.php";
require_once '../../includes/ajax/check_edit_page_ajax.php';

include_once "../../includes/auth.php";
$auth = array('manager');
$authRes = checkAuth($auth, $user);
if(!$authRes)
{
    http_response_code(401);
	echo json_encode(array('error_text' => 'Authntication Error'));
	exit;
}

include_once "../../includes/ajax/check_paid_ajax.php";

class updateOrderItem extends database
{
    public function updateData($quantity, $id)
    {
        $orderItem = $this->getOrderItem($id);
        if(!$orderItem)
        {
            return 0;
            exit;
        }
        
        $item = $this->getItem($orderItem['cl_menu_id']);
        if(!$item)
        {
            return 0;
            exit;
        }
        
        $price = $item['cl_price'] * $quantity;
        
        return $this->update('tb_order_item', ['cl_quantity' => $quantity, 'cl_price' => $price], ['cl_id' => $id]);
    }
    
    private function getOrderItem($id)
    {
        return $this->fetchRow('tb_order_item', ['cl_id' => $id]);
    }
    
    private function getItem($id)
    {
        return $this->fetchRow('tb_menu', ['cl_id' => $id]);
    }
    
    public function getOrder($id, $userID, $companyID)
    {
        $sql = ' SELECT * FROM tb_order o INNER JOIN tb_order_item oi ON o.cl_id=oi.cl_order_id WHERE o.deleted_at IS NULL AND oi.deleted_at IS NULL AND oi.cl_id=? AND o.cl_user_id=? AND o.cl_company_id=? ';
        return $this->callQueryRow($sql, [$id, $userID,$companyID]);
    }
}

$quantity = $_POST['quantity'];

$obj = new updateOrderItem();

$order = $obj->getOrder($id, $user['cl_id'], $user['cl_user_id']);
if(!$order)
{
    http_response_code(500);
    echo json_encode(['error_text' => 'Something Went Wrong']);
    exit;
}

$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;