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

try {

    // ✅ Get params (same style)
    $app_code        = isset($_GET['app_code']) ? strtoupper(trim($_GET['app_code'])) : 'CMMS';
    $platform        = isset($_GET['platform']) ? strtolower(trim($_GET['platform'])) : '';
    $env             = isset($_GET['env']) ? strtolower(trim($_GET['env'])) : 'beta';
    $current_version = isset($_GET['current_version']) ? trim($_GET['current_version']) : '';
    $site_cd         = isset($_GET['site_cd']) ? trim($_GET['site_cd']) : '';

    // ✅ Validate
    if ($platform === '' || $current_version === '') {
        returnError("Missing required parameters: platform / current_version");
    }

    if (!in_array($platform, ['android', 'ios'])) {
        returnError("Invalid platform. Use: android | ios");
    }

    if (!in_array($env, ['beta', 'prod'])) {
        $env = 'prod';
    }

    // ✅ SQL: site override first, then global
    $sql = "
    SELECT TOP 1 *
    FROM dbo.mobile_app_version (NOLOCK)
    WHERE is_active = 1
      AND app_code = ?
      AND platform = ?
      AND env = ?
      AND (
            ( ? <> '' AND site_cd = ? )
         OR ( ? = '' AND site_cd IS NULL )
         OR ( ? <> '' AND site_cd IS NULL )
      )
    ORDER BY
      CASE WHEN ( ? <> '' AND site_cd = ? ) THEN 0 ELSE 1 END,
      updated_dt DESC
    ";

    $params = array(
        $app_code,
        $platform,
        $env,

        $site_cd, $site_cd,
        $site_cd,
        $site_cd,

        $site_cd, $site_cd
    );

    $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);

    if (!$row) {
        returnData(array(
            "needs_update" => false,
            "update_type"  => "none",
            "force_update" => false,
            "message"      => "No active version rule found"
        ));
    }

    // ✅ Values from DB
    $latest_version = $row['latest_version'];
    $min_version    = $row['min_version'];
    $force_flag     = (int)$row['force_update'] === 1;
    $store_url      = $row['store_url'];
    $title          = !empty($row['update_title']) ? $row['update_title'] : "Update Available";
    $message        = !empty($row['update_message']) ? $row['update_message'] : "A new version is available. Please update.";

    // ✅ Version compare
    $isBelowMin    = version_compare($current_version, $min_version, '<');
    $isBelowLatest = version_compare($current_version, $latest_version, '<');

    $needs_update = false;
    $update_type  = "none";

    if ($isBelowMin || $force_flag) {
        $needs_update = true;
        $update_type  = "force";
    } else if ($isBelowLatest) {
        $needs_update = true;
        $update_type  = "optional";
    }

    // ✅ Format updated_dt safely
    $updated_dt = null;
    if (!empty($row['updated_dt'])) {
        if ($row['updated_dt'] instanceof DateTime) {
            $updated_dt = $row['updated_dt']->format('Y-m-d H:i:s');
        } else {
            $updated_dt = (string)$row['updated_dt'];
        }
    }

    // ✅ Final response
    returnData(array(
        "app_code" => $app_code,
        "platform" => $platform,
        "env" => $env,
        "site_cd" => $site_cd,

        "current_version" => $current_version,
        "latest_version" => $latest_version,
        "min_version" => $min_version,

        "needs_update" => $needs_update,
        "update_type" => $update_type,   // none | optional | force
        "force_update" => ($update_type === "force"),

        "title" => $title,
        "message" => $message,
        "store_url" => $store_url,

        "updated_dt" => $updated_dt
    ));

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


// ✅ SAME RESPONSE FORMAT AS YOUR API
function returnData($data) {
    $returnData = array(
        'status' => 'SUCCESS',
        'data' => $data
    );
    echo json_encode($returnData, JSON_UNESCAPED_UNICODE);
    exit();
}

function returnError($error_message) {
    $returnData = array(
        'status' => 'ERROR',
        'message' => $error_message,
        'data' => array()
    );
    echo json_encode($returnData, JSON_UNESCAPED_UNICODE);
    exit();
}
?>
