@echo off
title Pharmacy Financial System - Local Sync Server (Port 8080)
cd /d "%~dp0"

set "SELF_FILE=%~f0"
set "SELF_DIR=%~dp0"
set "STARTUP_VBS=%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup\PharmacySyncServerSilent.vbs"

if /i "%~1"=="--disable-autostart" goto :disable_autostart
if /i "%~1"=="--silent" goto :run_ps_server
if /i "%~1"=="--console" (
    call :ensure_autostart
    goto :run_ps_server
)

REM Default mode (double-click): enable Windows Auto-Start + ensure server is running in background
call :ensure_autostart

netstat -ano | findstr ":8080 " | findstr "LISTENING" >nul 2>nul
if %errorlevel%==0 (
    echo ==============================================================
    echo   [OK] Local Sync Server is ALREADY running on port 8080!
    echo   [OK] Windows Auto-Start is ENABLED ^(runs silently on boot^).
    echo   You can now use the Pharmacy Vercel site ^& Juleb POS.
    echo ==============================================================
    timeout /t 4 >nul
    exit /b 0
)

echo Starting Pharmacy Local Sync Server in background...
wscript.exe "%STARTUP_VBS%"

powershell -NoProfile -ExecutionPolicy Bypass -Command "$ok = $false; for ($i = 0; $i -lt 24; $i++) { Start-Sleep -Milliseconds 250; try { $r = Invoke-RestMethod -Uri 'http://127.0.0.1:8080/api/ping' -TimeoutSec 1; if ($r.ok) { $ok = $true; break } } catch {} }; if ($ok) { exit 0 } else { exit 1 }"
if %errorlevel%==0 (
    echo ==============================================================
    echo   [OK] Local Sync Server is RUNNING in background ^(Port 8080^)
    echo   [OK] Windows Auto-Start is ENABLED ^(starts silently on login^)
    echo   - You can close this window; the server stays active.
    echo   - To disable Auto-Start later, run with: --disable-autostart
    echo ==============================================================
    timeout /t 5 >nul
    exit /b 0
)

echo [!] Background launch did not respond in time; starting in console mode...
goto :run_ps_server

:ensure_autostart
> "%STARTUP_VBS%" (
    echo Set WshShell = CreateObject^("WScript.Shell"^)
    echo WshShell.CurrentDirectory = "%SELF_DIR%"
    echo WshShell.Run """%SELF_FILE%"" --silent", 0, False
)
exit /b 0

:disable_autostart
if exist "%STARTUP_VBS%" (
    del /f /q "%STARTUP_VBS%"
    echo ==============================================================
    echo   [REMOVED] Windows Auto-Start has been disabled.
    echo   Run Pharmacy_Local_Server.bat again anytime to re-enable it.
    echo ==============================================================
) else (
    echo ==============================================================
    echo   [INFO] Windows Auto-Start is already disabled.
    echo ==============================================================
)
pause
exit /b 0

:run_ps_server
powershell -NoProfile -ExecutionPolicy Bypass -Command "$raw = [System.IO.File]::ReadAllText($env:SELF_FILE, [System.Text.Encoding]::UTF8); $idx = $raw.LastIndexOf('# === PS_SERVER_START ==='); Invoke-Expression $raw.Substring($idx)"
if %errorlevel% neq 0 if /i not "%~1"=="--silent" pause
exit /b 0

# === PS_SERVER_START ===
$ErrorActionPreference = "Stop"
$Port = if ($env:PORT) { [int]$env:PORT } else { 8080 }
$RootDir = if ($env:SELF_DIR) { $env:SELF_DIR.TrimEnd('\') } else { (Get-Location).Path }

# If run from project folder that already has data/, use data/, otherwise PharmacyData/
$LegacyDataDir = Join-Path $RootDir "data"
$DataDir = if (Test-Path (Join-Path $LegacyDataDir "pharmacy_db.json")) { $LegacyDataDir } else { Join-Path $RootDir "PharmacyData" }
$DbFile = Join-Path $DataDir "pharmacy_db.json"
$DbTmpFile = Join-Path $DataDir "pharmacy_db.tmp.json"
$DbBackupFile = Join-Path $DataDir "pharmacy_db.backup.json"
$PosSessionFile = Join-Path $DataDir "pos_sessions.json"
$PosSessionTmpFile = Join-Path $DataDir "pos_sessions.tmp.json"
$Utf8NoBom = New-Object System.Text.UTF8Encoding($false)

if (-not (Test-Path $DataDir)) {
    New-Item -ItemType Directory -Path $DataDir -Force | Out-Null
}

function Set-CorsAndPnaHeaders($Request, $Response) {
    $Origin = $Request.Headers["Origin"]
    if ([string]::IsNullOrEmpty($Origin) -or $Origin -eq "null") {
        $Response.Headers["Access-Control-Allow-Origin"] = "*"
    } else {
        $Response.Headers["Access-Control-Allow-Origin"] = $Origin
        $Response.Headers["Vary"] = "Origin"
    }
    $Response.Headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS"
    $Response.Headers["Access-Control-Allow-Headers"] = "Content-Type, Access-Control-Request-Private-Network"
    $Response.Headers["Access-Control-Allow-Private-Network"] = "true"
    $Response.Headers["Cache-Control"] = "no-store, no-cache, must-revalidate"
}

function Send-JsonResponse($Request, $Response, [int]$StatusCode, [string]$JsonText) {
    Set-CorsAndPnaHeaders $Request $Response
    $Bytes = $Utf8NoBom.GetBytes($JsonText)
    $Response.StatusCode = $StatusCode
    $Response.ContentType = "application/json; charset=utf-8"
    $Response.ContentLength64 = $Bytes.Length
    $Response.OutputStream.Write($Bytes, 0, $Bytes.Length)
    $Response.OutputStream.Close()
}

function Read-RequestBodyUtf8($Request) {
    $Reader = New-Object System.IO.StreamReader($Request.InputStream, $Utf8NoBom)
    $Body = $Reader.ReadToEnd()
    $Reader.Close()
    if ($null -eq $Body) { return "" }
    return $Body.Trim()
}

function Read-DbEnvelope {
    foreach ($Candidate in @($DbFile, $DbBackupFile)) {
        if (-not (Test-Path $Candidate)) { continue }
        try {
            $Raw = [System.IO.File]::ReadAllText($Candidate, $Utf8NoBom).Trim()
            if ([string]::IsNullOrWhiteSpace($Raw)) { continue }
            $null = $Raw | ConvertFrom-Json
            $UpdMatch = [regex]::Match($Raw, '"updatedAt"\s*:\s*(\d+)')
            if ($UpdMatch.Success) {
                $Upd = [int64]$UpdMatch.Groups[1].Value
            } else {
                $Upd = [int64]([DateTimeOffset](Get-Item $Candidate).LastWriteTimeUtc).ToUnixTimeMilliseconds()
            }
            return @{ exists = $true; updatedAt = $Upd; rawJson = $Raw }
        } catch {}
    }
    return @{ exists = $false; updatedAt = 0; rawJson = "null" }
}

function Read-PosSessionRaw {
    if (Test-Path $PosSessionFile) {
        try {
            $Raw = [System.IO.File]::ReadAllText($PosSessionFile, $Utf8NoBom).Trim()
            if (-not [string]::IsNullOrWhiteSpace($Raw)) {
                $null = $Raw | ConvertFrom-Json
                return $Raw
            }
        } catch {}
    }
    return $null
}

$Listener = New-Object System.Net.HttpListener
$Listener.Prefixes.Add("http://localhost:$Port/")
$Listener.Prefixes.Add("http://127.0.0.1:$Port/")
$Listener.Start()

Write-Host "==============================================================" -ForegroundColor Cyan
Write-Host "  Pharmacy Financial System - Local Sync Server is ACTIVE!" -ForegroundColor Green
Write-Host "==============================================================" -ForegroundColor Cyan
Write-Host "  Status          : Connected & Ready for All Browsers (Vercel & Juleb POS)" -ForegroundColor Yellow
Write-Host "  Local Endpoint  : http://localhost:$Port"
Write-Host "  Database Folder : $DataDir"
Write-Host "  Database File   : $DbFile"
Write-Host "--------------------------------------------------------------"
Write-Host "  Auto-Start enabled. Keep running in background."
Write-Host "==============================================================" -ForegroundColor Cyan

try {
    while ($Listener.IsListening) {
        $Context = $Listener.GetContext()
        $Req = $Context.Request
        $Res = $Context.Response

        Set-CorsAndPnaHeaders $Req $Res

        if ($Req.HttpMethod -eq "OPTIONS") {
            $Res.StatusCode = 204
            $Res.OutputStream.Close()
            continue
        }

        $PathName = [System.Uri]::UnescapeDataString($Req.Url.AbsolutePath)

        if ($PathName -eq "/api/ping" -and $Req.HttpMethod -eq "GET") {
            Send-JsonResponse $Req $Res 200 "{`"ok`":true,`"port`":$Port,`"posBridge`":true}"
            continue
        }

        if ($PathName -eq "/api/pos/session" -and $Req.HttpMethod -eq "GET") {
            $PosRaw = Read-PosSessionRaw
            if ($null -ne $PosRaw -and $PosRaw.StartsWith("{")) {
                $Json = "{`"ok`":true," + $PosRaw.Substring(1)
            } else {
                $Json = "{`"ok`":true,`"updatedAt`":0,`"activeSession`":null,`"lastClosed`":null}"
            }
            Send-JsonResponse $Req $Res 200 $Json
            continue
        }

        if ($PathName -eq "/api/pos/session-open" -and $Req.HttpMethod -eq "POST") {
            try {
                $Trimmed = Read-RequestBodyUtf8 $Req
                if ([string]::IsNullOrWhiteSpace($Trimmed)) {
                    Send-JsonResponse $Req $Res 400 "{`"ok`":false,`"error`":`"Empty body`"}"
                    continue
                }
                $null = $Trimmed | ConvertFrom-Json
                $NowMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
                $OutJson = "{`"updatedAt`":$NowMs,`"activeSession`":$Trimmed,`"lastClosed`":null}"
                [System.IO.File]::WriteAllText($PosSessionTmpFile, $OutJson, $Utf8NoBom)
                Move-Item -Path $PosSessionTmpFile -Destination $PosSessionFile -Force
                Send-JsonResponse $Req $Res 200 "{`"ok`":true,`"updatedAt`":$NowMs}"
            } catch {
                $ErrMsg = ($_.Exception.Message -replace '"', '\"')
                Send-JsonResponse $Req $Res 500 "{`"ok`":false,`"error`":`"$ErrMsg`"}"
            }
            continue
        }

        if ($PathName -eq "/api/pos/session-close" -and $Req.HttpMethod -eq "POST") {
            try {
                $Trimmed = Read-RequestBodyUtf8 $Req
                $LastClosedRaw = "null"
                if (-not [string]::IsNullOrWhiteSpace($Trimmed)) {
                    $null = $Trimmed | ConvertFrom-Json
                    $LastClosedRaw = $Trimmed
                }
                $NowMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
                $OutJson = "{`"updatedAt`":$NowMs,`"activeSession`":null,`"lastClosed`":$LastClosedRaw}"
                [System.IO.File]::WriteAllText($PosSessionTmpFile, $OutJson, $Utf8NoBom)
                Move-Item -Path $PosSessionTmpFile -Destination $PosSessionFile -Force
                Send-JsonResponse $Req $Res 200 "{`"ok`":true,`"updatedAt`":$NowMs}"
            } catch {
                $ErrMsg = ($_.Exception.Message -replace '"', '\"')
                Send-JsonResponse $Req $Res 500 "{`"ok`":false,`"error`":`"$ErrMsg`"}"
            }
            continue
        }

        if ($PathName -eq "/api/state" -and $Req.HttpMethod -eq "GET") {
            $Db = Read-DbEnvelope
            $ExistsBool = if ($Db.exists) { "true" } else { "false" }
            if ($Req.QueryString["meta"] -eq "1") {
                $Json = "{`"ok`":true,`"exists`":$ExistsBool,`"updatedAt`":$($Db.updatedAt)}"
                Send-JsonResponse $Req $Res 200 $Json
                continue
            }
            if (-not $Db.exists) {
                $Json = "{`"ok`":true,`"exists`":false,`"updatedAt`":0,`"state`":null}"
            } else {
                $Raw = $Db.rawJson
                if ($Raw -match '(?s)^\{\s*"updatedAt"\s*:.*?"state"\s*:') {
                    $Json = "{`"ok`":true,`"exists`":true," + $Raw.Substring(1)
                } elseif ($Raw -match '(?s)^\{\s*"state"\s*:') {
                    $Json = "{`"ok`":true,`"exists`":true,`"updatedAt`":$($Db.updatedAt)," + $Raw.Substring(1)
                } else {
                    $Json = "{`"ok`":true,`"exists`":true,`"updatedAt`":$($Db.updatedAt),`"state`":$Raw}"
                }
            }
            Send-JsonResponse $Req $Res 200 $Json
            continue
        }

        if ($PathName -eq "/api/state" -and $Req.HttpMethod -eq "POST") {
            try {
                $Trimmed = Read-RequestBodyUtf8 $Req
                if ([string]::IsNullOrWhiteSpace($Trimmed)) {
                    Send-JsonResponse $Req $Res 400 "{`"ok`":false,`"error`":`"Empty body`"}"
                    continue
                }
                # Validate JSON syntax without re-serializing (avoids PowerShell 5.1 DateTime/array mangling)
                $null = $Trimmed | ConvertFrom-Json
                $NowMs = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()

                if ($Trimmed -match '(?s)^\{\s*"state"\s*:') {
                    $OutJson = "{`"updatedAt`":$NowMs," + $Trimmed.Substring(1)
                } else {
                    $OutJson = "{`"updatedAt`":$NowMs,`"state`":$Trimmed}"
                }

                if (Test-Path $DbFile) {
                    Copy-Item -Path $DbFile -Destination $DbBackupFile -Force -ErrorAction SilentlyContinue
                }
                [System.IO.File]::WriteAllText($DbTmpFile, $OutJson, $Utf8NoBom)
                Move-Item -Path $DbTmpFile -Destination $DbFile -Force

                Send-JsonResponse $Req $Res 200 "{`"ok`":true,`"updatedAt`":$NowMs}"
            } catch {
                $ErrMsg = ($_.Exception.Message -replace '"', '\"')
                Send-JsonResponse $Req $Res 500 "{`"ok`":false,`"error`":`"$ErrMsg`"}"
            }
            continue
        }

        # Friendly status page if opened directly in browser
        $HtmlStatus = "<!DOCTYPE html><html lang='ar' dir='rtl'><head><meta charset='UTF-8'><title>Pharmacy Sync Server</title><style>body{font-family:Segoe UI,Tahoma,sans-serif;background:#0f172a;color:#f8fafc;display:flex;align-items:center;justify-content:center;height:100vh;margin:0} .box{background:#1e293b;border:2px solid #10b981;border-radius:16px;padding:32px;max-width:520px;text-align:center;box-shadow:0 20px 40px rgba(0,0,0,.4)} h2{color:#34d399;margin-top:0} code{background:#0f172a;padding:4px 8px;border-radius:6px;color:#38bdf8}</style></head><body><div class='box'><h2>&#9989; Local Sync Server is Active</h2><p>Port <code>8080</code> is running in the background with Windows Auto-Start enabled. Open your Pharmacy Vercel website or Juleb POS in Chrome / Edge.</p></div></body></html>"
        $HtmlBytes = $Utf8NoBom.GetBytes($HtmlStatus)
        $Res.StatusCode = 200
        $Res.ContentType = "text/html; charset=utf-8"
        $Res.ContentLength64 = $HtmlBytes.Length
        $Res.OutputStream.Write($HtmlBytes, 0, $HtmlBytes.Length)
        $Res.OutputStream.Close()
    }
} finally {
    $Listener.Stop()
}
