<?php

// ===== CORS ALLOW ALL =====
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

#############################################################################

require_once 'vendor/autoload.php';

require_once 'model/HangHoa.php';
require_once 'model/DichVu.php';

require_once 'controller/ResponseHelper.php';

use Symfony\Component\HttpFoundation\Request;


$request = Request::createFromGlobals();

if (!in_array($request->getMethod(),['POST','GET'])) {
    ResponseHelper::responseError("Only POST method allowed");
}  

// Đọc dữ liệu JSON gửi lên
$data = json_decode($request->getContent(), true);

// Kiểm tra dữ liệu hợp lệ
if (!$data || !isset($data['action'])) {
    ResponseHelper::responseError("Invalid input, required field: action");
}

$hangHoa = new HangHoa();
$dichVu = new DichVu();

#############################################################################

//Function autoComplete item trong Bill
if ($data['action'] == 'autoCompleteBillItem'){

    //Xoá action để thêm data vào 
    unset($data['action']);

    if (!empty($data['kw'])){
        try{
            
            $result2 = $dichVu->autoCompleteDichVu($data['kw']);
            $result1 = $hangHoa->autoCompleteHangHoa($data['kw']);

            $result = array_merge($result1, $result2);
            
            ResponseHelper::responseSuccess($result);
        } catch (Throwable  $e){
            ResponseHelper::responseSuccess(null);
        }
        
    } else {
        ResponseHelper::responseSuccess(null);
    }
}

//Function autoComplete Dịch Vụ với option
if ($data['action']== 'autoCompleteDichVu'){

    //Xoá action để thêm data vào 
    unset($data['action']);

    if (!empty($data['kw'])){
        try{
            $result = $dichVu->autoCompleteDichVu($data['kw']);
            ResponseHelper::responseSuccess($result);
        } catch (Throwable  $e){
            ResponseHelper::responseSuccess(null);
        }
    } else {
        ResponseHelper::responseSuccess(null);
    }
}

?>