<?php

namespace App\Services\Install;

/**
 * Step 8, sub-task 1: writes .env from everything collected across Steps
 * 3-7. Idempotent — safe to call again if the install run is retried after
 * a partial failure (checks isWritten() first, per the "safe to resume"
 * requirement in 08-installation-workflow.md §Failure Handling).
 */
class EnvWriter
{
    private string $envPath;

    public function __construct()
    {
        $this->envPath = ROOTPATH . '.env';
    }

    public function isWritten(): bool
    {
        return file_exists($this->envPath) && str_contains(file_get_contents($this->envPath), 'CI_ENVIRONMENT');
    }

    public function write(array $wizardState): void
    {
        $db     = $wizardState['step3'] ?? [];
        $app    = $wizardState['step4'] ?? [];
        $smtp   = $wizardState['step6'] ?? [];
        $payment = $wizardState['step7'] ?? [];

        $jwtSecret = bin2hex(random_bytes(32));
        $encryptionKey = bin2hex(random_bytes(32));

        $lines = [
            "CI_ENVIRONMENT = production",
            "",
            "app.baseURL = '" . rtrim($app['app_url'] ?? base_url(), '/') . "/'",
            "app.appTimezone = '" . ($app['timezone'] ?? 'Asia/Karachi') . "'",
            "app.defaultLocale = '" . ($app['locale'] ?? 'en') . "'",
            "",
            "database.default.hostname = " . ($db['host'] ?? '127.0.0.1'),
            "database.default.database = " . ($db['database'] ?? ''),
            "database.default.username = " . ($db['username'] ?? ''),
            "database.default.password = " . ($db['password'] ?? ''),
            "database.default.DBDriver = MySQLi",
            "database.default.DBPrefix = " . ($db['prefix'] ?? ''),
            "database.default.port = " . ($db['port'] ?? '3306'),
            "",
            "jwt.secret = {$jwtSecret}",
            "jwt.accessTokenTTL = 900",
            "jwt.refreshTokenTTL = 2592000",
            "",
            "encryption.key = {$encryptionKey}",
            "",
            "email.protocol = smtp",
            "email.SMTPHost = " . ($smtp['host'] ?? ''),
            "email.SMTPUser = " . ($smtp['username'] ?? ''),
            "email.SMTPPass = " . ($smtp['password'] ?? ''),
            "email.SMTPPort = " . ($smtp['port'] ?? '587'),
            "email.SMTPCrypto = " . ($smtp['encryption'] ?? 'tls'),
            "email.fromEmail = " . ($smtp['from_email'] ?? ''),
            "email.fromName = '" . ($smtp['from_name'] ?? 'Job Portal') . "'",
            "",
            "stripe.publicKey = " . ($payment['stripe_public_key'] ?? ''),
            "stripe.secretKey = " . ($payment['stripe_secret_key'] ?? ''),
            "paypal.clientId = " . ($payment['paypal_client_id'] ?? ''),
            "paypal.secret = " . ($payment['paypal_secret'] ?? ''),
            "jazzcash.merchantId = " . ($payment['jazzcash_merchant_id'] ?? ''),
            "jazzcash.password = " . ($payment['jazzcash_password'] ?? ''),
            "jazzcash.integritySalt = " . ($payment['jazzcash_integrity_salt'] ?? ''),
            "easypaisa.storeId = " . ($payment['easypaisa_store_id'] ?? ''),
            "easypaisa.hashKey = " . ($payment['easypaisa_hash_key'] ?? ''),
            "",
            "redis.enabled = " . (($wizardState['step0']['redis_enabled'] ?? false) ? 'true' : 'false'),
        ];

        file_put_contents($this->envPath, implode("\n", $lines) . "\n");
    }
}
