<?php
require_once '../../includes/db.php';

// Form gönderildiğinde veritabanına kaydet
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $title = trim($_POST['title']);
    $exam_type = trim($_POST['exam_type']);
    $exam_date = $_POST['exam_date'];
    $is_official = isset($_POST['is_official']) ? 1 : 0;
    
    // Eğer resmi sınavsa marka ve ürünü NULL yap, değilse başvuru tarihlerini NULL yap
    if ($is_official == 1) {
        $brand_id = NULL;
        $product_id = NULL;
        $application_start_date = !empty($_POST['application_start_date']) ? $_POST['application_start_date'] : NULL;
        $application_end_date = !empty($_POST['application_end_date']) ? $_POST['application_end_date'] : NULL;
    } else {
        $brand_id = !empty($_POST['brand_id']) ? $_POST['brand_id'] : NULL;
        $product_id = !empty($_POST['product_id']) ? $_POST['product_id'] : NULL;
        $application_start_date = NULL;
        $application_end_date = NULL;
    }
    
    $description = trim($_POST['description']);
    $status = $_POST['status'];

    $stmt = $db->prepare("INSERT INTO exam_calendar (title, exam_type, exam_date, application_start_date, application_end_date, is_official, brand_id, product_id, description, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    if ($stmt->execute([$title, $exam_type, $exam_date, $application_start_date, $application_end_date, $is_official, $brand_id, $product_id, $description, $status])) {
        header("Location: index.php?success=1");
        exit;
    } else {
        $error = "Ekleme sırasında bir hata oluştu.";
    }
}

// Markaları ve Ürünleri (Sadece Tekli Denemeleri) Selectbox için çekiyoruz
$brands = $db->query("SELECT id, name FROM brands WHERE status=1 ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);
$products = $db->query("SELECT id, name FROM products WHERE type='single_exam' AND status=1 ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);

$page_title = "Yeni Sınav/Deneme Ekle";
require_once '../header.php';
?>

<div class="container-fluid px-4">
    <h1 class="mt-4">Yeni Sınav/Deneme Ekle</h1>
    <ol class="breadcrumb mb-4">
        <li class="breadcrumb-item"><a href="index.php">Takvim Listesi</a></li>
        <li class="breadcrumb-item active">Ekle</li>
    </ol>

    <?php if(isset($error)): ?>
        <div class="alert alert-danger"><?= $error ?></div>
    <?php endif; ?>

    <div class="card mb-4 shadow-sm border-0">
        <div class="card-body">
            <form method="POST" action="">
                
                <div class="row">
                    <div class="col-md-8 mb-3">
                        <label class="form-label fw-bold">Sınav/Deneme Başlığı *</label>
                        <input type="text" name="title" class="form-control" placeholder="Örn: 2026 YKS 1. Oturum (TYT)" required>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label fw-bold">Sınav Türü *</label>
                        <select name="exam_type" class="form-select" required>
                            <option value="">Seçiniz...</option>
                            <option value="TYT">TYT</option>
                            <option value="AYT">AYT</option>
                            <option value="YDT">YDT</option>
                            <option value="LGS">LGS</option>
                            <option value="AGS">AGS</option>
                            <option value="KPSS">KPSS</option>
                            <option value="Diğer">Diğer</option>
                        </select>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-4 mb-3">
                        <label class="form-label fw-bold">Sınav Tarihi *</label>
                        <input type="date" name="exam_date" class="form-control" required>
                    </div>
                    <div class="col-md-4 mb-3 d-flex align-items-end pb-2">
                        <div class="form-check form-switch fs-5">
                            <input class="form-check-input" type="checkbox" name="is_official" id="is_official" value="1">
                            <label class="form-check-label ms-2" for="is_official">Bu Bir Resmi Sınav (ÖSYM/MEB)</label>
                        </div>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label fw-bold">Durum</label>
                        <select name="status" class="form-select">
                            <option value="1">Aktif (Sitede Görünsün)</option>
                            <option value="0">Pasif</option>
                        </select>
                    </div>
                </div>

                <div class="row bg-light p-3 rounded mb-4 border" id="store_relations">
                    <h6 class="fw-bold mb-3"><i class="bi bi-shop text-primary me-2"></i>Mağaza Eşleştirmesi (Yayın Denemeleri İçin)</h6>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Yayın Evi (Marka)</label>
                        <select name="brand_id" class="form-select">
                            <option value="">-- Bağımsız / Belirtilmemiş --</option>
                            <?php foreach($brands as $b): ?>
                                <option value="<?= $b['id'] ?>"><?= htmlspecialchars($b['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Satıştaki Ürün ile Eşleştir</label>
                        <select name="product_id" class="form-select">
                            <option value="">-- Ürün Satışta Değil (Gelince Haber Ver) --</option>
                            <?php foreach($products as $p): ?>
                                <option value="<?= $p['id'] ?>"><?= htmlspecialchars($p['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <div class="row bg-danger bg-opacity-10 p-3 rounded mb-4 border border-danger border-opacity-25" id="official_dates" style="display:none;">
                    <h6 class="fw-bold mb-3 text-danger"><i class="bi bi-calendar2-check me-2"></i>Başvuru Tarihleri (Sadece Resmi Sınavlar İçin)</h6>
                    <div class="col-md-6 mb-3">
                        <label class="form-label text-danger fw-bold">Başvuru Başlangıç Tarihi</label>
                        <input type="date" name="application_start_date" class="form-control border-danger">
                        <small class="text-muted">Öğrencilere "Başvurular Başladı" uyarısı göstermek için.</small>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label text-danger fw-bold">Başvuru Bitiş Tarihi</label>
                        <input type="date" name="application_end_date" class="form-control border-danger">
                        <small class="text-muted">Öğrencilere "Son X Gün" uyarısı göstermek için.</small>
                    </div>
                </div>

                <div class="mb-4">
                    <label class="form-label fw-bold">Açıklama / Detaylar</label>
                    <textarea name="description" class="form-control" rows="3" placeholder="Sınav veya başvurular hakkında kısa bilgi..."></textarea>
                </div>

                <div class="d-flex gap-2">
                    <button type="submit" class="btn btn-success px-5"><i class="bi bi-save me-2"></i>Kaydet</button>
                    <a href="index.php" class="btn btn-secondary px-4">İptal</a>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    // Resmi Sınav seçeneği değiştiğinde alanların görünürlüğünü ayarla
    document.getElementById('is_official').addEventListener('change', function() {
        const storeBlock = document.getElementById('store_relations');
        const officialDatesBlock = document.getElementById('official_dates');
        
        if(this.checked) {
            storeBlock.style.display = 'none';
            officialDatesBlock.style.display = 'flex';
        } else {
            storeBlock.style.display = 'flex';
            officialDatesBlock.style.display = 'none';
        }
    });
</script>

<?php require_once '../footer.php'; ?>