# ============================================================
# Karvi Partner Contract — LIVE deploy package builder
# ============================================================
$ErrorActionPreference = 'Stop'

$projectRoot = Split-Path $PSScriptRoot -Parent
$parentDir = Split-Path $projectRoot -Parent
$deployDir = Join-Path $parentDir 'Karvi-Pro-Contract-LIVE'
$zipPath = Join-Path $parentDir 'Karvi-Pro-Contract-LIVE.zip'
$vendorZipPath = Join-Path $parentDir 'Karvi-VENDOR-FIX.zip'

$denyAllDirs = @(
    'config', 'includes', 'vendor', 'database', 'pages', 'scripts',
    'lang', 'templates', 'tools', 'src', 'deploy',
    'controllers', 'services', 'models', 'views', 'middleware',
    'uploads', 'uploads/contracts', 'uploads/signatures', 'uploads/signed', 'uploads/template'
)

$excludeDirs = @(
    'New folder', '.git', '_deploy_staging', '_package_staging',
    'UPLOAD-TO-SERVER', 'Karvi-Pro-Contract-LIVE', 'tools', 'indexUser'
)

$excludeFiles = @(
    'cookies.txt', 'composer.phar', 'composer-setup.php', 'templat_data.txt',
    'config.local.php', 'php-local.ini'
)

$requiredVendorFiles = @(
    'vendor\autoload.php',
    'vendor\setasign\fpdf\fpdf.php',
    'vendor\setasign\fpdi\src\Fpdi.php'
)

if (Test-Path $deployDir) { Remove-Item $deployDir -Recurse -Force }
if (Test-Path $zipPath) { Remove-Item $zipPath -Force }
if (Test-Path $vendorZipPath) { Remove-Item $vendorZipPath -Force }

New-Item -ItemType Directory -Path $deployDir | Out-Null

robocopy $projectRoot $deployDir /E /XD $excludeDirs /XF $excludeFiles /NFL /NDL /NJH /NJS | Out-Null

@('contracts', 'signatures', 'signed', 'template') | ForEach-Object {
    $dir = Join-Path $deployDir "uploads\$_"
    if (Test-Path $dir) {
        Get-ChildItem $dir -File | Where-Object { $_.Name -notin @('.htaccess', 'index.php') } | Remove-Item -Force
    }
}

Set-Content -Path (Join-Path $deployDir 'database\data.json') -Value '[]' -Encoding UTF8

Set-Content -Path (Join-Path $deployDir 'config\config.local.php') -Value @'
<?php

declare(strict_types=1);

return [
    'base_path' => '',
    'require_contract_location' => true,
];
'@ -Encoding UTF8
Copy-Item (Join-Path $projectRoot 'deploy\parent-index.php') (Join-Path $deployDir 'PARENT-index.php') -Force

$denyIndex = Join-Path $projectRoot 'deploy\deny-index.php'
$securityHtaccess = Join-Path $projectRoot 'deploy\security.htaccess'

foreach ($rel in $denyAllDirs) {
    $dir = Join-Path $deployDir $rel
    if (-not (Test-Path $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null }
    Copy-Item $denyIndex (Join-Path $dir 'index.php') -Force
    Copy-Item $securityHtaccess (Join-Path $dir '.htaccess') -Force
}

$apiRoot = Join-Path $deployDir 'api'
if (-not (Test-Path $apiRoot)) { New-Item -ItemType Directory -Path $apiRoot -Force | Out-Null }
Copy-Item $denyIndex (Join-Path $apiRoot 'index.php') -Force

if (Test-Path (Join-Path $projectRoot 'assets\.htaccess')) {
    Copy-Item (Join-Path $projectRoot 'assets\.htaccess') (Join-Path $deployDir 'assets\.htaccess') -Force
}
Copy-Item $denyIndex (Join-Path $deployDir 'assets\index.php') -Force
Copy-Item (Join-Path $deployDir '.htaccess') (Join-Path $deployDir 'htaccess.txt') -Force

foreach ($rel in $requiredVendorFiles) {
    if (-not (Test-Path (Join-Path $deployDir $rel))) {
        Write-Error ("Vendor incomplete. Missing: $rel")
    }
}

$requiredDeployFiles = @(
    'index.php',
    'default.php',
    'index.html',
    'htaccess.txt',
    '.htaccess',
    'includes\karvi_front.php',
    'includes\karvi_route.php',
    'router.php',
    'install.php',
    'health.php',
    'admin\login\index.php',
    'admin\contracts\index.php',
    'contracts\sign\index.php',
    'config\config.local.php',
    'PARENT-index.php'
)

foreach ($rel in $requiredDeployFiles) {
    if (-not (Test-Path (Join-Path $deployDir $rel))) {
        Write-Error ("Deploy package incomplete. Missing: $rel")
    }
}

$vendorCount = (Get-ChildItem (Join-Path $deployDir 'vendor') -Recurse -File).Count

@'
================================================================
     KARVI PRO CONTRACT — LIVE SERVER UPLOAD (Roman Urdu)
================================================================

ZIP SAHI UPLOAD KAISE KAREIN
----------------------------
1. Server par purani files DELETE karein (galat nested folder bhi)
2. Karvi-Pro-Contract-LIVE.zip extract karein
3. ANDAR ki SAARI files (Ctrl+A) upload karein seedha web folder mein
   Example: /karvi-pro/   (invoice/ ke andar mat daalein)

ZAROORI FILES CHECK (404 se bachne ke liye)
--------------------------------------------
  /karvi-pro/index.php
  /karvi-pro/.htaccess          (FTP hidden ON, ya htaccess.txt rename)
  /karvi-pro/default.php
  /karvi-pro/vendor/setasign/fpdf/fpdf.php
  /karvi-pro/includes/karvi_front.php

PEHLE INSTALL, PHIR APP
-----------------------
1. Browser: https://YOUR-DOMAIN/karvi-pro/install.php
   → Save & Activate dabayein
2. Phir: https://YOUR-DOMAIN/karvi-pro/admin/login/
3. Health check: https://YOUR-DOMAIN/karvi-pro/health.php

LOGIN
-----
  API ON: karviapi1.de email/password (config/api.php)
  Local: admin / 123456 (sirf jab auth_enabled=false ho)

AGAR FILES GALTI SE invoice/ MEIN HAIN
--------------------------------------
  Karvi-VENDOR-FIX.zip → /karvi-pro/invoice/vendor/
  PARENT-index.php copy karke /karvi-pro/index.php bana dein

SECURITY
--------
  config/, includes/, vendor/ web se block hain
  Directory listing band hai — saari files list nahi dikhegi

================================================================
'@ | Set-Content -Path (Join-Path $deployDir 'START-HIER.txt') -Encoding UTF8

Push-Location $deployDir
try {
    tar -acf $zipPath *
    tar -acf $vendorZipPath vendor
} finally {
    Pop-Location
}

$sizeMB = [math]::Round((Get-Item $zipPath).Length / 1MB, 2)
$vendorMB = [math]::Round((Get-Item $vendorZipPath).Length / 1MB, 2)

Write-Host ""
Write-Host "=== DEPLOY READY ==="
Write-Host "Full zip:   $zipPath ($sizeMB MB)"
Write-Host "Vendor fix: $vendorZipPath ($vendorMB MB)"
Write-Host "Vendor files: $vendorCount"
Write-Host ""
Write-Host "Upload full zip to /karvi-pro/ OR vendor fix to /karvi-pro/invoice/vendor/"
