<?php
/**
 * Step 6 post deploy helper.
 * Jalankan setelah deploy di staging/production:
 * php scripts/post_deploy.php
 */

$root = dirname(__DIR__);
$paths = [
    'storage/logs',
    'storage/cache',
    'storage/exports',
    'storage/backups',
    'uploads/jadwal',
    'uploads/dokumen',
    'uploads/lampiran',
    'uploads/temp',
    'exports',
];

function line_out(string $status, string $message): void
{
    echo '[' . $status . '] ' . $message . PHP_EOL;
}

foreach ($paths as $relativePath) {
    $fullPath = $root . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $relativePath);
    if (!is_dir($fullPath)) {
        if (@mkdir($fullPath, 0755, true)) {
            line_out('OK', "Created {$relativePath}");
        } else {
            line_out('FAIL', "Cannot create {$relativePath}");
            continue;
        }
    } else {
        line_out('OK', "Exists {$relativePath}");
    }

    if (!is_writable($fullPath)) {
        @chmod($fullPath, 0755);
    }

    line_out(is_writable($fullPath) ? 'OK' : 'WARN', "Writable check {$relativePath}");
}

$envPath = $root . DIRECTORY_SEPARATOR . '.env';
if (!is_file($envPath)) {
    line_out('WARN', '.env belum ada. Copy deploy/env/.env.staging.template atau .env.production.template menjadi .env lalu isi credential asli.');
} else {
    line_out('OK', '.env tersedia');
}

$htaccessFiles = [
    'uploads/.htaccess' => "Options -Indexes\n<FilesMatch \"\\.php$\">\n    Require all denied\n</FilesMatch>\n",
    'storage/.htaccess' => "Require all denied\n",
];

foreach ($htaccessFiles as $relativePath => $content) {
    $fullPath = $root . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $relativePath);
    if (!is_file($fullPath)) {
        if (@file_put_contents($fullPath, $content) !== false) {
            line_out('OK', "Created {$relativePath}");
        } else {
            line_out('WARN', "Cannot create {$relativePath}");
        }
    } else {
        line_out('OK', "Exists {$relativePath}");
    }
}

line_out('DONE', 'Post deploy selesai. Lanjut jalankan: php scripts/preflight.php');
