<?php
session_start();

// Set language from GET parameter, cookie, or default to Turkish
$lang = $_GET['lang'] ?? $_COOKIE['lang'] ?? 'tr';

// Save language preference in a cookie for 30 days and in session
if (isset($_GET['lang'])) {
    $lang = $_GET['lang'];
    setcookie('lang', $lang, time() + (86400 * 30), '/'); // 30 days
    $_SESSION['lang'] = $lang; // Also store in session for immediate use
} elseif (isset($_SESSION['lang'])) {
    $lang = $_SESSION['lang'];
} elseif (isset($_COOKIE['lang'])) {
    $lang = $_COOKIE['lang'];
}

// Ensure we have a valid language
if (!in_array($lang, ['tr', 'en'])) {
    $lang = 'tr';
}

// Initialize translations array
$translations = [];

// Load language file
$lang_file = __DIR__ . '/languages/' . $lang . '.php';
if (file_exists($lang_file)) {
    $translations = include $lang_file;
    if (!is_array($translations)) {
        $translations = [];
    }
} else {
    // Fallback to Turkish if language file doesn't exist
    $lang = 'tr';
    $translations = include __DIR__ . '/languages/tr.php';
    if (!is_array($translations)) {
        $translations = [];
    }
}

// Make sure the language is set in session
$_SESSION['lang'] = $lang;

// Translation function if not exists
if (!function_exists('__')) {
    function __($key, $params = []) {
        global $translations;
        $translation = $translations[$key] ?? $key;
        
        // Replace parameters if any
        if (!empty($params) && is_array($params)) {
            foreach ($params as $param => $value) {
                $translation = str_replace(':' . $param, $value, $translation);
            }
        }
        
        return $translation;
    }
}

// CSRF Token Oluşturma
function csrf_token_olustur() {
    if (empty($_SESSION["csrf_token"])) {
        $_SESSION["csrf_token"] = bin2hex(random_bytes(32));
    }
    return $_SESSION["csrf_token"];
}

// CSRF Token Doğrulama
function csrf_token_dogrula($token) {
    if (isset($_SESSION["csrf_token"]) && hash_equals($_SESSION["csrf_token"], $token)) {
        unset($_SESSION["csrf_token"]);
        return true;
    }
    return false;
}

// SQL dosyasını çalıştırma fonksiyonu
function execute_sql_file($pdo, $sql_file_path, $progress_callback = null) {
    if (!file_exists($sql_file_path)) {
        throw new Exception("SQL dosyası bulunamadı: " . $sql_file_path);
    }
    
    // Veritabanı bağlantısını kontrol et
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // SQL dosyasını satır satır oku
    $file = fopen($sql_file_path, 'r');
    if (!$file) {
        throw new Exception("SQL dosyası açılamadı: " . $sql_file_path);
    }
    
    $query = "";
    $delimiter = ';';
    $in_string = false;
    $query_count = 0;
    $total_queries = 0;
    
    // Toplam sorgu sayısını hesapla (ilerleme çubuğu için)
    $content = file_get_contents($sql_file_path);
    $total_queries = substr_count($content, ';') + 1;
    
    // İşlem başlangıcında foreign key kontrollerini devre dışı bırak
    $pdo->exec("SET FOREIGN_KEY_CHECKS = 0");
    
    try {
        while (!feof($file)) {
            $line = fgets($file);
            
            // Yorum satırlarını atla
            if (preg_match('/^--|^\/\*|^#/', $line)) {
                continue;
            }
            
            // DELIMITER değişikliklerini kontrol et
            if (preg_match('/^\s*DELIMITER\s+(\S+)/i', $line, $matches)) {
                $delimiter = $matches[1];
                continue;
            }
            
            // Sorguya satır ekle
            $query .= $line;
            
            // Eğer satırda noktalı virgül yoksa veya string içindeyse devam et
            if (strpos($line, $delimiter) === false || ($in_string && substr_count($line, '"') % 2 != 0)) {
                $in_string = !$in_string;
                continue;
            }
            
            // Sorguyu temizle ve çalıştır
            $query = trim($query);
            if (!empty($query) && $query != $delimiter) {
                // Sondaki delimiter'ı kaldır
                $query = rtrim($query, $delimiter);
                
                try {
                    $pdo->exec($query);
                    $query_count++;
                    
                    // İlerleme durumunu güncelle
                    if (is_callable($progress_callback)) {
                        $progress_callback($query_count, $total_queries);
                    }
                } catch (PDOException $e) {
                    throw new Exception("Sorgu hatası: " . $e->getMessage() . "\nHatalı Sorgu: " . $query);
                }
            }
            
            // Sorguyu sıfırla
            $query = "";
        }
        
        // Foreign key kontrollerini tekrar etkinleştir
        $pdo->exec("SET FOREIGN_KEY_CHECKS = 1");
        
        fclose($file);
        return $query_count;
    } catch (Exception $e) {
        // Hata durumunda foreign key kontrollerini tekrar etkinleştir
        $pdo->exec("SET FOREIGN_KEY_CHECKS = 1");
        
        // Hata durumunda ilerleme çubuğunu güncelle
        if (is_callable($progress_callback)) {
            $progress_callback(0, 1);
        }
        
        throw $e;
    }
}

// config.php dosyasını güncelleme fonksiyonu
function create_config_file($db_config) {
    $config_file_path = __DIR__ . '/includes/config.php';
    
    // Mevcut config.php dosyasını oku
    if (file_exists($config_file_path)) {
        $config_content = file_get_contents($config_file_path);
        
        // Veritabanı bilgilerini güncelle
        $config_content = preg_replace('/\$host\s*=\s*"[^"]*"/', '$host = "' . $db_config["db_server"] . '"', $config_content);
        $config_content = preg_replace('/\$dbname\s*=\s*"[^"]*"/', '$dbname = "' . $db_config["db_name"] . '"', $config_content);
        $config_content = preg_replace('/\$username\s*=\s*"[^"]*"/', '$username = "' . $db_config["db_username"] . '"', $config_content);
        $config_content = preg_replace('/\$password\s*=\s*"[^"]*"/', '$password = "' . $db_config["db_password"] . '"', $config_content);
        
        // Dosyayı güncelle
        if (file_put_contents($config_file_path, $config_content) === false) {
            throw new Exception(__('config_update_failed'));
        }
    } else {
        throw new Exception("config.php dosyası bulunamadı.");
    }
}

// Metin Temizleme
function temizle($veri) {
    return htmlspecialchars(strip_tags(trim($veri)));
}

$step = isset($_GET["step"]) ? (int)$_GET["step"] : 1;
$install_message = $_SESSION["install_message"] ?? "";
$install_error = $_SESSION["install_error"] ?? "";
unset($_SESSION["install_message"], $_SESSION["install_error"]);

$csrf_token = csrf_token_olustur();

if (isset($_GET['ajax']) && $_GET['ajax'] == 'progress') {
    // AJAX ilerleme talepleri için
    header('Content-Type: application/json');
    echo json_encode([
        'progress' => $_SESSION['install_progress'] ?? 0,
        'message' => $_SESSION['install_progress_message'] ?? __('starting') . '...',
        'completed' => $_SESSION['install_completed'] ?? false
    ]);
    exit();
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (!csrf_token_dogrula($_POST["csrf_token"] ?? "")) {
        $_SESSION["install_error"] = __("invalid_csrf_token");
        header("Location: install_setup.php?step=" . $step);
        exit();
    }

    if ($step == 1) {
        // Adım 1: Veritabanı Bağlantısı
        $db_server = temizle($_POST["db_server"] ?? "");
        $db_name = temizle($_POST["db_name"] ?? "");
        $db_username = temizle($_POST["db_username"] ?? "");
        $db_password = $_POST["db_password"] ?? "";

        if (empty($db_server) || empty($db_name) || empty($db_username)) {
            $_SESSION["install_error"] = __("fill_required_fields");
            header("Location: install_setup.php?step=1&lang=" . urlencode($lang));
            exit();
        }

        try {
            $pdo = new PDO("mysql:host=" . $db_server . ";dbname=" . $db_name, $db_username, $db_password);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $pdo->exec("SET NAMES utf8");

            $_SESSION["db_config"] = [
                "db_server" => $db_server,
                "db_name" => $db_name,
                "db_username" => $db_username,
                "db_password" => $db_password
            ];

            $_SESSION["install_message"] = __("db_connection_success");
            header("Location: install_setup.php?step=2&lang=" . urlencode($lang));
            exit();

        } catch (Exception $e) {
            $_SESSION["install_error"] = __("db_connection_error") . ": " . $e->getMessage();
            header("Location: install_setup.php?step=1&lang=" . urlencode($lang));
            exit();
        }
    } elseif ($step == 2) {
        // Adım 2: Kurulum İşlemi
        $db_config = $_SESSION["db_config"] ?? null;

        if (!$db_config) {
            $_SESSION["install_error"] = __("missing_database_info");
            header("Location: install_setup.php?step=1&lang=" . urlencode($lang));
            exit();
        }

        try {
            // Veritabanı bağlantı parametrelerini ayarla
            $dsn = sprintf(
                'mysql:host=%s;dbname=%s;charset=utf8mb4',
                $db_config["db_server"],
                $db_config["db_name"]
            );
            
            $options = [
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES   => false,
                PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci'
            ];
            
            // Veritabanına bağlan
            $pdo = new PDO($dsn, $db_config["db_username"], $db_config["db_password"], $options);
            
            // Karakter setini ayarla
            $pdo->exec('SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci');
            $pdo->exec('SET CHARACTER SET utf8mb4');
            
            // İlerleme çubuğu callback fonksiyonu
            $progress_callback = function($current, $total) {
                if ($total > 0) {
                    $progress = ($current / $total) * 100;
                    $_SESSION['install_progress'] = $progress;
                    $_SESSION['install_progress_message'] = sprintf(
                        __('installation_progress'), 
                        round($progress)
                    );
                    
                    // Oturumu güncelle
                    session_write_close();
                    session_start();
                }
            };

            // Kurulum aksiyonunu kontrol et
            $action = $_POST["action"] ?? "full";

            if ($action == "full") {
                // Tam kurulum - Tüm tabloları oluştur
                $pdo->exec("SET FOREIGN_KEY_CHECKS = 0");
                execute_sql_file($pdo, __DIR__ . '/install.sql', $progress_callback);
                $pdo->exec("SET FOREIGN_KEY_CHECKS = 1");
                $_SESSION["install_message"] = __("full_installation_complete");
            } elseif ($action == "partial") {
                // Kısmi kurulum - Sadece eksik tabloları ekle
                $pdo->exec("SET FOREIGN_KEY_CHECKS = 0");
                execute_sql_file($pdo, __DIR__ . '/install.sql', $progress_callback); // IF NOT EXISTS kullanıldığı için mevcutları etkilemez
                $_SESSION["install_message"] = __("partial_installation_complete");
            } elseif ($action == "drop_and_full") {
                // TÜM TABLOLARI SİL ve SIFIRDAN KUR
                $pdo->exec("SET FOREIGN_KEY_CHECKS = 0");
                // Tüm tablo isimlerini al
                $tables = $pdo->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
                foreach ($tables as $table) {
                    $pdo->exec("DROP TABLE IF EXISTS `" . $table . "`");
                }
                $pdo->exec("SET FOREIGN_KEY_CHECKS = 1");
                // install.sql'i çalıştır
                execute_sql_file($pdo, __DIR__ . '/install.sql', $progress_callback);
                $_SESSION["install_message"] = "Tüm veriler silindi ve sıfırdan kurulum tamamlandı!";
            } else {
                throw new Exception(__('invalid_installation_action'));
            }
            
            $_SESSION['install_progress'] = 100;
            $_SESSION['install_progress_message'] = __('installation_complete');
            $_SESSION['install_completed'] = true;

            header("Location: install_setup.php?step=3&lang=" . urlencode($lang));
            exit();

        } catch (Exception $e) {
            // Hata detaylarını logla
            $errorDetails = [
                'message' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => $e->getTraceAsString(),
                'time' => date('Y-m-d H:i:s'),
                'post_data' => $_POST
            ];
            
            // Hata detaylarını dosyaya yaz
            $logMessage = "[" . date('Y-m-d H:i:s') . "] Kurulum Hatası:\n";
            $logMessage .= "Mesaj: " . $e->getMessage() . "\n";
            $logMessage .= "Dosya: " . $e->getFile() . " (Satır: " . $e->getLine() . ")\n";
            $logMessage .= "Hata İzi: " . $e->getTraceAsString() . "\n";
            $logMessage .= "POST Verileri: " . print_r($_POST, true) . "\n\n";
            
            // Hata dosyasına yaz
            $errorLogFile = __DIR__ . '/install_errors.log';
            file_put_contents($errorLogFile, $logMessage, FILE_APPEND);
            
            // Kullanıcı dostu hata mesajı oluştur
            $errorMsg = "<div class='alert alert-danger'>";
            $errorMsg .= "<h4><i class='fas fa-exclamation-triangle'></i> Kurulum Hatası</h4>";
            $errorMsg .= "<p>" . htmlspecialchars($e->getMessage()) . "</p>";
            
            // Geliştirici için daha fazla detay (sadece geliştirme ortamında)
            if (strpos($_SERVER['HTTP_HOST'], 'localhost') !== false) {
                $errorMsg .= "<hr><h5>Hata Detayları:</h5>";
                $errorMsg .= "<p><strong>Dosya:</strong> " . htmlspecialchars($e->getFile()) . "</p>";
                $errorMsg .= "<p><strong>Satır:</strong> " . $e->getLine() . "</p>";
                
                // SQL hatası ise daha fazla detay göster
                if (strpos(strtolower($e->getMessage()), 'sql') !== false) {
                    $errorMsg .= "<p><strong>SQL Sorgusu:</strong> <code>" . 
                                htmlspecialchars($pdo->lastQuery ?? 'Bilinmiyor') . "</code></p>";
                }
                
                // Hata izini göster (sadece ilk 5 satır)
                $trace = explode("\n", $e->getTraceAsString());
                $errorMsg .= "<p><strong>Hata İzi (ilk 5 satır):</strong><br><small>" . 
                            implode("<br>", array_slice($trace, 0, 5)) . "</small></p>";
            } else {
                $errorMsg .= "<p>Lütfen sistem yöneticinizle iletişime geçin veya daha sonra tekrar deneyin.</p>";
            }
            
            $errorMsg .= "</div>";
            
            // Hata mesajını kaydet ve yönlendir
            $_SESSION["install_error"] = $errorMsg;
            $_SESSION['install_completed'] = false;
            $_SESSION['install_progress'] = 0;
            
            // Hata sayfasına yönlendir
            header("Location: install_setup.php?step=2&error=1");
            exit();
        }
    } elseif ($step == 3) {
        // Adım 3: İlk Şirket Oluşturma
        $db_config = $_SESSION["db_config"] ?? null;

        if (!$db_config) {
            $_SESSION["install_error"] = __("missing_database_info");
            header("Location: install_setup.php?step=1&lang=" . urlencode($lang));
            exit();
        }

        try {
            $pdo = new PDO("mysql:host=" . $db_config["db_server"] . ";dbname=" . $db_config["db_name"], $db_config["db_username"], $db_config["db_password"]);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $pdo->exec("SET NAMES utf8");

            $sirket_adi = temizle($_POST["sirket_adi"] ?? "");
            $adres = temizle($_POST["adres"] ?? "");
            $telefon = temizle($_POST["telefon"] ?? "");
            $email = temizle($_POST["email"] ?? "");
            $para_birimi = temizle($_POST["para_birimi"] ?? "TRY");
            $stok_aktif = !empty($_POST["stok_aktif"]) ? 1 : 0;
            $teklif_aktif = !empty($_POST["teklif_aktif"]) ? 1 : 0;

            if (empty($sirket_adi)) {
                throw new Exception("Şirket adı gereklidir.");
            }

            $pdo->beginTransaction();

            // İlk şirketi oluştur
            $stmt_sirket = $pdo->prepare("INSERT INTO sirketler (sirket_adi, adres, telefon, email, para_birimi, stok_islemleri_aktif, teklifler_modulu_aktif) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt_sirket->execute([$sirket_adi, $adres, $telefon, $email, $para_birimi, $stok_aktif, $teklif_aktif]);
            $sirket_id = $pdo->lastInsertId();

            // Varsayılan cari grubu oluştur
            $stmt_cari_grup = $pdo->prepare("INSERT INTO cari_gruplari (sirket_id, grup_adi) VALUES (?, ?)");
            $stmt_cari_grup->execute([$sirket_id, 'Perakende Müşteriler']);

            // Genel sistem ayarlarını (şirkete özgü olmayanları) ekle - Eğer yoksa
            $ayar_ekle_stmt = $pdo->prepare("INSERT IGNORE INTO ayarlar (ayar_adi, ayar_degeri, sirket_id) VALUES (?, ?, NULL)");
            $ayar_ekle_stmt->execute(['site_adi', 'Odjoo Yönetim Sistemi']);
            $ayar_ekle_stmt->execute(['resmi_kullanim_dili', 'tr']);
            $ayar_ekle_stmt->execute(['varsayilan_doviz_kuru', 'USD']);
            $ayar_ekle_stmt->execute(['varsayilan_doviz_alis_kuru', '30.00']);
            $ayar_ekle_stmt->execute(['varsayilan_doviz_satis_kuru', '30.50']);
            
            $pdo->commit();

            // Şirket bilgisini session'a kaydet
            $_SESSION["sirket_id"] = $sirket_id;
            $_SESSION["sirket_adi"] = $sirket_adi;

            $_SESSION["install_message"] = __("company_created_successfully");
            header("Location: install_setup.php?step=4&lang=" . urlencode($lang));
            exit();

        } catch (Exception $e) {
            $pdo->rollBack();
            $_SESSION["install_error"] = __("error_creating_company") . ": " . $e->getMessage();
            header("Location: install_setup.php?step=3&lang=" . urlencode($lang));
            exit();
        }
    } elseif ($step == 4) {
        // Adım 4: Admin Kullanıcı Oluşturma
        $db_config = $_SESSION["db_config"] ?? null;
        $sirket_id = $_SESSION["sirket_id"] ?? null;

        if (!$db_config || !$sirket_id) {
            $_SESSION["install_error"] = "Veritabanı bilgileri veya şirket bilgisi eksik. Lütfen tekrar deneyin.";
            header("Location: install_setup.php?step=1&lang=" . urlencode($lang));
            exit();
        }

        try {
            $pdo = new PDO("mysql:host=" . $db_config["db_server"] . ";dbname=" . $db_config["db_name"], $db_config["db_username"], $db_config["db_password"]);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $pdo->exec("SET NAMES utf8");

            $admin_ad_soyad = temizle($_POST["admin_ad_soyad"] ?? "");
            $admin_email = temizle($_POST["admin_email"] ?? "");
            $admin_username = temizle($_POST["admin_username"] ?? "");
            $admin_password = $_POST["admin_password"] ?? "";

            if (empty($admin_ad_soyad) || empty($admin_username) || empty($admin_password)) {
                throw new Exception("Tüm gerekli alanları doldurun: Yönetici adı soyadı, Yönetici kullanıcı adı ve Şifresi.");
            }

            $pdo->beginTransaction();

            // Admin kullanıcıyı oluştur
            $admin_language = isset($_POST["admin_language"]) ? temizle($_POST["admin_language"]) : 'tr';
            $hashed_password = password_hash($admin_password, PASSWORD_DEFAULT);
            $stmt_user = $pdo->prepare("INSERT INTO kullanicilar (ad_soyad, kullanici_adi, email, sifre, yetki_seviyesi, dil) VALUES (?, ?, ?, ?, 'admin', ?)");
            $stmt_user->execute([$admin_ad_soyad, $admin_username, $admin_email, $hashed_password, $admin_language]);
            $user_id = $pdo->lastInsertId();

            // Kullanıcıyı şirkete ata
            $stmt_iliski = $pdo->prepare("INSERT INTO kullanici_sirket_iliskisi (kullanici_id, sirket_id, rol) VALUES (?, ?, 'admin')");
            $stmt_iliski->execute([$user_id, $sirket_id]);
            
            $pdo->commit();

            create_config_file($db_config);

            $_SESSION["install_message"] = "Kurulum başarıyla tamamlandı! Yönetici kullanıcı oluşturuldu. Lütfen `install.php` dosyasını sunucunuzdan silin.";
            header("Location: install_setup.php?step=5");
            exit();

        } catch (Exception $e) {
            $pdo->rollBack();
            $_SESSION["install_error"] = "Yönetici kullanıcı oluşturulurken bir hata oluştu: " . $e->getMessage();
            header("Location: install_setup.php?step=4&lang=" . urlencode($lang));
            exit();
        }
    }
} // End of POST request handling

?>
<!DOCTYPE html>
<html lang="<?= $lang ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Odjoo - <?= __('installation') ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            font-family: 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            position: relative;
            overflow-x: hidden;
        }
        
        /* Animasyonlu arka plan şekilleri */
        body::before {
            content: '';
            position: fixed;
            top: -50%;
            left: -50%;
            width: 200%;
            height: 200%;
            background: radial-gradient(circle, rgba(255,255,255,0.1) 1px, transparent 1px);
            background-size: 50px 50px;
            animation: float 20s ease-in-out infinite;
            z-index: -1;
        }
        
        @keyframes float {
            0%, 100% { transform: translateY(0px) rotate(0deg); }
            50% { transform: translateY(-20px) rotate(180deg); }
        }
        
        .main-container {
            max-width: 800px;
            margin: 0 auto;
            padding: 2rem;
            position: relative;
            z-index: 1;
        }
        
        .hero-section {
            text-align: center;
            margin-bottom: 3rem;
            color: white;
        }
        
        .hero-section h1 {
            font-size: 2.5rem;
            font-weight: 700;
            margin-bottom: 1rem;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }
        
        .hero-section p {
            font-size: 1.1rem;
            opacity: 0.9;
            margin-bottom: 2rem;
        }
        
        .card {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            border: none;
            box-shadow: 0 15px 35px rgba(0,0,0,0.1);
            overflow: hidden;
            backdrop-filter: blur(10px);
        }
        
        .card-header {
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            padding: 1.5rem;
            border-bottom: none;
            text-align: center;
        }
        
        .card-header h4 {
            font-weight: 700;
            margin-bottom: 0;
            letter-spacing: 0.5px;
        }
        
        .card-body {
            padding: 2.5rem;
        }
        
        .form-label {
            font-weight: 600;
            color: #343a40;
        }
        
        .form-control {
            border-radius: 10px;
            padding: 12px 15px;
            border: 2px solid #e9ecef;
            transition: all 0.3s ease;
        }
        
        .form-control:focus {
            border-color: #28a745;
            box-shadow: 0 0 0 0.2rem rgba(40, 167, 69, 0.25);
        }
        
        .btn {
            border-radius: 10px;
            font-weight: 600;
            padding: 12px 25px;
            transition: all 0.3s ease;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #28a745, #20c997);
            border: none;
        }
        
        .btn-primary:hover {
            background: linear-gradient(135deg, #218838, #1ea085);
            transform: translateY(-2px);
        }
        
        .btn-success {
            background: linear-gradient(135deg, #28a745, #20c997);
            border: none;
        }
        
        .btn-success:hover {
            background: linear-gradient(135deg, #218838, #1ea085);
            transform: translateY(-2px);
        }
        
        .alert {
            border-radius: 10px;
            border: none;
        }
        
        .progress-container {
            background-color: #e9ecef;
            border-radius: 10px;
            height: 20px;
            overflow: hidden;
            margin: 1rem 0;
        }
        
        .progress-bar {
            background: linear-gradient(135deg, #28a745, #20c997);
            height: 100%;
            transition: width 0.6s ease;
        }
        
        .floating-shapes {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            pointer-events: none;
            z-index: -1;
        }
        
        .shape {
            position: absolute;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 50%;
            animation: float-shape 6s ease-in-out infinite;
        }
        
        .shape:nth-child(1) {
            width: 60px;
            height: 60px;
            top: 20%;
            left: 10%;
            animation-delay: 0s;
        }
        
        .shape:nth-child(2) {
            width: 100px;
            height: 100px;
            top: 60%;
            right: 10%;
            animation-delay: 2s;
        }
        
        .shape:nth-child(3) {
            width: 40px;
            height: 40px;
            bottom: 20%;
            left: 20%;
            animation-delay: 4s;
        }
        
        @keyframes float-shape {
            0%, 100% { transform: translateY(0px) rotate(0deg); }
            50% { transform: translateY(-30px) rotate(180deg); }
        }
        
        @media (max-width: 768px) {
            .hero-section h1 {
                font-size: 2rem;
            }
            
            .main-container {
                padding: 1rem;
            }
            
            .card-body {
                padding: 1.5rem;
            }
        }
    </style>
</head>
<body>
    <!-- Animated background shapes -->
    <div class="floating-shapes">
        <div class="shape"></div>
        <div class="shape"></div>
        <div class="shape"></div>
    </div>

    <div class="main-container">
        <!-- Hero Section -->
        <div class="hero-section">
            <h1><i class="bi bi-download me-3"></i><?= __('odjoo_installation') ?></h1>
            <p><?= __('system_setup_guide') ?></p>
        </div>

        <div class="card">
            <div class="card-header">
                <h4><i class="bi bi-gear-fill me-2"></i><?= __('odjoo_setup_wizard') ?></h4>

            </div>
            <div class="card-body">
                <?php if ($install_message): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="bi bi-check-circle-fill me-2"></i>
                        <?= $install_message ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>
                
                <?php if ($install_error): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="bi bi-exclamation-triangle-fill me-2"></i>
                        <?= $install_error ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>

                <?php if ($step == 1): ?>
                    <!-- Database Connection -->
                    <h5 class="card-title mb-4">
                        <i class="bi bi-1-circle-fill text-primary me-2"></i>
                        <?= __('database_information') ?>
                    </h5>
                    <p class="text-muted mb-4"><?= __('enter_database_credentials') ?></p>
                    
                    <form method="post">
                        <input type="hidden" name="csrf_token" value="<?= $csrf_token ?>">
                        <input type="hidden" name="step" value="1">
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="db_server" class="form-label"><?= __('database_server') ?></label>
                                <input type="text" class="form-control" id="db_server" name="db_server" value="localhost" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="db_name" class="form-label"><?= __('database_name') ?></label>
                                <input type="text" class="form-control" id="db_name" name="db_name" required>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="db_username" class="form-label"><?= __('database_username') ?></label>
                                <input type="text" class="form-control" id="db_username" name="db_username" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="db_password" class="form-label"><?= __('database_password') ?></label>
                                <input type="password" class="form-control" id="db_password" name="db_password">
                            </div>
                        </div>
                        
                        <div class="d-grid">
                            <button type="submit" class="btn btn-primary btn-lg">
                                <i class="bi bi-arrow-right me-2"></i><?= __('test_connection_and_continue') ?>
                            </button>
                        </div>
                    </form>

                <?php elseif ($step == 2): ?>
                    <!-- Step 2: Installation Options -->
                    <h5 class="card-title mb-4">
                        <i class="bi bi-2-circle-fill text-primary me-2"></i>
                        <?= __('installation_options') ?>
                    </h5>
                    <p class="text-muted mb-4"><?= __('db_connection_success') ?></p>
                    <form method="post" onsubmit="return confirmDropTables(this)">
                        <input type="hidden" name="csrf_token" value="<?= $csrf_token ?>">
                        <input type="hidden" name="step" value="2">
                        <div class="d-grid gap-3 mb-4">
                            <button type="submit" name="action" value="drop_and_full" class="btn btn-danger btn-lg">
                                <i class="bi bi-exclamation-triangle me-2"></i><?= __('drop_all_data_and_install') ?>
                            </button>
                        </div>
                        <div class="alert alert-info">
                            <i class="bi bi-info-circle me-2"></i>
                            <span class="text-danger"><b><?= __('warning_irreversible_action') ?></b></span>
                        </div>
                    </form>
                    <script>
                    function confirmDropTables(form) {
                        if (form.action.value === 'drop_and_full') {
                            return confirm('<?= __('confirm_drop_tables') ?>');
                        }
                        return true;
                    }
                    </script>
                <?php elseif ($step == 3): ?>
                    <!-- Adım 3: İlk Şirket Oluşturma -->
                    <h5 class="card-title mb-4">
                        <i class="bi bi-3-circle-fill text-primary me-2"></i>
                        İlk Şirket Oluşturma
                    </h5>
                    <p class="text-muted mb-4">Lütfen sisteminiz için ilk şirketi oluşturun.</p>
                    
                    <form method="post">
                        <input type="hidden" name="csrf_token" value="<?= $csrf_token ?>">
                        <input type="hidden" name="step" value="3">
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="sirket_adi" class="form-label">Şirket Adı <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="sirket_adi" name="sirket_adi" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="para_birimi" class="form-label">Para Birimi</label>
                                <select class="form-select" id="para_birimi" name="para_birimi" required>
                                    <option value="TRY" selected>TRY - Türk Lirası</option>
                                    <option value="USD">USD - Amerikan Doları</option>
                                    <option value="EUR">EUR - Euro</option>
                                    <option value="GBP">GBP - İngiliz Sterlini</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="adres" class="form-label">Adres</label>
                            <textarea class="form-control" id="adres" name="adres" rows="2"></textarea>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="telefon" class="form-label">Telefon</label>
                                <input type="text" class="form-control" id="telefon" name="telefon">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="email" class="form-label">E-posta</label>
                                <input type="email" class="form-control" id="email" name="email">
                            </div>
                        </div>
                        
                        <div class="form-check form-switch mb-3">
                            <input class="form-check-input" type="checkbox" id="stok_aktif" name="stok_aktif" value="1" checked>
                            <label class="form-check-label" for="stok_aktif">Stok Modülünü Aktif Et</label>
                        </div>
                        
                        <div class="form-check form-switch mb-4">
                            <input class="form-check-input" type="checkbox" id="teklif_aktif" name="teklif_aktif" value="1" checked>
                            <label class="form-check-label" for="teklif_aktif">Teklifler Modülünü Aktif Et</label>
                        </div>
                        
                        <div class="d-grid">
                            <button type="submit" class="btn btn-primary btn-lg">
                                <i class="bi bi-check-circle me-2"></i><?= __('create_company_and_continue') ?>
                            </button>
                        </div>
                    </form>

                <?php elseif ($step == 4): ?>
                    <!-- Adım 4: Admin Kullanıcı Oluşturma -->
                    <h5 class="card-title mb-4">
                        <i class="bi bi-4-circle-fill text-primary me-2"></i>
                        <?= __('create_admin_user') ?>
                    </h5>
                    <p class="text-muted mb-4"><?= __('company_created_successfully') ?></p>
                    
                    <form method="post">
                        <input type="hidden" name="csrf_token" value="<?= $csrf_token ?>">
                        <input type="hidden" name="step" value="4">
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="admin_ad_soyad" class="form-label"><?= __('full_name') ?> <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="admin_ad_soyad" name="admin_ad_soyad" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="admin_email" class="form-label">E-posta (Opsiyonel)</label>
                                <input type="email" class="form-control" id="admin_email" name="admin_email">
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="admin_username" class="form-label">Kullanıcı Adı <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="admin_username" name="admin_username" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="admin_password" class="form-label">Şifre <span class="text-danger">*</span></label>
                                <input type="password" class="form-control" id="admin_password" name="admin_password" required>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-4">
                                <label for="admin_language" class="form-label"><?= __('language') ?> <span class="text-danger">*</span></label>
                                <select class="form-select" id="admin_language" name="admin_language" required>
                                    <?php
                                    // Get all PHP files in the languages directory
                                    $language_files = glob(__DIR__ . '/languages/*.php');
                                    $languages = [];
                                    
                                    foreach ($language_files as $file) {
                                        $lang_code = basename($file, '.php');
                                        // Skip files with _ in the name (like tr_updated.php)
                                        if (strpos($lang_code, '_') === false) {
                                            // Get language name from the language file if possible
                                            $lang_name = strtoupper($lang_code);
                                            if (file_exists($file)) {
                                                $lang_data = include $file;
                                                if (is_array($lang_data) && isset($lang_data['language_name'])) {
                                                    $lang_name = $lang_data['language_name'];
                                                }
                                            }
                                            $selected = ($lang_code === 'tr') ? 'selected' : '';
                                            echo "<option value='$lang_code' $selected>$lang_name</option>";
                                        }
                                    }
                                    ?>
                                </select>
                            </div>
                        </div>
                        
                        <div class="d-grid">
                            <button type="submit" class="btn btn-primary btn-lg">
                                <i class="bi bi-check-circle me-2"></i><?= __('create_admin_and_complete') ?>
                            </button>
                        </div>
                    </form>

                <?php elseif ($step == 5): ?>
                    <!-- Adım 5: <?= __('installation_complete') ?> -->
                    <div class="text-center">
                        <div class="mb-4">
                            <i class="bi bi-check-circle-fill text-success" style="font-size: 4rem;"></i>
                        </div>
                        <h3 class="text-success mb-3"><?= __('installation_successful') ?>!</h3>
                        <p class="text-muted mb-4"><?= __('system_installed_successfully') ?></p>
                        
                        <div class="alert alert-danger">
                            <i class="bi bi-exclamation-triangle me-2"></i>
                            <strong>Önemli:</strong> Güvenliğiniz için lütfen sunucunuzdaki <code>install.php</code> dosyasını silin veya erişimini engelleyin.
                        </div>
                        
                        <div class="d-grid gap-2">
                            <a href="views/login.php" class="btn btn-success btn-lg">
                                <i class="bi bi-box-arrow-in-right me-2"></i><?= __('login_to_system') ?>
                            </a>
                            <a href="install.php" class="btn btn-outline-primary">
                                <i class="bi bi-house me-2"></i><?= __('back_to_home') ?>
                            </a>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html> 