' Agente de impresión Egurrola — inicio oculto (sin ventana de consola).
' Funciona en cualquier carpeta: todas las rutas se resuelven desde la ubicación de este archivo.

Option Explicit

Dim fso, shell, agentRoot, runPhp, phpExe, logDir, logFile, cmd

Set fso = CreateObject("Scripting.FileSystemObject")
Set shell = CreateObject("WScript.Shell")

agentRoot = fso.GetParentFolderName(WScript.ScriptFullName)
runPhp = agentRoot & "\bin\run.php"
logDir = agentRoot & "\storage"

If Not fso.FolderExists(logDir) Then
    fso.CreateFolder logDir
End If

logFile = logDir & "\agent-startup.log"

If Not fso.FileExists(runPhp) Then
    Call WriteLog(logFile, "ERROR: No se encontró " & runPhp)
    WScript.Quit 1
End If

phpExe = ResolvePhpExe(agentRoot)
If phpExe = "" Then
    Call WriteLog(logFile, "ERROR: No se encontró php.exe. Cree php-path.txt con la ruta completa o agregue PHP al PATH.")
    WScript.Quit 1
End If

shell.CurrentDirectory = agentRoot

' 0 = ventana oculta
cmd = """" & phpExe & """ """ & runPhp & """"
Call WriteLog(logFile, "Iniciando agente: " & cmd)
shell.Run cmd, 0, False

Function ResolvePhpExe(root)
    Dim pathFile, stream, line, candidates, i, p

    pathFile = root & "\php-path.txt"
    If fso.FileExists(pathFile) Then
        Set stream = fso.OpenTextFile(pathFile, 1, False)
        line = Trim(stream.ReadLine())
        stream.Close
        If line <> "" And fso.FileExists(line) Then
            ResolvePhpExe = line
            Exit Function
        End If
    End If

    candidates = Array( _
        root & "\php\php.exe", _
        "C:\php\php.exe", _
        "C:\xampp\php\php.exe", _
        "C:\laragon\bin\php\php-8.2.12-Win32-vs16-x64\php.exe", _
        "C:\laragon\bin\php\php-8.3.0-Win32-vs16-x64\php.exe" _
    )

    For i = 0 To UBound(candidates)
        p = candidates(i)
        If fso.FileExists(p) Then
            ResolvePhpExe = p
            Exit Function
        End If
    Next

    ResolvePhpExe = FindPhpInPath()
End Function

Function FindPhpInPath()
    Dim exec, line
    On Error Resume Next
    Set exec = shell.Exec("cmd /c where php 2>nul")
    Do While exec.Status = 0
        WScript.Sleep 50
    Loop
    line = Trim(exec.StdOut.ReadLine())
    If line <> "" And fso.FileExists(line) Then
        FindPhpInPath = line
    Else
        FindPhpInPath = ""
    End If
    On Error GoTo 0
End Function

Sub WriteLog(path, message)
    Dim stream
    On Error Resume Next
    Set stream = fso.OpenTextFile(path, 8, True)
    stream.WriteLine "[" & Now & "] " & message
    stream.Close
    On Error GoTo 0
End Sub
