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

// 1. ID Kontrolü
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("Location: index.php");
    exit;
}

$id = (int)$_GET['id'];

// 2. Mevcut Veriyi Çek
$stmt = $db->prepare("SELECT * FROM exam_calendar WHERE id = ?");
$stmt->execute([$id]);
$item = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$item) {
    header("Location: index.php");
    exit;
}

// 3. Form Gönderildiğinde Güncelle
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ü temizle, değilse başvuru tarihlerini temizle
    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'];

    $update_sql = "UPDATE exam_calendar SET 
                    title = ?, 
                    exam_type = ?, 
                    exam_date = ?, 
                    application_start_date = ?,
                    application_end_date = ?,
                    is_official = ?, 
                    brand_id = ?, 
                    product_id = ?, 
                    description = ?, 
                    status = ? 
                   WHERE id = ?";
    
    $update_stmt = $db->prepare($update_sql);
    if ($update_stmt->execute([$title, $exam_type, $exam_date, $application_start_date, $application_end_date, $is_official, $brand_id, $product_id, $description, $status, $id])) {
        $success = "Kayıt başarıyla güncellendi.";
        // Güncel veriyi tekrar çekelim
        $stmt->execute([$id]);
        $item = $stmt->fetch(PDO::FETCH_ASSOC);
    } else {
        $error = "Güncelleme sırasında bir hata oluştu.";
    }
}

// Markaları ve Ürünleri (Sadece Tekli Denemeleri) ç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 = "Sınav/Deneme Düzenle";
require_once '../header.php';
?>

<div class="container-fluid px-4">
    <h1 class="mt-4">Takvim Kaydını Düzenle</h1>
    <ol class="breadcrumb mb-4">
        <li class="breadcrumb-item"><a href="index.php">Takvim Listesi</a></li>
        <li class="breadcrumb-item active">Düzenle</li>
    </ol>

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

    <?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 text-dark">Sınav/Deneme Başlığı *</label>
                        <input type="text" name="title" class="form-control" value="<?= htmlspecialchars($item['title']) ?>" required>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label fw-bold text-dark">Sınav Türü *</label>
                        <select name="exam_type" class="form-select" required>
                            <option value="TYT" <?= $item['exam_type'] == 'TYT' ? 'selected' : '' ?>>TYT</option>
                            <option value="AYT" <?= $item['exam_type'] == 'AYT' ? 'selected' : '' ?>>AYT</option>
                            <option value="YDT" <?= $item['exam_type'] == 'YDT' ? 'selected' : '' ?>>YDT</option>
                            <option value="LGS" <?= $item['exam_type'] == 'LGS' ? 'selected' : '' ?>>LGS</option>
                            <option value="AGS" <?= $item['exam_type'] == 'AGS' ? 'selected' : '' ?>>AGS</option>
                            <option value="KPSS" <?= $item['exam_type'] == 'KPSS' ? 'selected' : '' ?>>KPSS</option>
                            <option value="Diğer" <?= $item['exam_type'] == 'Diğer' ? 'selected' : '' ?>>Diğer</option>
                        </select>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-4 mb-3">
                        <label class="form-label fw-bold text-dark">Sınav Tarihi *</label>
                        <input type="date" name="exam_date" class="form-control" value="<?= $item['exam_date'] ?>" 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" <?= $item['is_official'] == 1 ? 'checked' : '' ?>>
                            <label class="form-check-label ms-2" for="is_official">Bu Bir Resmi Sınav</label>
                        </div>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label fw-bold text-dark">Durum</label>
                        <select name="status" class="form-select">
                            <option value="1" <?= $item['status'] == 1 ? 'selected' : '' ?>>Aktif (Sitede Görünsün)</option>
                            <option value="0" <?= $item['status'] == 0 ? 'selected' : '' ?>>Pasif</option>
                        </select>
                    </div>
                </div>

                <div class="row bg-light p-3 rounded mb-4 border mx-0" id="store_relations" style="<?= $item['is_official'] == 1 ? 'display:none;' : 'display:flex;' ?>">
                    <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 small fw-bold text-muted">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'] ?>" <?= $item['brand_id'] == $b['id'] ? 'selected' : '' ?>><?= htmlspecialchars($b['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label small fw-bold text-muted">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'] ?>" <?= $item['product_id'] == $p['id'] ? 'selected' : '' ?>><?= 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 mx-0" id="official_dates" style="<?= $item['is_official'] == 1 ? 'display:flex;' : '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" value="<?= $item['application_start_date'] ?>">
                        <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" value="<?= $item['application_end_date'] ?>">
                        <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 text-dark">Açıklama / Detaylar</label>
                    <textarea name="description" class="form-control" rows="3"><?= htmlspecialchars($item['description']) ?></textarea>
                </div>

                <div class="d-flex gap-2">
                    <button type="submit" class="btn btn-primary px-5"><i class="bi bi-check-lg me-2"></i>Değişiklikleri Kaydet</button>
                    <a href="index.php" class="btn btn-outline-secondary px-4">Vazgeç</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'; ?>