<?php
/**
 * Hermes Bilişim Raporlama Sistemi - Otomatik Kurulum Sihirbazı (Bootstrap Installer)
 *
 * KULLANIM:
 * Bu dosyayı yeni müşterinin sunucusuna (XAMPP htdocs veya public_html) atın
 * ve tarayıcıdan çalıştırın. Kurulum paketi install.zip olarak iner.
 * Sürüm güncellemesi kurulumdan sonra uygulamanın kendi kontrolüyle yapılır.
 */

define('INSTALL_PACKAGE_URL', 'https://hermesbilisim.com/Raporlama/install.zip');

if (isset($_GET['indir'])) {
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="installer.php"');
    header('Content-Length: ' . filesize(__FILE__));
    header('Cache-Control: no-store');
    readfile(__FILE__);
    exit;
}

/**
 * Paketi indir. Önce cURL, yoksa file_get_contents.
 * @return array{ok:bool,http_code:int,error:string}
 */
function installer_download_file($url, $destPath) {
    if (function_exists('curl_init')) {
        $fp = fopen($destPath, 'w+');
        if (!$fp) {
            return ['ok' => false, 'http_code' => 0, 'error' => 'Geçici ZIP dosyası yazılamadı. Klasör izinlerini kontrol edin.'];
        }
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_FILE, $fp);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
        curl_setopt($ch, CURLOPT_TIMEOUT, 300);
        $ok = curl_exec($ch);
        $http_code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $err = curl_error($ch);
        curl_close($ch);
        fclose($fp);
        if ($ok === false) {
            @unlink($destPath);
            return ['ok' => false, 'http_code' => $http_code, 'error' => $err ?: 'cURL indirme başarısız.'];
        }
        return ['ok' => true, 'http_code' => $http_code, 'error' => ''];
    }

    if (!ini_get('allow_url_fopen')) {
        return [
            'ok' => false,
            'http_code' => 0,
            'error' => 'PHP cURL kapalı ve allow_url_fopen da kapalı. php.ini içinde extension=curl satırını açıp Apache\'yi yeniden başlatın.',
        ];
    }

    $ctx = stream_context_create([
        'http' => [
            'method' => 'GET',
            'timeout' => 300,
            'follow_location' => 1,
            'ignore_errors' => true,
            'header' => "User-Agent: HermesInstaller/1.0\r\n",
        ],
        'ssl' => [
            'verify_peer' => false,
            'verify_peer_name' => false,
        ],
    ]);

    $data = @file_get_contents($url, false, $ctx);
    $http_code = 0;
    if (isset($http_response_header) && is_array($http_response_header)) {
        foreach ($http_response_header as $line) {
            if (preg_match('/^HTTP\/\S+\s+(\d+)/', $line, $m)) {
                $http_code = (int)$m[1];
            }
        }
    }
    if ($data === false) {
        return ['ok' => false, 'http_code' => $http_code, 'error' => 'file_get_contents ile paket indirilemedi.'];
    }
    if (@file_put_contents($destPath, $data) === false) {
        return ['ok' => false, 'http_code' => $http_code, 'error' => 'İndirilen paket diske yazılamadı.'];
    }
    return ['ok' => true, 'http_code' => $http_code ?: 200, 'error' => ''];
}

$step = $_GET['step'] ?? 'start';
$error = '';
$success = '';
$can_download = function_exists('curl_init') || (bool)ini_get('allow_url_fopen');

if ($step === 'download') {
    try {
        if (!class_exists('ZipArchive')) {
            throw new Exception("Sunucuda ZipArchive eklentisi aktif değil. php.ini içinde extension=zip satırını açın veya xampp_setup.bat çalıştırın.");
        }
        if (!$can_download) {
            throw new Exception("İndirme için PHP cURL veya allow_url_fopen gerekir. php.ini içinde extension=curl satırını açıp Apache'yi yeniden başlatın.");
        }

        $download_url = INSTALL_PACKAGE_URL;
        $temp_zip = __DIR__ . '/hermes_system.zip';

        $dl = installer_download_file($download_url, $temp_zip);
        if (!$dl['ok']) {
            @unlink($temp_zip);
            throw new Exception($dl['error']);
        }

        $http_code = (int)$dl['http_code'];
        if ($http_code !== 200 || !file_exists($temp_zip) || filesize($temp_zip) < 100) {
            @unlink($temp_zip);
            throw new Exception("ZIP paketi indirilemedi (HTTP $http_code). Merkez sunucuda bu dosya yok: $download_url");
        }

        $zip = new ZipArchive;
        if ($zip->open($temp_zip) === TRUE) {
            for ($i = 0; $i < $zip->numFiles; $i++) {
                $filename = $zip->getNameIndex($i);
                $normalized_filename = str_replace('\\', '/', $filename);
                $targetPath = __DIR__ . '/' . ltrim($normalized_filename, '/');

                if (substr($normalized_filename, -1) === '/') {
                    if (!is_dir($targetPath)) {
                        mkdir($targetPath, 0755, true);
                    }
                } else {
                    $dir = dirname($targetPath);
                    if (!is_dir($dir)) {
                        mkdir($dir, 0755, true);
                    }
                    $fp = $zip->getStream($filename);
                    if ($fp) {
                        $ofp = fopen($targetPath, 'w');
                        if ($ofp) {
                            while (!feof($fp)) {
                                fwrite($ofp, fread($fp, 8192));
                            }
                            fclose($ofp);
                        }
                        fclose($fp);
                    }
                }
            }
            $zip->close();
            @unlink($temp_zip);
            header("Location: setup.php");
            exit;
        }

        @unlink($temp_zip);
        throw new Exception("İndirilen ZIP paketi açılamadı. Dizin yazma izinlerini kontrol edin.");
    } catch (Exception $e) {
        $error = $e->getMessage();
        $step = 'start';
    }
}
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hermes Bilişim - Akıllı Kurulum</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
    <style>
        body { background: #0f172a; color: #f1f5f9; font-family: 'Inter', sans-serif; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; }
        .box { background: rgba(30, 41, 59, 0.8); padding: 40px; border-radius: 12px; text-align: center; max-width: 520px; box-shadow: 0 10px 30px rgba(0,0,0,0.5); border: 1px solid rgba(255,255,255,0.1); }
        h1 { color: #38bdf8; margin-top: 0; }
        p { color: #94a3b8; line-height: 1.6; }
        .btn { display: inline-block; background: #38bdf8; color: #0f172a; padding: 12px 30px; font-weight: 600; border-radius: 8px; text-decoration: none; font-size: 1.1rem; margin-top: 20px; border: none; cursor: pointer; transition: all 0.2s; }
        .btn:hover { background: #0284c7; color: #fff; }
        .error { background: rgba(239, 68, 68, 0.1); color: #ef4444; padding: 15px; border-radius: 8px; margin-top: 20px; text-align: left; border: 1px solid rgba(239, 68, 68, 0.2); }
        code { background: #0f172a; padding: 1px 6px; border-radius: 4px; }
        ul { text-align: left; color: #fca5a5; margin-top: 10px; }
    </style>
</head>
<body>
    <div class="box">
        <h1>Hermes Raporlama</h1>
        <p>Kurulum paketi <b>install.zip</b> olarak merkezden indirilir ve bu klasöre açılır.<br>Kurulum bittikten sonra yeni sürüm varsa uygulama kendi güncelleme kontrolünü yapar.</p>

        <?php if ($error): ?>
            <div class="error"><b>Hata:</b> <?= htmlspecialchars($error) ?></div>
        <?php endif; ?>

        <?php if (!extension_loaded('zip')): ?>
            <div class="error" style="border: 2px solid #ef4444;">
                <h3 style="margin-top: 0; color: #ef4444;">PHP ZIP eklentisi eksik</h3>
                <p style="color: #f87171; margin-bottom: 0;">Kurulum için <strong>extension=zip</strong> açık olmalı.</p>
                <ul>
                    <li><code>php.ini</code> içinde <code>;extension=zip</code> satırının başındaki <code>;</code> işaretini kaldırın.</li>
                    <li>Apache'yi yeniden başlatın. İsterseniz <code>xampp_setup.bat</code> çalıştırın.</li>
                </ul>
            </div>
        <?php elseif (!$can_download): ?>
            <div class="error" style="border: 2px solid #ef4444;">
                <h3 style="margin-top: 0; color: #ef4444;">PHP cURL eklentisi eksik</h3>
                <p style="color: #f87171; margin-bottom: 0;">Paketi indirmek için <strong>extension=curl</strong> gerekir.</p>
                <ul>
                    <li>XAMPP Control Panel → Apache → Config → <code>php.ini</code></li>
                    <li><code>;extension=curl</code> satırını <code>extension=curl</code> yapın.</li>
                    <li>Apache'yi Stop / Start ile yeniden başlatın.</li>
                </ul>
            </div>
        <?php else: ?>
            <?php if (!function_exists('curl_init')): ?>
                <p style="font-size:0.85rem;color:#fbbf24;">cURL kapalı; indirme <code>allow_url_fopen</code> ile denenecek. Kalıcı çözüm: <code>extension=curl</code> açın.</p>
            <?php endif; ?>
            <a href="?step=download" class="btn" onclick="this.innerHTML='İndiriliyor... Lütfen bekleyin'; this.style.pointerEvents='none';">Kuruluma Başla (Buluttan İndir)</a>
        <?php endif; ?>
    </div>
</body>
</html>
