<?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 SaveOrder extends database
{
    public function index($data)
    {
        
        $this->dbh = $this->connectPDO1();
        $this->dbh->beginTransaction();
        try
        {
          $orderID = $this->insert1($this->dbh, 'orders',['order_status'=>'Pending']);
          if(!$orderID)
          {
              return 0;
              exit;
          }
          
        
          
          foreach($data as $value)
          {
              $itemID = $value['item_id'];
              $item = $this->getItem($itemID);
              if(!$item)
              {
                  return 0;
                  exit;
              }
             
              if(!is_numeric($value['quantity']))
              {
                   return 0;
                  exit;
              }
              
            
              
              
              $data1 = $value;
              $data1['price'] = $item['price'] * $data1['quantity'];
              $data1['order_id'] = $orderID;
              $res = $this->insert1($this->dbh, 'order_item',$data1);
              if(!$res)
              {
                  return 0;
                  exit;
              }
          }
          
           
          $this->dbh->commit();
            return 1;
            exit;
        }
        catch (PDOException $e) {
            // roll back transaction
            $this->dbh->rollback();
            return 0;
        }
    }
    
    private function getItem($itemID)
    {
        return $this->fetchRow('menu_item', ['id' => $itemID]);
    }
}
$obj =new SaveOrder();

if(!isset($_POST['data']))
{
    http_response_code(400);
    echo 'no input found';
    exit;
}

$data = $_POST['data'];

if(empty($data))
{
    http_response_code(400);
    echo 'no input found';
    exit;
}

$res =$obj -> index($data);
if(!$res)
{
  http_response_code(500);
  echo json_encode(['error_text' => 'Something went wrong']);
exit;
}
http_response_code(200);
  echo json_encode(['message' => 'Order Saved Successfully']);
?>