<?php
// install.php - Otomatik Kurulum Sihirbazı
session_start();

// Güvenlik: Eğer kurulum zaten yapılmışsa (ayar dosyası doluysa) sihirbazı durdur.
$configFile = __DIR__ . '/config/database.php';
if (file_exists($configFile)) {
    $config = require $configFile;
    if (!empty($config['dbname'])) {
        die("<h1>Kurulum Zaten Tamamlanmış!</h1><p>Sistem zaten kurulu. Güvenliğiniz için bu dosyayı (install.php) sunucudan silmeniz önerilir.</p><a href='admin/login.php'>Yönetim Paneline Git</a>");
    }
}

$step = 1;
$errors = [];
$success = false;

// 1. Sistem Gereksinimleri Kontrolü
$php_version_ok = version_compare(PHP_VERSION, '8.4.0', '>=');
$pdo_ok = extension_loaded('pdo_mysql');

if (!$php_version_ok || !$pdo_ok) {
    $errors[] = "Sunucunuz sistem gereksinimlerini karşılamıyor. Lütfen ayarlarınızı kontrol edin.";
}

// 2. Form Gönderildiğinde Kurulumu Başlat
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $php_version_ok && $pdo_ok) {
    $db_host = trim($_POST['db_host'] ?? 'localhost');
    $db_name = trim($_POST['db_name'] ?? '');
    $db_user = trim($_POST['db_user'] ?? '');
    $db_pass = trim($_POST['db_pass'] ?? '');

    if (empty($db_name) || empty($db_user)) {
        $errors[] = "Lütfen veritabanı adı ve kullanıcı adı alanlarını doldurun.";
    } else {
        try {
            // Veritabanına test bağlantısı yapıyoruz
            $pdo = new PDO("mysql:host=$db_host;charset=utf8mb4", $db_user, $db_pass, [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
            ]);

            // Veritabanını seç
            $pdo->exec("USE `$db_name`");

            // --- SQL KURULUM SORGULARI ---
            $sql = "
                SET SQL_MODE = 'NO_AUTO_VALUE_ON_ZERO';
                ALTER DATABASE `$db_name` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

                CREATE TABLE IF NOT EXISTS `settings` (
                  `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
                  `setting_key` varchar(50) NOT NULL UNIQUE,
                  `setting_value` text NOT NULL
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

                INSERT IGNORE INTO `settings` (`setting_key`, `setting_value`) VALUES
                ('site_title', 'Ajans Kurumsal Çözümler'),
                ('contact_email', 'info@ajans.com'),
                ('whatsapp_number', '+905550000000'),
                ('footer_text', 'Tüm Hakları Saklıdır.');

                CREATE TABLE IF NOT EXISTS `menus` (
                  `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
                  `name` varchar(50) NOT NULL,
                  `location` varchar(50) NOT NULL UNIQUE
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

                INSERT IGNORE INTO `menus` (`id`, `name`, `location`) VALUES
                (1, 'Üst Menü (Header)', 'header'),
                (2, 'Alt Menü (Footer)', 'footer');

                CREATE TABLE IF NOT EXISTS `menu_items` (
                  `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
                  `menu_id` int(11) NOT NULL,
                  `parent_id` int(11) DEFAULT NULL,
                  `title` varchar(100) NOT NULL,
                  `url` varchar(255) NOT NULL,
                  `sort_order` int(11) DEFAULT 0,
                  CONSTRAINT `fk_menu` FOREIGN KEY (`menu_id`) REFERENCES `menus` (`id`) ON DELETE CASCADE,
                  CONSTRAINT `fk_menu_parent` FOREIGN KEY (`parent_id`) REFERENCES `menu_items` (`id`) ON DELETE CASCADE
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

                INSERT IGNORE INTO `menu_items` (`id`, `menu_id`, `parent_id`, `title`, `url`, `sort_order`) VALUES
                (1, 1, NULL, 'Kurumsal', '/kurumsal', 1),
                (2, 1, NULL, 'Çözümler', '/cozumler', 2),
                (3, 1, NULL, 'Referanslar', '/referanslar', 3),
                (4, 1, NULL, 'İletişim', '/iletisim', 4);

                CREATE TABLE IF NOT EXISTS `pages` (
                  `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
                  `title` varchar(255) NOT NULL,
                  `slug` varchar(255) NOT NULL UNIQUE,
                  `is_active` tinyint(1) DEFAULT 1,
                  `created_at` timestamp NOT NULL DEFAULT current_timestamp()
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

                INSERT IGNORE INTO `pages` (`id`, `title`, `slug`, `is_active`) VALUES
                (1, 'Anasayfa', 'anasayfa', 1);

                CREATE TABLE IF NOT EXISTS `blocks` (
                  `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
                  `name` varchar(100) NOT NULL,
                  `file_path` varchar(255) NOT NULL
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

                INSERT IGNORE INTO `blocks` (`id`, `name`, `file_path`) VALUES
                (1, 'Hero (Karşılama)', 'blocks/hero.php'),
                (2, 'Hizmetler (3 Sütunlu)', 'blocks/services.php'),
                (3, 'İstatistikler (Neden Biz)', 'blocks/stats.php');

                CREATE TABLE IF NOT EXISTS `page_blocks` (
                  `id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,
                  `page_id` int(11) NOT NULL,
                  `block_id` int(11) NOT NULL,
                  `sort_order` int(11) DEFAULT 0,
                  `content_json` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL,
                  CONSTRAINT `fk_pb_page` FOREIGN KEY (`page_id`) REFERENCES `pages` (`id`) ON DELETE CASCADE,
                  CONSTRAINT `fk_pb_block` FOREIGN KEY (`block_id`) REFERENCES `blocks` (`id`) ON DELETE CASCADE
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

                INSERT IGNORE INTO `page_blocks` (`id`, `page_id`, `block_id`, `sort_order`, `content_json`) VALUES
                (1, 1, 1, 1, '{\"subtitle\":\"Ajans Yazılım\",\"mega_title\":\"YAZILIMI SANATA<br>DÖNÜŞTÜRÜYORUZ\",\"description\":\"Sektörünüze özel, yenilikçi stratejilerle işletmenizin online varlığını güçlendiriyor, benzersiz ve etkileyici bir dijital deneyim sunuyoruz.\",\"button_text\":\"Bizi Tanı\",\"button_link\":\"#\",\"image_path\":\"https://images.unsplash.com/photo-1522071820081-009f0129c71c?auto=format&fit=crop&w=1200&q=80\"}'),
                (2, 1, 2, 2, '{\"subtitle\":\"Hizmetler\",\"title\":\"Kurumsal ihtiyaçlar için çözüm portföyü\",\"feature_title\":\"Uçtan uca yönetilen IT operasyonu\",\"items\":[{\"icon\":\"💻\",\"title\":\"Özel Yazılım\",\"desc\":\"Markanıza özel güvenli web yazılımları.\",\"link\":\"#\"},{\"icon\":\"📈\",\"title\":\"SEO & Pazarlama\",\"desc\":\"Organik büyüme ve performans reklamları.\",\"link\":\"#\"},{\"icon\":\"🛡️\",\"title\":\"Sunucu & Güvenlik\",\"desc\":\"Linux tabanlı yüksek performanslı altyapı.\",\"link\":\"#\"}]}'),
                (3, 1, 3, 3, '{\"subtitle\":\"NEDEN BİZ?\",\"title\":\"Güven inşa eden<br>IT hizmetleri.\",\"items\":[{\"value\":\"1190+\",\"label\":\"Mutlu Müşteri\"},{\"value\":\"10.000+\",\"label\":\"Çözülen Ticket\"},{\"value\":\"7/24\",\"label\":\"Kesintisiz Destek\"}]}');
            ";
            
            // Tüm SQL sorgularını çalıştırıyoruz
            $pdo->exec($sql);

            // 3. Ayar Dosyasını (config/database.php) Oluştur
            $configContent = "<?php\nreturn [\n    'host'     => '$db_host',\n    'dbname'   => '$db_name',\n    'username' => '$db_user',\n    'password' => '$db_pass',\n    'charset'  => 'utf8mb4'\n];\n";
            
            // config klasörünün varlığından emin olalım
            if (!is_dir(__DIR__ . '/config')) {
                mkdir(__DIR__ . '/config', 0755, true);
            }
            
            file_put_contents($configFile, $configContent);

            // Kurulum bittikten sonra güvenlik için dosyayı kilitliyoruz
            rename(__FILE__, __FILE__ . '.locked');
            
            $success = true;

        } catch (PDOException $e) {
            $errors[] = "Veritabanına bağlanılamadı. Bilgilerinizi kontrol edin: " . $e->getMessage();
        } catch (Exception $e) {
            $errors[] = "Kurulum sırasında bir hata oluştu: " . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ajans CMS - Kurulum Sihirbazı</title>
    <style>
        * { box-sizing: border-box; font-family: system-ui, sans-serif; }
        body { background: #f3f4f6; display: flex; align-items: center; justify-content: center; min-height: 100vh; margin: 0; padding: 2rem; }
        .install-box { background: white; padding: 3rem; border-radius: 16px; box-shadow: 0 20px 25px -5px rgba(0,0,0,0.1); width: 100%; max-width: 600px; }
        .install-box h2 { margin-top: 0; color: #111827; text-align: center; font-size: 2rem; margin-bottom: 0.5rem; }
        .install-box p { text-align: center; color: #6b7280; margin-bottom: 2.5rem; }
        .form-group { margin-bottom: 1.5rem; }
        label { display: block; margin-bottom: 0.5rem; color: #4b5563; font-weight: 600; font-size: 0.95rem; }
        input { width: 100%; padding: 0.8rem; border: 1px solid #d1d5db; border-radius: 8px; outline: none; transition: border-color 0.3s; }
        input:focus { border-color: #10b981; }
        button { width: 100%; padding: 1rem; background: #0f172a; color: white; border: none; border-radius: 8px; font-weight: bold; font-size: 1.1rem; cursor: pointer; margin-top: 1rem; transition: background 0.3s; }
        button:hover { background: #1e293b; }
        .error { background: #fee2e2; color: #b91c1c; padding: 1rem; border-radius: 8px; margin-bottom: 1.5rem; font-size: 0.9rem; }
        .success { text-align: center; }
        .success svg { width: 80px; height: 80px; color: #10b981; margin-bottom: 1.5rem; }
        .req-box { display: flex; justify-content: space-between; padding: 1rem; background: #f8fafc; border-radius: 8px; margin-bottom: 1rem; font-size: 0.9rem; border: 1px solid #e2e8f0; }
        .status-ok { color: #10b981; font-weight: bold; }
        .status-fail { color: #ef4444; font-weight: bold; }
    </style>
</head>
<body>

    <div class="install-box">
        <?php if ($success): ?>
            <div class="success">
                <svg fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                <h2 style="color: #10b981;">Kurulum Başarılı!</h2>
                <p style="color: #4b5563;">Veritabanı bağlantısı kuruldu, tablolar oluşturuldu ve örnek içerikler sisteme başarıyla yüklendi.</p>
                <a href="admin/login.php" style="display:inline-block; width:100%; padding:1rem; background:#10b981; color:white; border-radius:8px; font-weight:bold; text-decoration:none;">Yönetim Paneline Git →</a>
            </div>
        <?php else: ?>
            <h2>CMS Kurulumu</h2>
            <p>Sistemi başlatmak için veritabanı bilgilerinizi girin.</p>

            <?php if (!empty($errors)): ?>
                <div class="error">
                    <ul style="margin:0; padding-left:1.2rem;">
                        <?php foreach ($errors as $err): ?>
                            <li><?= $err ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php endif; ?>

            <div style="margin-bottom: 2rem;">
                <h4 style="margin-bottom: 0.8rem; color:#111827;">Sistem Gereksinimleri</h4>
                <div class="req-box">
                    <span>PHP Sürümü (Min: 8.4)</span>
                    <span class="<?= $php_version_ok ? 'status-ok' : 'status-fail' ?>"><?= $php_version_ok ? 'Uygun (' . PHP_VERSION . ')' : 'Yetersiz' ?></span>
                </div>
                <div class="req-box">
                    <span>PDO MySQL Eklentisi</span>
                    <span class="<?= $pdo_ok ? 'status-ok' : 'status-fail' ?>"><?= $pdo_ok ? 'Aktif' : 'Pasif' ?></span>
                </div>
            </div>

            <?php if ($php_version_ok && $pdo_ok): ?>
                <form method="POST">
                    <div class="form-group">
                        <label>Veritabanı Sunucusu (Host)</label>
                        <input type="text" name="db_host" value="localhost" required>
                    </div>
                    <div class="form-group">
                        <label>Veritabanı Adı</label>
                        <input type="text" name="db_name" placeholder="Plesk panelinizden oluşturduğunuz ad..." required>
                    </div>
                    <div class="form-group">
                        <label>Veritabanı Kullanıcı Adı</label>
                        <input type="text" name="db_user" required>
                    </div>
                    <div class="form-group">
                        <label>Veritabanı Şifresi</label>
                        <input type="password" name="db_pass">
                    </div>
                    <button type="submit">Sistemi Kur ve Başlat</button>
                </form>
            <?php endif; ?>
        <?php endif; ?>
    </div>

</body>
</html>