<?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']) : '';
$type      = isset($_GET['type']) ? strtoupper(trim($_GET['type'])) : 'ALL';

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

    // map type => query + label
    $typeMap = [
        "ASSET" => [
            "checked" => "ast_mst",
            "label"   => "ASSET",
            "sql"     => "SELECT * FROM ast_mst (NOLOCK) WHERE site_cd = ? AND ast_mst_asset_no = ?"
        ],
        "WORK_REQUEST" => [
            "checked" => "wkr_mst",
            "label"   => "WORK_REQUEST",
            "sql"     => "SELECT * FROM wkr_mst (NOLOCK) WHERE site_cd = ? AND wkr_mst_wr_no = ?"
        ],
        "WORK_ORDER" => [
            "checked" => "wko_mst",
            "label"   => "WORK_ORDER",
            "sql"     => "SELECT * FROM wko_mst (NOLOCK) WHERE site_cd = ? AND wko_mst_wo_no = ?"
        ],
        "INVENTORY" => [
            "checked" => "itm_mst",
            "label"   => "INVENTORY",
            "sql"     => "SELECT * FROM itm_mst (NOLOCK) WHERE site_cd = ? AND itm_mst_stockno = ?"
        ],
    ];

    $checked = [];

    // If type is specific, run ONLY that
    if ($type !== '' && $type !== 'ALL') {

        if (!isset($typeMap[$type])) {
            returnError("Invalid type. Use: ASSET / WORK_REQUEST / WORK_ORDER / INVENTORY / ALL");
        }

        $checked[] = $typeMap[$type]["checked"];
        $row = fetchOne($conn, $typeMap[$type]["sql"], [$site_cd, $scan_data]);

        if ($row) {
            returnData([
                "found_in"       => $typeMap[$type]["label"],
                "scan_data"      => $scan_data,
                "record"         => $row,
                "checked_steps"  => $checked
            ]);
        }

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

    // type = ALL (default) -> follow sequence
    $sequence = ["ASSET", "WORK_REQUEST", "WORK_ORDER", "INVENTORY"];

    foreach ($sequence as $t) {
        $checked[] = $typeMap[$t]["checked"];
        $row = fetchOne($conn, $typeMap[$t]["sql"], [$site_cd, $scan_data]);

        if ($row) {
            returnData([
                "found_in"       => $typeMap[$t]["label"],
                "scan_data"      => $scan_data,
                "record"         => $row,
                "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();
}
?>
