@echo off
setlocal

set "PROJECT_ROOT=%~dp0"
set "BACKEND_DIR=%PROJECT_ROOT%backend"
set "FRONTEND_DIR=%PROJECT_ROOT%frontend"

if not exist "%BACKEND_DIR%\artisan" (
    echo [ERROR] Backend directory or artisan file was not found.
    pause
    exit /b 1
)

if not exist "%FRONTEND_DIR%\package.json" (
    echo [ERROR] Frontend directory or package.json was not found.
    pause
    exit /b 1
)

set "PHP_EXE="
for /f "delims=" %%P in ('where php 2^>nul') do if not defined PHP_EXE set "PHP_EXE=%%P"

if not defined PHP_EXE (
    for /d %%D in ("%LOCALAPPDATA%\Microsoft\WinGet\Packages\PHP.PHP.8.4_*") do (
        if exist "%%~fD\php.exe" set "PHP_EXE=%%~fD\php.exe"
    )
)

if not defined PHP_EXE (
    echo [ERROR] PHP is not available in PATH.
    echo Install PHP 8.4 with: winget install --id PHP.PHP.8.4 --exact
    pause
    exit /b 1
)

for %%I in ("%PHP_EXE%") do set "PHP_DIR=%%~dpI"
set "PHP_EXT_DIR=%PHP_DIR%ext"
set "PHPRC=%BACKEND_DIR%"
set "PATH=%PHP_DIR%;%PATH%"

where npm.cmd >nul 2>&1
if errorlevel 1 (
    echo [ERROR] npm is not available in PATH.
    pause
    exit /b 1
)

if not exist "%BACKEND_DIR%\vendor\autoload.php" (
    echo [ERROR] Backend dependencies are missing. Run: composer install
    pause
    exit /b 1
)

if not exist "%FRONTEND_DIR%\node_modules" (
    echo [ERROR] Frontend dependencies are missing. Run: npm install
    pause
    exit /b 1
)

echo Starting backend at http://127.0.0.1:8000 ...
start "PM Backend" /D "%BACKEND_DIR%\public" cmd /k ""%PHP_EXE%" -S 127.0.0.1:8000 ..\vendor\laravel\framework\src\Illuminate\Foundation\resources\server.php"

echo Starting frontend ...
start "PM Frontend" /D "%FRONTEND_DIR%" cmd /k "npm run dev"

echo Backend and frontend were started in separate windows.
endlocal
