# Grocery API Setup Script for Laragon
# This script sets up the Laravel project with PHP 8.2+

Write-Host "=== Grocery API Setup ===" -ForegroundColor Green
Write-Host ""

# Check if PHP 8.2+ is available
$php82Path = "D:\laragon\bin\php\php-8.2.28-nts-Win32-vs16-x64\php.exe"
$php83Path = "D:\laragon\bin\php\php-8.3.26-Win32-vs16-x64\php.exe"

if (Test-Path $php82Path) {
    $phpExe = $php82Path
    Write-Host "Using PHP 8.2.28" -ForegroundColor Yellow
} elseif (Test-Path $php83Path) {
    $phpExe = $php83Path
    Write-Host "Using PHP 8.3.26" -ForegroundColor Yellow
} else {
    Write-Host "ERROR: PHP 8.2+ not found in Laragon!" -ForegroundColor Red
    Write-Host "Please install PHP 8.2+ in Laragon" -ForegroundColor Red
    exit 1
}

# Set PHP path temporarily
$env:Path = "D:\laragon\bin\php\php-8.2.28-nts-Win32-vs16-x64;$env:Path"

Write-Host "Step 1: Installing Composer dependencies..." -ForegroundColor Cyan
& $phpExe "D:\laragon\bin\composer\composer.phar" install --no-interaction
if ($LASTEXITCODE -ne 0) {
    Write-Host "ERROR: Composer install failed!" -ForegroundColor Red
    exit 1
}

Write-Host "Step 2: Checking .env file..." -ForegroundColor Cyan
if (-not (Test-Path ".env")) {
    Write-Host "Creating .env file from .env.example..." -ForegroundColor Yellow
    Copy-Item ".env.example" ".env"
} else {
    Write-Host ".env file already exists" -ForegroundColor Green
}

Write-Host "Step 3: Generating application key..." -ForegroundColor Cyan
& $phpExe artisan key:generate --force
if ($LASTEXITCODE -ne 0) {
    Write-Host "ERROR: Key generation failed!" -ForegroundColor Red
    exit 1
}

Write-Host "Step 4: Creating database..." -ForegroundColor Cyan
Write-Host "Please ensure MySQL is running in Laragon" -ForegroundColor Yellow
Write-Host "Database name: grocery_api" -ForegroundColor Yellow
Write-Host "Username: root" -ForegroundColor Yellow
Write-Host "Password: (empty)" -ForegroundColor Yellow
Write-Host ""
Read-Host "Press Enter after creating the database in Laragon MySQL"

Write-Host "Step 5: Running migrations..." -ForegroundColor Cyan
& $phpExe artisan migrate --force
if ($LASTEXITCODE -ne 0) {
    Write-Host "ERROR: Migrations failed!" -ForegroundColor Red
    Write-Host "Please check your database configuration in .env" -ForegroundColor Yellow
    exit 1
}

Write-Host ""
Write-Host "=== Setup Complete! ===" -ForegroundColor Green
Write-Host ""
Write-Host "To start the server, run:" -ForegroundColor Cyan
Write-Host "  D:\laragon\bin\php\php-8.2.28-nts-Win32-vs16-x64\php.exe artisan serve" -ForegroundColor Yellow
Write-Host ""
Write-Host "Or use Laragon's PHP 8.2+ version" -ForegroundColor Yellow
Write-Host ""
Write-Host "API will be available at: http://localhost:8000/api/v1" -ForegroundColor Green
