<?php
declare(strict_types=1);

/**
 * Step 8 deploy wizard.
 *
 * Generates a local deploy plan from deploy/cpanel/values.example.env or a copied
 * deploy/cpanel/values.env file. This does not connect to GitHub or cPanel.
 *
 * Usage:
 *   cp deploy/cpanel/values.example.env deploy/cpanel/values.env
 *   php scripts/setup_deploy_wizard.php staging
 *   php scripts/setup_deploy_wizard.php production
 */

if (PHP_SAPI !== 'cli') {
    http_response_code(403);
    echo "403 Forbidden\n";
    exit(1);
}

$root = dirname(__DIR__);
$environment = $argv[1] ?? '';

if (!in_array($environment, ['staging', 'production'], true)) {
    fwrite(STDERR, "Usage: php scripts/setup_deploy_wizard.php <staging|production>\n");
    exit(1);
}

$valuesFile = $root . '/deploy/cpanel/values.env';
$fallbackFile = $root . '/deploy/cpanel/values.example.env';
$sourceFile = is_file($valuesFile) ? $valuesFile : $fallbackFile;

function parse_values(string $path): array
{
    $values = [];
    foreach (file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [] as $line) {
        $line = trim($line);
        if ($line === '' || str_starts_with($line, '#') || !str_contains($line, '=')) {
            continue;
        }
        [$key, $value] = explode('=', $line, 2);
        $values[trim($key)] = trim($value);
    }
    return $values;
}

$values = parse_values($sourceFile);
$prefix = strtoupper($environment);

$username = $values['CPANEL_USERNAME'] ?? 'USERNAME';
$remote = $values['GITHUB_REMOTE'] ?? 'git@github.com:OWNER/REPO.git';
$branch = $values["{$prefix}_BRANCH"] ?? ($environment === 'staging' ? 'develop' : 'main');
$target = $values["{$prefix}_DEPLOY_TARGET"] ?? 'public_html/perawat';
$appUrl = $values["{$prefix}_APP_URL"] ?? '';
$homeTarget = '/home/' . $username . '/' . trim($target, '/') . '/';

$outputDir = $root . '/deploy/generated';
if (!is_dir($outputDir)) {
    mkdir($outputDir, 0755, true);
}

$plan = <<<TEXT
# Deploy Plan - {$environment}

Generated from: {$sourceFile}

## Values

- GitHub remote: {$remote}
- Branch: {$branch}
- cPanel username: {$username}
- Deploy path: {$homeTarget}
- App URL: {$appUrl}

## Local Git commands

```bash
bash scripts/init_git_branches.sh {$remote}
git push -u origin main
git push -u origin develop
```

## Generate .cpanel.yml

```bash
php scripts/generate_cpanel_yml.php {$environment} {$username} {$target}
```

## First run on server

```bash
php scripts/create_env.php {$environment}
nano .env
php scripts/post_deploy.php
php scripts/preflight.php
php scripts/deploy_ready.php {$environment}
php scripts/step7_smoke_test.php
php scripts/migrate.php status
```

## cPanel Git Version Control

Repository URL:

```text
{$remote}
```

Branch:

```text
{$branch}
```

Deployment path:

```text
{$homeTarget}
```

TEXT;

$planPath = $outputDir . "/deploy-plan-{$environment}.md";
file_put_contents($planPath, $plan);

echo "Generated {$planPath}\n";
echo "Review it before configuring cPanel Git Version Control.\n";

