<?php

declare(strict_types=1);

/**
 * One-time server setup. Open in browser after upload, then delete this file.
 * Example: https://yourdomain.de/karvi-pro/install.php
 */

header('Content-Type: text/html; charset=utf-8');

$root = __DIR__;
$configLocal = $root . '/config/config.local.php';
$messages = [];
$errors = [];

if (version_compare(PHP_VERSION, '8.0.0', '<')) {
    $errors[] = 'PHP 8.0+ required. Current: ' . PHP_VERSION;
}

if (!is_file($root . '/vendor/autoload.php')) {
    $errors[] = 'vendor/autoload.php missing — upload vendor/ folder from zip';
}

$fpdfFile = $root . '/vendor/setasign/fpdf/fpdf.php';
if (!is_file($fpdfFile)) {
    $errors[] = 'vendor/setasign/fpdf/fpdf.php missing — upload full vendor/ folder (use Karvi-VENDOR-FIX.zip)';
}

$scriptName = str_replace('\\', '/', (string)($_SERVER['SCRIPT_NAME'] ?? '/install.php'));
require_once __DIR__ . '/includes/bootstrap.php';
require_once __DIR__ . '/includes/helpers.php';

if (!defined('KARVI_ROOT')) {
    define('KARVI_ROOT', $root);
}

$detectedBase = app_detect_web_base_from_filesystem();
if ($detectedBase === '') {
    $detectedBase = rtrim(str_replace('\\', '/', dirname($scriptName)), '/');
    if ($detectedBase === '/' || $detectedBase === '.') {
        $detectedBase = '';
    }
}

foreach (['uploads/contracts', 'uploads/signatures', 'uploads/signed', 'database'] as $dir) {
    $path = $root . '/' . $dir;
    if (!is_dir($path)) {
        @mkdir($path, 0755, true);
    }
    if (!is_dir($path)) {
        $errors[] = 'Cannot create folder: ' . $dir;
    } elseif (!is_writable($path)) {
        $errors[] = 'Folder not writable: ' . $dir . ' (chmod 755 or 775)';
    }
}

$dbFile = $root . '/database/data.json';
if (!is_file($dbFile)) {
    @file_put_contents($dbFile, "[]\n");
}

$exts = ['gd', 'mbstring', 'curl', 'openssl'];
foreach ($exts as $ext) {
    if (!extension_loaded($ext)) {
        $errors[] = 'Missing PHP extension: ' . $ext;
    }
}

$runSetup = ($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST' || isset($_GET['run']);

if ($runSetup && $errors === []) {
    $basePath = trim((string)($_POST['base_path'] ?? $_GET['base_path'] ?? $detectedBase));
    $basePath = rtrim(str_replace('\\', '/', $basePath), '/');

    $configContent = "<?php\n\ndeclare(strict_types=1);\n\nreturn [\n    'base_path' => "
        . var_export($basePath, true) . ",\n];\n";

    if (@file_put_contents($configLocal, $configContent) === false) {
        $errors[] = 'Could not write config/config.local.php — check config/ folder permissions.';
    } else {
        $messages[] = 'Saved config/config.local.php with base_path = ' . ($basePath !== '' ? $basePath : '(root)');
    }
}

$configuredBase = '';
if (is_file($configLocal)) {
    $local = require $configLocal;
    if (is_array($local)) {
        $configuredBase = trim((string)($local['base_path'] ?? ''));
    }
}

$appUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http')
    . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost')
    . ($configuredBase !== '' ? $configuredBase : $detectedBase);

?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Karvi — Install</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 680px; margin: 2rem auto; padding: 0 1rem; line-height: 1.5; }
        .ok { color: #0a7; } .err { color: #c00; }
        .box { background: #f8f8f8; border: 1px solid #ddd; padding: 1rem; border-radius: 8px; margin: 1rem 0; }
        input[type=text] { width: 100%; padding: 8px; font-size: 1rem; box-sizing: border-box; }
        button { padding: 10px 20px; font-size: 1rem; cursor: pointer; background: #b8860b; color: #fff; border: none; border-radius: 6px; }
        code { background: #eee; padding: 2px 6px; border-radius: 4px; }
    </style>
</head>
<body>
    <h1>Karvi Partner Contract — Install</h1>

    <?php if ($errors !== []): ?>
        <div class="err">
            <strong>Fix these first:</strong>
            <ul><?php foreach ($errors as $e): ?><li><?= htmlspecialchars($e, ENT_QUOTES, 'UTF-8') ?></li><?php endforeach; ?></ul>
        </div>
    <?php endif; ?>

    <?php foreach ($messages as $m): ?>
        <p class="ok">✓ <?= htmlspecialchars($m, ENT_QUOTES, 'UTF-8') ?></p>
    <?php endforeach; ?>

    <div class="box">
        <p><strong>Detected folder path:</strong><br><code><?= htmlspecialchars($detectedBase !== '' ? $detectedBase : '/', ENT_QUOTES, 'UTF-8') ?></code></p>
        <?php if (str_contains($detectedBase, 'Karvi_partner_contract')): ?>
        <p class="err"><strong>Nested folder detected.</strong> For best results upload zip files directly into your web folder (e.g. <code>/karvi-pro/</code>), not inside extra <code>Karvi_partner_contract</code> subfolders.</p>
        <?php endif; ?>
        <p>Upload all zip files into this exact web folder, then click Save &amp; Activate.</p>
    </div>

    <?php if ($errors === []): ?>
    <form method="post">
        <p><label>Base path (auto-detected — usually correct):</label></p>
        <input type="text" name="base_path" value="<?= htmlspecialchars($configuredBase !== '' ? $configuredBase : $detectedBase, ENT_QUOTES, 'UTF-8') ?>">
        <p style="margin-top:1rem;"><button type="submit">Save &amp; Activate</button></p>
    </form>

    <?php if ($configuredBase !== '' || is_file($configLocal)): ?>
        <p class="ok" style="margin-top:1.5rem;">
            <strong>App ready:</strong><br>
            <a href="<?= htmlspecialchars($appUrl . '/index.php', ENT_QUOTES, 'UTF-8') ?>">Open App</a> &nbsp;|&nbsp;
            <a href="<?= htmlspecialchars($appUrl . '/admin/login/', ENT_QUOTES, 'UTF-8') ?>">Admin Login</a>
        </p>
        <p><small>Delete <code>install.php</code> and <code>check.php</code> after setup.</small></p>
    <?php endif; ?>
    <?php endif; ?>
</body>
</html>
