<?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";

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


if($user['cl_type'] !='manager')
{
        http_response_code(403);
        echo json_encode(['error_text' => 'Authentication Error']);
        exit;
}
    
class saveOrderItem extends database
{
    public function insertData($data, $userID, $companyID)
    {
        $this->dbh = $this->connectPDO1();
        $this->dbh->beginTransaction();
        try
        {
        
            $item = $this->getPrice($data['cl_menu_id'], $companyID);
            if(!$item)
            {
                $this->dbh->rollback();
                return 0;
            }

            $data['cl_price'] = $item['cl_price'] * $data['cl_quantity'];
            $orderItemID =  $this->insert('tb_order_item', $data);
            if(!$orderItemID)
            {
                $this->dbh->rollback();
                return 0;
            }
            
            
            
            
            $this->dbh->commit();
            return $orderItemID;
        }
        catch (PDOException $e) {
            // roll back transaction
            $this->dbh->rollback();
            return 0;
        }
    }
    
    private function getPrice($itemID,$companyID)
    {
        return $this->fetchRow('tb_menu', ['cl_id' => $itemID,'cl_user_id' => $companyID]);
    }
    
    
    public function getOrder($id, $userID, $companyID)
    {
        return $this->fetchRow('tb_order', ['cl_user_id' => $userID, 'cl_company_id' => $companyID, 'cl_id' => $id]);
    }
}
    
$quantity = $_POST['quantity'];
$itemID = $_POST['itemID'];

    $data['cl_order_id'] = $id;
    $data['cl_menu_id'] = $itemID;
    $data['cl_quantity'] = $quantity;
    
    $obj = new saveOrderItem();
    
    $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->insertData($data, $user['cl_id'], $user['cl_user_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 Added Successful']);
        exit;