<?php
/**
 * Installer Helper Functions
 */

session_start();

define('INSTALL_PATH', dirname(__DIR__));
define('INSTALL_DIR', __DIR__);

/**
 * Cek requirement sistem
 */
function checkRequirements() {
    $requirements = [];
    
    // PHP Version
    $requirements[] = [
        'name'     => 'PHP Version',
        'required' => '>= 7.4',
        'current'  => PHP_VERSION,
        'status'   => version_compare(PHP_VERSION, '7.4.0', '>='),
        'critical' => true
    ];
    
    // Extensions
    $extensions = [
        'pdo'           => 'PDO',
        'pdo_mysql'     => 'PDO MySQL',
        'curl'          => 'cURL',
        'json'          => 'JSON',
        'mbstring'      => 'Mbstring',
        'openssl'       => 'OpenSSL',
        'session'       => 'Session'
    ];
    
    foreach ($extensions as $ext => $label) {
        $loaded = extension_loaded($ext);
        $requirements[] = [
            'name'     => $label . ' Extension',
            'required' => 'Enabled',
            'current'  => $loaded ? 'Enabled' : 'Disabled',
            'status'   => $loaded,
            'critical' => true
        ];
    }
    
    // Writable directories
    $writables = [
        INSTALL_PATH . '/config'   => 'config/',
        INSTALL_PATH . '/logs'     => 'logs/',
        INSTALL_PATH . '/install'  => 'install/',
    ];
    
    foreach ($writables as $path => $label) {
        if (!is_dir($path)) {
            @mkdir($path, 0755, true);
        }
        $writable = is_writable($path);
        $requirements[] = [
            'name'     => 'Writable: ' . $label,
            'required' => 'Writable',
            'current'  => $writable ? 'Writable' : 'Not Writable',
            'status'   => $writable,
            'critical' => true
        ];
    }
    
    // cURL function
    $requirements[] = [
        'name'     => 'cURL Function',
        'required' => 'Available',
        'current'  => function_exists('curl_init') ? 'Available' : 'Not Available',
        'status'   => function_exists('curl_init'),
        'critical' => true
    ];
    
    return $requirements;
}

/**
 * Test koneksi database
 */
function testDatabaseConnection($host, $port, $user, $pass) {
    try {
        $pdo = new PDO("mysql:host=$host;port=$port", $user, $pass, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        ]);
        return ['success' => true, 'version' => $pdo->query('SELECT VERSION()')->fetchColumn()];
    } catch (PDOException $e) {
        return ['success' => false, 'error' => $e->getMessage()];
    }
}

/**
 * Execute SQL schema
 */
function executeSchema($pdo, $schemaFile) {
    if (!file_exists($schemaFile)) {
        return ['success' => false, 'error' => 'Schema file not found'];
    }
    
    $sql = file_get_contents($schemaFile);
    
    try {
        // Split by statements
        $statements = array_filter(
            array_map('trim', explode(';', $sql)),
            function($s) { 
                return !empty($s) && !preg_match('/^--/', $s); 
            }
        );
        
        foreach ($statements as $statement) {
            if (empty(trim($statement))) continue;
            $pdo->exec($statement);
        }
        
        return ['success' => true];
    } catch (PDOException $e) {
        return ['success' => false, 'error' => $e->getMessage(), 'sql' => $statement ?? ''];
    }
}

/**
 * Tulis file konfigurasi
 */
function writeConfigFile($filename, $content) {
    $path = INSTALL_PATH . '/config/' . $filename;
    return file_put_contents($path, $content) !== false;
}

/**
 * Generate config file content
 */
function generateDatabaseConfig($data) {
    return "<?php\nreturn [\n" .
           "    'host'     => " . var_export($data['db_host'], true) . ",\n" .
           "    'database' => " . var_export($data['db_name'], true) . ",\n" .
           "    'username' => " . var_export($data['db_user'], true) . ",\n" .
           "    'password' => " . var_export($data['db_pass'], true) . ",\n" .
           "    'charset'  => 'utf8mb4',\n" .
           "    'port'     => " . (int)($data['db_port'] ?? 3306) . "\n" .
           "];\n";
}

function generateIpaymuConfig($data) {
    return "<?php\nreturn [\n" .
           "    'mode'        => " . var_export($data['ipaymu_mode'], true) . ",\n" .
           "    'sandbox'     => [\n" .
           "        'url'     => 'https://sandbox.ipaymu.com/api/v2/',\n" .
           "        'va'      => " . var_export($data['ipaymu_sandbox_va'], true) . ",\n" .
           "        'apiKey'  => " . var_export($data['ipaymu_sandbox_key'], true) . ",\n" .
           "    ],\n" .
           "    'production'  => [\n" .
           "        'url'     => 'https://my.ipaymu.com/api/v2/',\n" .
           "        'va'      => " . var_export($data['ipaymu_prod_va'], true) . ",\n" .
           "        'apiKey'  => " . var_export($data['ipaymu_prod_key'], true) . ",\n" .
           "    ],\n" .
           "    'notifyUrl'   => " . var_export($data['ipaymu_notify_url'], true) . ",\n" .
           "    'returnUrl'   => " . var_export($data['ipaymu_return_url'], true) . ",\n" .
           "    'cancelUrl'   => " . var_export($data['ipaymu_cancel_url'], true) . ",\n" .
           "];\n";
}

function generateWablasConfig($data) {
    return "<?php\nreturn [\n" .
           "    'token'   => " . var_export($data['wablas_token'], true) . ",\n" .
           "    'baseUrl' => " . var_export($data['wablas_url'], true) . ",\n" .
           "];\n";
}

function generateMikrotikConfig($data) {
    return "<?php\nreturn [\n" .
           "    'host'     => " . var_export($data['mt_host'], true) . ",\n" .
           "    'user'     => " . var_export($data['mt_user'], true) . ",\n" .
           "    'pass'     => " . var_export($data['mt_pass'], true) . ",\n" .
           "    'port'     => " . (int)($data['mt_port'] ?? 8700) . ",\n" .
           "    'timeout'  => 5,\n" .
           "    'pppoe_service' => " . var_export($data['mt_pppoe_service'] ?? 'pppoe-service', true) . ",\n" .
           "];\n";
}

function generateAppConfig($data) {
    return "<?php\nreturn [\n" .
           "    'name'         => " . var_export($data['app_name'], true) . ",\n" .
           "    'url'          => " . var_export($data['app_url'], true) . ",\n" .
           "    'timezone'     => 'Asia/Jakarta',\n" .
           "    'debug'        => false,\n" .
           "    'session_name' => 'RTRWNET_SESS'\n" .
           "];\n";
}

/**
 * Hash password (sama dengan yang dipakai di sistem)
 */
function hashPassword($password) {
    return password_hash($password, PASSWORD_BCRYPT);
}

/**
 * Lock installer (keamanan)
 */
function lockInstaller() {
    $lockFile = INSTALL_PATH . '/install.lock';
    $content = "Installed at: " . date('Y-m-d H:i:s') . "\n";
    $content .= "IP: " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown') . "\n";
    return file_put_contents($lockFile, $content) !== false;
}

function isLocked() {
    return file_exists(INSTALL_PATH . '/install.lock');
}

/**
 * Sanitize input
 */
function clean($str) {
    return htmlspecialchars(trim($str ?? ''), ENT_QUOTES, 'UTF-8');
}