<?php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../functions/yardimci_fonksiyonlar.php';
require_once __DIR__ . '/../functions/log_fonksiyonlari.php';
require_once __DIR__ . '/../functions/kullanici_fonksiyonlari.php';

// Set language from cookie or default to Turkish
$lang = $_COOKIE['lang'] ?? 'tr';
$lang_file = __DIR__ . "/../languages/{$lang}.php";

if (file_exists($lang_file)) {
    include $lang_file;
} else {
    // Fallback to Turkish if language file doesn't exist
    include __DIR__ . "/../languages/tr.php";
}

// Translation function if not exists
if (!function_exists('__')) {
    function __($key, $params = []) {
        global $translations;
        return $translations[$key] ?? $key;
    }
}

// Hata ayıklama başlangıcı
error_log("Login sayfasına erişim: " . date('Y-m-d H:i:s'));
error_log("POST verileri: " . print_r($_POST, true));

// Zaten giriş yapmışsa yönlendir
if(isset($_SESSION['kullanici_id'])) {
    header("Location: index.php");
    exit();
}

$hata = '';
$kullanici_adi = '';
$kayit_hatalari = [];
$kayit_basarili = false;

// Sayfaya gelen isteğin türünü belirle
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    // 1. KAYIT İŞLEMİ Mİ?
    if (isset($_POST['kayit_ol'])) {
        $ad_soyad = trim($_POST['ad_soyad'] ?? '');
        $kullanici_adi = trim($_POST['yeni_kullanici_adi'] ?? '');
        $eposta = trim($_POST['eposta'] ?? '');
        $sifre = $_POST['yeni_sifre'] ?? '';
        $sifre_tekrar = $_POST['sifre_tekrar'] ?? '';
        
        if(strlen($ad_soyad) < 3) $kayit_hatalari[] = __('full_name_min_length');
        if(strlen($kullanici_adi) < 3) $kayit_hatalari[] = __('username_min_length');
        if(!filter_var($eposta, FILTER_VALIDATE_EMAIL)) $kayit_hatalari[] = __('enter_valid_email');
        if(strlen($sifre) < 6) $kayit_hatalari[] = __('password_min_length');
        if($sifre !== $sifre_tekrar) $kayit_hatalari[] = __('passwords_dont_match');

        // Kullanıcı adı veya e-posta daha önce alınmış mı?
        if(empty($kayit_hatalari)) {
            $stmt = $db->prepare('SELECT COUNT(*) FROM kullanicilar WHERE kullanici_adi = ? OR email = ?');
            $stmt->execute([$kullanici_adi, $eposta]);
            if($stmt->fetchColumn() > 0) {
                $kayit_hatalari[] = __('username_or_email_exists');
            }
        }
        
        if(empty($kayit_hatalari)) {
            $hash = password_hash($sifre, PASSWORD_DEFAULT);
            try {
                $stmt = $db->prepare('INSERT INTO kullanicilar (ad_soyad, kullanici_adi, email, sifre, aktif, yetki_seviyesi) VALUES (?, ?, ?, ?, 1, "kullanici")');
                $stmt->execute([$ad_soyad, $kullanici_adi, $eposta, $hash]);
                $kayit_basarili = true;
            } catch (PDOException $e) {
                error_log("Kayıt hatası: " . $e->getMessage());
                $kayit_hatalari[] = __('database_error_register');
            }
        }

    // 2. GİRİŞ İŞLEMİ Mİ?
    } else {
        $kullanici_adi = trim($_POST['kullanici_adi'] ?? '');
        $sifre = $_POST['sifre'] ?? '';

        if(empty($kullanici_adi) || empty($sifre)) {
            $hata = __("username_password_required");
        } else {
    // Brute-force koruması
    if (!brute_force_kontrol()) {
                $hata = $_SESSION['hata'] ?? __("too_many_failed_attempts");
    } else {
        try {
            $stmt = $db->prepare("SELECT id, kullanici_adi, ad_soyad, sifre, yetki_seviyesi, COALESCE(yetkiler, '{}') as yetkiler FROM kullanicilar WHERE kullanici_adi = ? AND aktif = 1");
            $stmt->execute([$kullanici_adi]);
            $kullanici = $stmt->fetch();

                    if($kullanici && password_verify($sifre, $kullanici['sifre'])) {

                    // ÇOKLU ŞİRKET KONTROLÜ
                    $stmt_sirket = $db->prepare("SELECT s.id, s.sirket_adi FROM kullanici_sirket_iliskisi k_s JOIN sirketler s ON k_s.sirket_id = s.id WHERE k_s.kullanici_id = ? ORDER BY s.id ASC");
                    $stmt_sirket->execute([$kullanici['id']]);
                    $kullanici_sirketleri = $stmt_sirket->fetchAll(PDO::FETCH_ASSOC);

                        // Başarılı giriş, session'ları ayarla
                        brute_force_reset();
                        
                        // Session regenerate işlemini güvenli şekilde yap
                        if (!headers_sent()) {
                            session_regenerate_id(true);
                        }

                        $_SESSION['kullanici_id'] = $kullanici['id'];
                        $_SESSION['kullanici_adi'] = $kullanici['kullanici_adi'];
                        $_SESSION['ad_soyad'] = $kullanici['ad_soyad'];
                        $_SESSION["yetki_seviyesi"] = $kullanici["yetki_seviyesi"];
                        $_SESSION['yetkiler'] = $kullanici['yetkiler'];
                        $_SESSION['login_time'] = time();
                        $_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
                        $_SESSION['last_regen'] = time();

                        // Şirket bilgileri session'a ekleniyor
                        if (!empty($kullanici_sirketleri)) {
                        $_SESSION['aktif_sirket_id'] = $kullanici_sirketleri[0]['id'];
                        $_SESSION['aktif_sirket_adi'] = $kullanici_sirketleri[0]['sirket_adi'];
                        $_SESSION['kullanici_sirketleri'] = $kullanici_sirketleri;
                        } else {
                            // Şirketi yoksa bu değerler boş olacak
                            $_SESSION['aktif_sirket_id'] = null;
                            $_SESSION['aktif_sirket_adi'] = null;
                            $_SESSION['kullanici_sirketleri'] = [];
                        }

                        // Önce session'ı güncelle
                        if (!empty($kullanici_sirketleri)) {
                            $_SESSION['aktif_sirket_id'] = $kullanici_sirketleri[0]['id'];
                            $_SESSION['aktif_sirket_adi'] = $kullanici_sirketleri[0]['sirket_adi'];
                            $_SESSION['kullanici_sirketleri'] = $kullanici_sirketleri;
                        } else {
                            // Şirketi yoksa bu değerler boş olacak
                            $_SESSION['aktif_sirket_id'] = null;
                            $_SESSION['aktif_sirket_adi'] = null;
                            $_SESSION['kullanici_sirketleri'] = [];
                        }

                        aktif_oturum_ekle($db, $kullanici['id'], session_id(), $_SESSION['aktif_sirket_id']);

                        $ip = $_SERVER['REMOTE_ADDR'];
                        $stmt = $db->prepare("UPDATE kullanicilar SET son_giris = NOW(), son_ip = ? WHERE id = ?");
                        $stmt->execute([$ip, $kullanici['id']]);

                        // Session kurulduktan sonra log ekle
                        oturum_log_ekle($db, 'giris', $kullanici['id']);

                        // Şirket durumuna göre yönlendirme belirle
                        if (!empty($kullanici_sirketleri)) {
                            // Şirketi varsa direkt ana sayfaya yönlendir
                            if (!headers_sent()) {
                                header("Location: index.php");
                                exit();
                            } else {
                                echo '<script>window.location.href = "index.php";</script>';
                                exit();
                            }
                        } else {
                            // Şirketi yoksa şirket oluştur sayfasına yönlendir
                            if (!headers_sent()) {
                                header("Location: sirket_olustur.php");
                                exit();
                            } else {
                                echo '<script>window.location.href = "sirket_olustur.php";</script>';
                                exit();
                            }
                        }
                        
                    } else {
                        brute_force_log_attempt();
                        oturum_log_ekle($db, 'basarisiz_giris', $kullanici['id'] ?? null);
                $hata = __("invalid_username_or_password");
            }

        } catch(PDOException $e) {
            error_log("Giriş hatası: " . $e->getMessage());
            $hata = __("system_error_try_again");
        }
    }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= __("login_page_title") ?></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>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        html, body {
            height: 100%;
            overflow: hidden;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            position: relative;
        }

        /* Animated Background with Gradient Mesh */
        .animated-background {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: linear-gradient(135deg, #1e3a8a 0%, #3b82f6 50%, #06b6d4 100%);
            z-index: 0;
        }

        /* Animated Waves */
        .waves {
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 100%;
            overflow: hidden;
        }

        .wave {
            position: absolute;
            bottom: 0;
            left: 0;
            width: 200%;
            height: 100%;
            background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1200 120' preserveAspectRatio='none'%3E%3Cpath d='M321.39,56.44c58-10.79,114.16-30.13,172-41.86,82.39-16.72,168.19-17.73,250.45-.39C823.78,31,906.67,72,985.66,92.83c70.05,18.48,146.53,26.09,214.34,3V0H0V27.35A600.21,600.21,0,0,0,321.39,56.44Z' fill='rgba(255,255,255,0.05)'/%3E%3C/svg%3E") repeat-x;
            animation: wave 25s linear infinite;
        }

        .wave:nth-child(2) {
            bottom: 10px;
            animation: wave 20s linear infinite reverse;
            opacity: 0.5;
        }

        .wave:nth-child(3) {
            bottom: 20px;
            animation: wave 30s linear infinite;
            opacity: 0.3;
        }

        @keyframes wave {
            0% { transform: translateX(0); }
            100% { transform: translateX(-50%); }
        }

        /* Floating Particles */
        .particles {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            overflow: hidden;
        }

        .particle {
            position: absolute;
            width: 4px;
            height: 4px;
            background: rgba(255, 255, 255, 0.5);
            border-radius: 50%;
            animation: float-particle 15s infinite ease-in-out;
        }

        .particle:nth-child(1) { left: 10%; animation-delay: 0s; }
        .particle:nth-child(2) { left: 20%; animation-delay: 2s; }
        .particle:nth-child(3) { left: 30%; animation-delay: 4s; }
        .particle:nth-child(4) { left: 40%; animation-delay: 6s; }
        .particle:nth-child(5) { left: 50%; animation-delay: 8s; }
        .particle:nth-child(6) { left: 60%; animation-delay: 10s; }
        .particle:nth-child(7) { left: 70%; animation-delay: 12s; }
        .particle:nth-child(8) { left: 80%; animation-delay: 14s; }

        @keyframes float-particle {
            0%, 100% {
                transform: translateY(100vh) scale(0);
                opacity: 0;
            }
            10% {
                opacity: 1;
            }
            90% {
                opacity: 1;
            }
            100% {
                transform: translateY(-100px) scale(1);
            }
        }

        /* Main Container */
        .login-container {
            position: relative;
            z-index: 10;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 2rem;
            overflow-y: auto;
        }

        .login-box {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(20px);
            border-radius: 2px;
            padding: 2.5rem 2rem;
            width: 100%;
            max-width: 380px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            border: 1px solid rgba(255, 255, 255, 0.3);
            animation: slideUp 0.8s ease-out;
        }

        @keyframes slideUp {
            from {
                opacity: 0;
                transform: translateY(40px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* Header */
        .login-header {
            text-align: center;
            margin-bottom: 2rem;
        }

        .logo-box {
            width: 60px;
            height: 60px;
            background: linear-gradient(135deg, #3b82f6 0%, #1e40af 100%);
            border-radius: 2px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 1rem;
            box-shadow: 0 8px 24px rgba(59, 130, 246, 0.4);
            animation: logoFloat 3s ease-in-out infinite;
        }

        @keyframes logoFloat {
            0%, 100% { transform: translateY(0); }
            50% { transform: translateY(-8px); }
        }

        .logo-box i {
            font-size: 1.75rem;
            color: white;
        }

        .login-header h1 {
            font-size: 1.5rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.35rem;
        }

        .login-header p {
            color: #64748b;
            font-size: 0.875rem;
        }

        /* Form */
        .login-form {
            margin-top: 1.5rem;
        }

        .form-group {
            margin-bottom: 1rem;
        }

        .form-group label {
            display: block;
            font-weight: 600;
            color: #334155;
            margin-bottom: 0.4rem;
            font-size: 0.8125rem;
        }

        .input-group {
            position: relative;
        }

        .input-group i {
            position: absolute;
            left: 0.875rem;
            top: 50%;
            transform: translateY(-50%);
            color: #94a3b8;
            font-size: 0.95rem;
            transition: all 0.3s ease;
            z-index: 2;
        }

        .form-control {
            width: 100%;
            padding: 0.65rem 0.875rem 0.65rem 2.5rem;
            border: 1.5px solid #e2e8f0;
            border-radius: 2px;
            font-size: 0.875rem;
            transition: all 0.3s ease;
            background: white;
            color: #1e293b;
        }

        .form-control:focus {
            outline: none;
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.12);
            background: white;
        }

        .form-control:focus ~ i {
            color: #3b82f6;
            transform: translateY(-50%) scale(1.08);
        }

        .form-control::placeholder {
            color: #cbd5e0;
            font-size: 0.8125rem;
        }

        /* Button */
        .btn-login {
            width: 100%;
            padding: 0.75rem;
            background: linear-gradient(135deg, #3b82f6 0%, #1e40af 100%);
            color: white;
            border: none;
            border-radius: 2px;
            font-size: 0.9rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-top: 0.75rem;
            box-shadow: 0 4px 16px rgba(59, 130, 246, 0.4);
            position: relative;
            overflow: hidden;
        }

        .btn-login::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
            transition: left 0.5s ease;
        }

        .btn-login:hover::before {
            left: 100%;
        }

        .btn-login:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 24px rgba(59, 130, 246, 0.5);
        }

        .btn-login:active {
            transform: translateY(0);
        }

        /* Language Selector */
        .language-selector {
            position: absolute;
            top: 2rem;
            right: 2rem;
            z-index: 100;
        }

        .language-selector select {
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.3);
            border-radius: 2px;
            padding: 0.6rem 1rem;
            font-size: 0.9rem;
            cursor: pointer;
            transition: all 0.3s ease;
            color: #1e293b;
            font-weight: 500;
        }

        .language-selector select:hover {
            background: white;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        /* Alerts */
        .alert {
            border-radius: 2px;
            border: none;
            padding: 0.75rem 0.875rem;
            margin-bottom: 1rem;
            font-size: 0.8125rem;
            animation: alertSlide 0.5s ease-out;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        @keyframes alertSlide {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .alert-warning {
            background: #fef3c7;
            color: #92400e;
        }

        .alert-danger {
            background: #fee2e2;
            color: #991b1b;
        }

        .alert-success {
            background: #d1fae5;
            color: #065f46;
        }

        .alert i {
            font-size: 0.875rem;
        }

        .btn-close {
            background: transparent;
            border: none;
            font-size: 1.25rem;
            cursor: pointer;
            opacity: 0.6;
            transition: opacity 0.2s ease;
            line-height: 1;
        }

        .btn-close:hover {
            opacity: 1;
        }

        /* Responsive */
        @media (max-width: 576px) {
            .login-box {
                padding: 2rem 1.5rem;
                max-width: 340px;
            }

            .login-header h1 {
                font-size: 1.35rem;
            }

            .logo-box {
                width: 55px;
                height: 55px;
            }

            .logo-box i {
                font-size: 1.5rem;
            }

            .language-selector {
                top: 1rem;
                right: 1rem;
            }

            .form-control {
                padding: 0.6rem 0.75rem 0.6rem 2.25rem;
                font-size: 0.8125rem;
            }

            .input-group i {
                left: 0.75rem;
                font-size: 0.875rem;
            }
        }
    </style>
</head>
<body>
    <!-- Animated Background -->
    <div class="animated-background">
        <div class="waves">
            <div class="wave"></div>
            <div class="wave"></div>
            <div class="wave"></div>
        </div>
        <div class="particles">
            <div class="particle"></div>
            <div class="particle"></div>
            <div class="particle"></div>
            <div class="particle"></div>
            <div class="particle"></div>
            <div class="particle"></div>
            <div class="particle"></div>
            <div class="particle"></div>
        </div>
    </div>

    <!-- Language Selector -->
    <div class="language-selector">
        <form method="get" action="">
            <select name="lang" id="lang" onchange="this.form.submit()">
                <option value="tr" <?= ($lang ?? 'tr') === 'tr' ? 'selected' : '' ?>>🇹🇷 Türkçe</option>
                <option value="en" <?= ($lang ?? 'tr') === 'en' ? 'selected' : '' ?>>🇬🇧 English</option>
            </select>
        </form>
    </div>

    <!-- Login Container -->
    <div class="login-container">
        <div class="login-box">
            <div class="login-header">
                <div class="logo-box">
                    <i class="bi bi-shop"></i>
                </div>
                <h1>Begeb Creative</h1>
                <p><?= __("business_management_panel") ?></p>
            </div>

            <?php if(isset($_GET['timeout'])): ?>
                <div class="alert alert-warning">
                    <span><i class="bi bi-exclamation-triangle-fill me-2"></i><?= __("session_expired_login_again") ?></span>
                    <button type="button" class="btn-close" onclick="this.parentElement.remove()">×</button>
                </div>
            <?php endif; ?>

            <?php if(isset($_GET['hacking'])): ?>
                <div class="alert alert-danger">
                    <span><i class="bi bi-shield-exclamation me-2"></i><?= __("session_terminated_security") ?></span>
                    <button type="button" class="btn-close" onclick="this.parentElement.remove()">×</button>
                </div>
            <?php endif; ?>

            <?php if($hata): ?>
                <div class="alert alert-danger">
                    <span><i class="bi bi-exclamation-circle-fill me-2"></i><?= htmlspecialchars($hata) ?></span>
                    <button type="button" class="btn-close" onclick="this.parentElement.remove()">×</button>
                </div>
            <?php endif; ?>

            <?php if (!empty($kayit_hatalari)): ?>
                <div class="alert alert-danger">
                    <ul style="margin: 0; padding-left: 1.25rem;">
                        <?php foreach($kayit_hatalari as $err): ?>
                            <li><?= htmlspecialchars($err) ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php endif; ?>
            
            <?php if (!empty($kayit_basarili)): ?>
                <div class="alert alert-success">
                    <span><?= __("registration_successful_login_now") ?></span>
                </div>
            <?php endif; ?>

            <form method="post" autocomplete="off" class="login-form">
                <div class="form-group">
                    <label for="kullanici_adi">Kullanıcı Adı</label>
                    <div class="input-group">
                        <input type="text" class="form-control" id="kullanici_adi" name="kullanici_adi"
                            value="<?= htmlspecialchars($kullanici_adi) ?>" placeholder="Kullanıcı adınızı girin" required autofocus>
                        <i class="bi bi-person"></i>
                    </div>
                </div>

                <div class="form-group">
                    <label for="sifre">Şifre</label>
                    <div class="input-group">
                        <input type="password" class="form-control" id="sifre" name="sifre"
                            placeholder="Şifrenizi girin" required>
                        <i class="bi bi-lock"></i>
                    </div>
                </div>

                <button type="submit" class="btn-login">
                    <i class="bi bi-box-arrow-in-right me-2"></i>Giriş Yap
                </button>
            </form>
        </div>
    </div>
	
    <!-- Üye Ol Modal -->
    <div class="modal fade" id="uyeOlModal" tabindex="-1" aria-labelledby="uyeOlModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <form method="post" autocomplete="off">
            <div class="modal-header">
              <h5 class="modal-title" id="uyeOlModalLabel"><?= __("sign_up") ?></h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Kapat"></button>
            </div>
            <div class="modal-body">
              <input type="hidden" name="kayit_ol" value="1">
              <div class="mb-3">
                <label for="ad_soyad" class="form-label"><?= __("full_name") ?></label>
                <input type="text" class="form-control" id="ad_soyad" name="ad_soyad" required>
              </div>
              <div class="mb-3">
                <label for="yeni_kullanici_adi" class="form-label"><?= __("username") ?></label>
                <input type="text" class="form-control" id="yeni_kullanici_adi" name="yeni_kullanici_adi" required>
              </div>
              <div class="mb-3">
                <label for="eposta" class="form-label"><?= __("email") ?></label>
                <input type="email" class="form-control" id="eposta" name="eposta" required>
              </div>
              <div class="mb-3">
                <label for="yeni_sifre" class="form-label"><?= __("password") ?></label>
                <input type="password" class="form-control" id="yeni_sifre" name="yeni_sifre" required>
              </div>
              <div class="mb-3">
                <label for="sifre_tekrar" class="form-label"><?= __("password_repeat") ?></label>
                <input type="password" class="form-control" id="sifre_tekrar" name="sifre_tekrar" required>
              </div>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">İptal</button>
              <button type="submit" class="btn btn-primary"><?= __("register") ?></button>
            </div>
          </form>
        </div>
      </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

