<?php
require_once 'config/config.php';
require_once 'includes/auth.php';

// Zaten giriş yapmışsa yönlendir
if (isCompanyLoggedIn()) {
    redirect(COMPANY_URL . '/dashboard.php');
}

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $company_name = trim($_POST['company_name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $phone = trim($_POST['phone'] ?? ''); // Telefon opsiyonel olabilir ama formda var

    if (empty($company_name) || empty($email) || empty($password)) {
        $error = 'Lütfen zorunlu alanları doldurun.';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'Geçerli bir e-posta adresi giriniz.';
    } else {
        // E-posta kontrolü
        $stmt = $pdo->prepare("SELECT id FROM companies WHERE email = ?");
        $stmt->execute([$email]);
        if ($stmt->fetch()) {
            $error = 'Bu e-posta adresi zaten kayıtlı.';
        } else {
            try {
                $hashedPassword = hashPassword($password);

                $slug = createSlug($company_name);
                // Unique slug check
                $originalSlug = $slug;
                $i = 2;
                while (true) {
                    $checkSlug = $pdo->prepare("SELECT id FROM companies WHERE slug = ?");
                    $checkSlug->execute([$slug]);
                    if (!$checkSlug->fetch())
                        break;
                    $slug = $originalSlug . '-' . $i;
                    $i++;
                }

                $stmt = $pdo->prepare("
                    INSERT INTO companies (company_name, email, password, phone, slug, status, membership_type, created_at) 
                    VALUES (?, ?, ?, ?, ?, 'active', 'free', NOW())
                ");
                $stmt->execute([$company_name, $email, $hashedPassword, $phone, $slug]);

                $companyId = $pdo->lastInsertId();

                // Otomatik giriş yap
                companyLogin($companyId, $email);

                // Kategori seçimine yönlendir
                redirect(COMPANY_URL . '/categories.php');

            } catch (PDOException $e) {
                $error = 'Kayıt olurken bir hata oluştu: ' . $e->getMessage();
            }
        }
    }
}

$page_title = 'Firma Kayıt';
include 'includes/header.php';
?>

<div class="container py-5">
    <!-- Başlık -->
    <div class="text-center mb-5">
        <h1 class="display-4 fw-bold">Firmanızı Kaydedin</h1>
        <p class="lead text-muted">Hemen üye olun, kayak severlerle buluşun.</p>
    </div>

    <!-- Paket Karşılaştırma -->
    <div class="row justify-content-center mb-5">
        <!-- Ücretsiz Paket -->
        <div class="col-md-5 col-lg-4 mb-4">
            <div class="card h-100 border-0 shadow-sm hover-shadow transition">
                <div class="card-header bg-light text-center py-4 border-0">
                    <h3 class="my-0 fw-normal">Ücretsiz</h3>
                </div>
                <div class="card-body">
                    <h1 class="card-title pricing-card-title text-center">₺0<small
                            class="text-muted fw-light">/ay</small></h1>
                    <ul class="list-unstyled mt-3 mb-4">
                        <li class="mb-2"><i class="fas fa-check text-success me-2"></i>Temel Firma Bilgileri</li>
                        <li class="mb-2"><i class="fas fa-check text-success me-2"></i>1 Kategori Seçimi</li>
                        <li class="mb-2"><i class="fas fa-check text-success me-2"></i>Standart Listelenme</li>
                        <li class="mb-2 text-muted"><i class="fas fa-times me-2"></i>Öne Çıkarılma Yok</li>
                        <li class="mb-2 text-muted"><i class="fas fa-times me-2"></i>Sosyal Medya Linkleri Yok</li>
                        <li class="mb-2 text-muted"><i class="fas fa-times me-2"></i>Fotoğraf Galerisi Yok</li>
                    </ul>
                    <div class="d-grid gap-2">
                        <button onclick="openRegisterModal('free')" class="btn btn-outline-primary btn-lg">Üye
                            Ol</button>
                        <a href="login.php" class="btn btn-link text-decoration-none">Giriş Yap</a>
                    </div>
                </div>
            </div>
        </div>

        <!-- Gold Paket -->
        <div class="col-md-5 col-lg-4 mb-4">
            <div class="card h-100 border-primary shadow border-2">
                <div class="card-header bg-primary text-white text-center py-4 border-0 position-relative">
                    <h3 class="my-0 fw-normal">Gold</h3>
                    <span
                        class="position-absolute top-0 start-50 translate-middle badge rounded-pill bg-warning text-dark border border-light">
                        ÖNERİLEN
                    </span>
                </div>
                <div class="card-body">
                    <h1 class="card-title pricing-card-title text-center">₺499<small
                            class="text-muted fw-light">/yıl</small></h1>
                    <ul class="list-unstyled mt-3 mb-4">
                        <li class="mb-2"><i class="fas fa-check text-success me-2"></i><strong>Tüm Firma
                                Bilgileri</strong></li>
                        <li class="mb-2"><i class="fas fa-check text-success me-2"></i><strong>Sınırsız
                                Kategori</strong></li>
                        <li class="mb-2"><i class="fas fa-check text-success me-2"></i><span
                                class="badge bg-warning text-dark">Öne Çıkarılan Firma</span></li>
                        <li class="mb-2"><i class="fas fa-check text-success me-2"></i>Logo ve Kapak Resmi</li>
                        <li class="mb-2"><i class="fas fa-check text-success me-2"></i>Sosyal Medya Entegrasyonu</li>
                        <li class="mb-2"><i class="fas fa-check text-success me-2"></i>Sınırsız Fotoğraf Galerisi</li>
                        <li class="mb-2"><i class="fas fa-check text-success me-2"></i>Öncelikli Destek</li>
                    </ul>
                    <div class="d-grid gap-2">
                        <button onclick="openRegisterModal('gold')" class="btn btn-primary btn-lg">Üye Ol</button>
                        <a href="login.php" class="btn btn-link text-white text-decoration-none">Giriş Yap</a>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>

<!-- Registration Modal -->
<div class="modal fade" id="registerModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title fw-bold">Firma Kayıt</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body p-4">
                <div id="goldWarning" class="alert alert-warning d-none">
                    <i class="fas fa-crown me-2"></i><strong>Gold Üyelik:</strong> Kaydınız yönetici onayından sonra
                    aktif edilecektir.
                </div>

                <?php if ($error): ?>
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-circle me-2"></i><?= e($error) ?>
                    </div>
                <?php endif; ?>

                <form method="POST" id="registerForm">
                    <input type="hidden" name="package" id="selectedPackage" value="free">

                    <div class="row g-3">
                        <div class="col-md-6">
                            <label for="company_name" class="form-label fw-bold">Firma Adı <span
                                    class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="company_name" name="company_name" required>
                        </div>
                        <div class="col-md-6">
                            <label for="phone" class="form-label fw-bold">Telefon</label>
                            <input type="text" class="form-control" id="phone" name="phone">
                        </div>
                        <div class="col-12">
                            <label for="email" class="form-label fw-bold">E-posta <span
                                    class="text-danger">*</span></label>
                            <input type="email" class="form-control" id="email" name="email" required>
                        </div>
                        <div class="col-12">
                            <label for="password" class="form-label fw-bold">Şifre <span
                                    class="text-danger">*</span></label>
                            <input type="password" class="form-control" id="password" name="password" required>
                        </div>
                        <div class="col-12 mt-4">
                            <button type="submit" class="btn btn-success w-100 py-3 fw-bold">Kayıt Ol</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    function openRegisterModal(package) {
        document.getElementById('selectedPackage').value = package;
        const warning = document.getElementById('goldWarning');
        if (package === 'gold') {
            warning.classList.remove('d-none');
        } else {
            warning.classList.add('d-none');
        }

        var myModal = new bootstrap.Modal(document.getElementById('registerModal'));
        myModal.show();
    }

    // Show modal if there was an error
    <?php if ($error): ?>
        window.onload = function () {
            var myModal = new bootstrap.Modal(document.getElementById('registerModal'));
            myModal.show();
        }
    <?php endif; ?>
</script>

<style>
    .hover-shadow:hover {
        box-shadow: 0 .5rem 1rem rgba(0, 0, 0, .15) !important;
    }

    .transition {
        transition: all .3s ease;
    }

    .hover-scale:hover {
        transform: translateY(-2px);
    }
</style>

<?php include 'includes/footer.php'; ?>