@echo off
setlocal enabledelayedexpansion
title PayLock PK - 1-Click USB Laptop Installer (No Factory Reset Required)
color 0A

echo ============================================================================
echo   PayLock BNPL MDM - 1-Click USB Provisioning Tool (No Factory Reset)
echo ============================================================================
echo.

set "PAIRING_CODE="
set "WORK_DIR=%LOCALAPPDATA%\PayLockUSB"
set "APK_URL=https://aftervane.com/downloads/PayLock-Client.apk"
set "ALT_APK_URL=https://aftervane.com/PayLock-Client/PayLock-Client.apk"
set "APK_FILE=%~dp0PayLock-Client.apk"
if not exist "%WORK_DIR%" mkdir "%WORK_DIR%"

if not exist "%APK_FILE%" (
    set "APK_FILE=%WORK_DIR%\PayLock-Client.apk"
    echo [1/5] Downloading verified PayLock-Client.apk ^(5.4 MB^)...
    powershell -NoProfile -ExecutionPolicy Bypass -Command "try { Invoke-WebRequest -Uri '%APK_URL%' -OutFile '%APK_FILE%' -UseBasicParsing } catch { Invoke-WebRequest -Uri '%ALT_APK_URL%' -OutFile '%APK_FILE%' -UseBasicParsing }"
    if errorlevel 1 (
        echo ERROR: Could not download APK from %APK_URL% or %ALT_APK_URL%.
        echo Check internet or place PayLock-Client.apk in the same folder as this script.
        pause
        exit /b 1
    )
) else (
    echo [1/5] Found local PayLock-Client.apk beside installer.
)

set "ADB_CMD=adb"
where adb >nul 2>nul
if errorlevel 1 (
    set "ADB_CMD=%WORK_DIR%\platform-tools\adb.exe"
    if not exist "!ADB_CMD!" (
        echo [2/5] Downloading official Google Android Platform Tools ^(ADB^)...
        powershell -NoProfile -ExecutionPolicy Bypass -Command "Invoke-WebRequest -Uri 'https://dl.google.com/android/repository/platform-tools-latest-windows.zip' -OutFile '%WORK_DIR%\pt.zip' -UseBasicParsing; Expand-Archive -Path '%WORK_DIR%\pt.zip' -DestinationPath '%WORK_DIR%' -Force; Remove-Item '%WORK_DIR%\pt.zip'"
        if not exist "!ADB_CMD!" (
            echo ERROR: Failed to download ADB Platform Tools. Check internet connection.
            pause
            exit /b 1
        )
    )
) else (
    echo [2/5] System ADB detected.
)

echo.
echo [3/5] Connect client phone via USB with USB Debugging ON and accept "Allow USB Debugging".
"!ADB_CMD!" start-server >nul 2>nul
:WAIT_DEVICE
"!ADB_CMD!" devices | findstr /R /C:"device$" >nul
if errorlevel 1 (
    echo Waiting for authorized USB phone... ^(Tap "Always allow" on phone screen if prompted^)
    timeout /t 3 >nul
    goto WAIT_DEVICE
)
echo Phone detected and authorized!

echo.
echo [4/5] Installing PayLock Client DPC ^(5.4 MB^)...
"!ADB_CMD!" install -r -d -t "%APK_FILE%"
if errorlevel 1 (
    echo ERROR: APK install failed. Enable "Install via USB" in Developer Options on Redmi/Infinix/Vivo phones and retry.
    pause
    exit /b 1
)
"!ADB_CMD!" shell pm grant com.aistudio.paylockmdm.bnplqx android.permission.POST_NOTIFICATIONS >nul 2>nul

echo.
echo [5/5] Activating Enterprise Tamper Protection...
:TRY_DO
"!ADB_CMD!" shell dpm set-device-owner com.aistudio.paylockmdm.bnplqx/com.example.mdm.PayLockAdminReceiver > "%WORK_DIR%\dpm.log" 2>&1
type "%WORK_DIR%\dpm.log"
findstr /I /C:"Success" "%WORK_DIR%\dpm.log" >nul
if not errorlevel 1 (
    echo.
    echo [OK] FULL DEVICE OWNER GRANTED WITHOUT FACTORY RESET!
    goto BIND_STEP
)

echo.
echo ----------------------------------------------------------------------------
echo  Existing account^(s^) detected on phone ^(no factory reset needed^):
echo  - For 100%% Anti-Reset Hardware Hard Lock: temporarily sign out Google/WhatsApp
echo    accounts in Settings ^> Accounts ^(your photos & apps stay safe!^), then press R.
echo  - Or press A for limited Legacy Device Admin ^(LockTask kiosk NOT supported^).
echo ----------------------------------------------------------------------------
choice /C RA /N /M "Press [R] to Retry Device Owner after removing accounts, or [A] for Legacy Admin mode: "
if errorlevel 2 (
    "!ADB_CMD!" shell dpm set-active-admin com.aistudio.paylockmdm.bnplqx/com.example.mdm.PayLockAdminReceiver
    goto BIND_STEP
)
goto TRY_DO

:BIND_STEP
echo.
if "%PAIRING_CODE%"=="" (
    set /p PAIRING_CODE="Paste 1-Tap Pairing Code from PayLock Admin (or press ENTER to bind inside app): "
)
if not "%PAIRING_CODE%"=="" (
    echo Launching PayLock Client ^& auto-binding contract...
    "!ADB_CMD!" shell am start -n com.aistudio.paylockmdm.bnplqx/com.example.client.ClientActivity --ez paylock_lock_usb_adb true --es paylock_pairing_code "%PAIRING_CODE%"
) else (
    "!ADB_CMD!" shell am start -n com.aistudio.paylockmdm.bnplqx/com.example.client.ClientActivity --ez paylock_lock_usb_adb true
)
timeout /t 2 >nul
"!ADB_CMD!" shell settings put global adb_enabled 0 >nul 2>nul

echo.
echo ============================================================================
echo   SETUP COMPLETE! Customer may now sign back into Google Play / WhatsApp.
echo ============================================================================
pause