<?php
require_once('config.php');

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

$site_cd   = isset($_GET['site_cd']) ? trim($_GET['site_cd']) : '';
$scan_data = isset($_GET['scan_data']) ? trim($_GET['scan_data']) : '';

if ($site_cd === '' || $scan_data === '') {
    returnError("Missing required parameters: site_cd / scan_data");
}

try {

    function fetchOne($conn, $sql, $params = []) {
        $stmt = sqlsrv_query($conn, $sql, $params);
        if ($stmt === false) {
            throw new Exception("DB Error: " . print_r(sqlsrv_errors(), true));
        }
        $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
        sqlsrv_free_stmt($stmt);
        return $row ?: null;
    }

    $checked = [];

    // 1) ASSET
    $checked[] = "ast_mst";
    $sql_ast = "SELECT * FROM ast_mst (NOLOCK) WHERE site_cd = ? AND ast_mst_asset_no = ?";
    $asset = fetchOne($conn, $sql_ast, [$site_cd, $scan_data]);
    if ($asset) {
        returnData([
            "found_in" => "ASSET",
            "scan_data" => $scan_data,
            "record" => $asset,
            "checked_steps" => $checked
        ]);
    }

    // 2) WORK REQUEST
    $checked[] = "wkr_mst";
    $sql_wkr = "SELECT * FROM wkr_mst (NOLOCK) WHERE site_cd = ? AND wkr_mst_wr_no = ?";
    $wkr = fetchOne($conn, $sql_wkr, [$site_cd, $scan_data]);
    if ($wkr) {
        returnData([
            "found_in" => "WORK_REQUEST",
            "scan_data" => $scan_data,
            "record" => $wkr,
            "checked_steps" => $checked
        ]);
    }

    // 3) WORK ORDER
    $checked[] = "wko_mst";
    $sql_wko = "SELECT * FROM wko_mst (NOLOCK) WHERE site_cd = ? AND wko_mst_wo_no = ?";
    $wko = fetchOne($conn, $sql_wko, [$site_cd, $scan_data]);
    if ($wko) {
        returnData([
            "found_in" => "WORK_ORDER",
            "scan_data" => $scan_data,
            "record" => $wko,
            "checked_steps" => $checked
        ]);
    }

    // 4) INVENTORY
    $checked[] = "itm_mst";
    $sql_itm = "SELECT * FROM itm_mst (NOLOCK) WHERE site_cd = ? AND itm_mst_stockno = ?";
    $itm = fetchOne($conn, $sql_itm, [$site_cd, $scan_data]);
    if ($itm) {
        returnData([
            "found_in" => "INVENTORY",
            "scan_data" => $scan_data,
            "record" => $itm,
            "checked_steps" => $checked
        ]);
    }

    returnError("No record found for scan_data: $scan_data", $checked);

} catch (Exception $e) {
    returnError($e->getMessage());
}

function returnData($payload) {
    echo json_encode([
        'status' => 'SUCCESS',
        'data'   => $payload
    ]);
    exit();
}

function returnError($error_message, $checked_steps = []) {
    echo json_encode([
        'status'  => 'ERROR',
        'message' => $error_message,
        'checked_steps' => $checked_steps,
        'data'    => []
    ]);
    exit();
}
?>
