<?php
/**
 * Admin Tekli Deneme Düzenleme Sayfası
 * Konum: /magaza/admin/deneme/duzenle.php
 */

require_once '../../includes/db.php';
require_once '../../includes/functions.php';

/**
 * GÜVENLİK KONTROLÜ
 */
adminCheck();

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

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

// Düzenlenecek Denemeyi Çek (Sadece single_exam olanları çeker, güvenlik önlemi)
$stmt = $db->prepare("SELECT * FROM products WHERE id = ? AND type = 'single_exam'");
$stmt->execute([$id]);
$urun = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$urun) {
    echo "<script>alert('Deneme bulunamadı veya silinmiş!'); window.location.href='index.php';</script>";
    exit;
}

$mesaj = '';

// Formdaki seçim alanları için Yayın Evlerini (Markaları) çek
$markalar = $db->query("SELECT id, name FROM brands ORDER BY name ASC")->fetchAll();

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['deneme_guncelle'])) {
    
    // 1. TEMEL BİLGİLERİ AL VE TEMİZLE
    $name = trim($_POST['name']);
    $exam_type = !empty($_POST['exam_type']) ? $_POST['exam_type'] : NULL;
    $brand_id = !empty($_POST['brand_id']) ? $_POST['brand_id'] : NULL;
    $description = trim($_POST['description']);
    $sku = !empty($_POST['sku']) ? trim($_POST['sku']) : NULL;
    
    // Deneme Özel Bilgileri
    $exam_publication_date = !empty($_POST['exam_publication_date']) ? trim($_POST['exam_publication_date']) : NULL;
    $exam_date = !empty($_POST['exam_date']) ? $_POST['exam_date'] : NULL;
    
    // SEO Link (Slug) Oluşturma
    $slug = seoLink($name);

    // 2. FİYAT, KDV VE STOK VERİLERİ
    $price = $_POST['price'];
    $discount_price = !empty($_POST['discount_price']) ? $_POST['discount_price'] : NULL;
    $vat_rate = isset($_POST['vat_rate']) ? (int)$_POST['vat_rate'] : 0;
    $vat_included = isset($_POST['vat_included']) ? (int)$_POST['vat_included'] : 1;
    $stock_quantity = !empty($_POST['stock_quantity']) ? (int)$_POST['stock_quantity'] : 0;
    
    // 3. ZAMANLAMA
    $publish_date = !empty($_POST['publish_date']) ? $_POST['publish_date'] : date('Y-m-d H:i:s');
    $end_date = !empty($_POST['end_date']) ? $_POST['end_date'] : NULL;

    // Zorunlu Alan Kontrolü
    if (empty($name) || empty($price) || empty($exam_type)) {
        $mesaj = "<div class='alert alert-warning shadow-sm'><i class='bi bi-exclamation-triangle me-2'></i>Deneme adı, türü ve fiyat alanları zorunludur.</div>";
    } else {
        // Benzersiz Slug Kontrolü (Mevcut ürünün kendi ID'si hariç tutulur)
        $check = $db->prepare("SELECT id FROM products WHERE slug = ? AND id != ?");
        $check->execute([$slug, $id]);
        if ($check->rowCount() > 0) { 
            $slug = $slug . '-' . time(); 
        }

        try {
            $db->beginTransaction();

            // 1. Denemeyi Güncelle
            $guncelle_stmt = $db->prepare("UPDATE products SET 
                brand_id = ?, 
                name = ?, 
                slug = ?, 
                description = ?, 
                price = ?, 
                discount_price = ?, 
                vat_rate = ?, 
                vat_included = ?, 
                stock_quantity = ?, 
                sku = ?, 
                publish_date = ?, 
                end_date = ?, 
                exam_type = ?, 
                exam_publication_date = ?, 
                exam_date = ? 
                WHERE id = ? AND type = 'single_exam'");
            
            $guncelle_stmt->execute([$brand_id, $name, $slug, $description, $price, $discount_price, $vat_rate, $vat_included, $stock_quantity, $sku, $publish_date, $end_date, $exam_type, $exam_publication_date, $exam_date, $id]);
            
            // 2. Çoklu Görsel Yükleme İşlemi (Eğer yeni dosya seçildiyse mevcutlara ekler)
            if (isset($_FILES['images']) && !empty($_FILES['images']['name'][0])) {
                $dosya_sayisi = count($_FILES['images']['name']);
                
                // Eğer daha önce hiç is_main=1 olan resim yoksa, ilk yükleneni main yap
                $check_main = $db->prepare("SELECT id FROM product_images WHERE product_id = ? AND is_main = 1");
                $check_main->execute([$id]);
                $has_main = $check_main->rowCount() > 0;

                for ($i = 0; $i < $dosya_sayisi; $i++) {
                    if ($_FILES['images']['error'][$i] === UPLOAD_ERR_OK) {
                        $tmp_name = $_FILES['images']['tmp_name'][$i];
                        $orijinal_isim = $_FILES['images']['name'][$i];
                        $optimize_yol = uploadAndOptimizeImage($tmp_name, $orijinal_isim);
                        if ($optimize_yol) {
                            $is_main = (!$has_main && $i === 0) ? 1 : 0; 
                            $db->prepare("INSERT INTO product_images (product_id, image_path, is_main) VALUES (?, ?, ?)")->execute([$id, $optimize_yol, $is_main]);
                        }
                    }
                }
            }

            $db->commit();
            $mesaj = "<div class='alert alert-success shadow-sm'><i class='bi bi-check-circle-fill me-2'></i>Deneme bilgileri başarıyla güncellendi! <a href='index.php' class='fw-bold'>Listeye Dön</a></div>";
            
            // Veriyi ekrana güncel yansıtmak için tekrar çekiyoruz
            $stmt->execute([$id]);
            $urun = $stmt->fetch(PDO::FETCH_ASSOC);

        } catch (Exception $e) {
            $db->rollBack();
            $mesaj = "<div class='alert alert-danger shadow-sm'><i class='bi bi-x-circle-fill me-2'></i>Hata Oluştu: " . $e->getMessage() . "</div>";
        }
    }
}

// Mevcut görselleri çek (Silme ve önizleme için)
$gorseller = $db->prepare("SELECT * FROM product_images WHERE product_id = ? ORDER BY is_main DESC, id ASC");
$gorseller->execute([$id]);
$urun_gorselleri = $gorseller->fetchAll(PDO::FETCH_ASSOC);

// DateTime formatlamaları (HTML5 datetime-local inputu için)
$formated_publish = $urun['publish_date'] ? date('Y-m-d\TH:i', strtotime($urun['publish_date'])) : '';
$formated_end = $urun['end_date'] ? date('Y-m-d\TH:i', strtotime($urun['end_date'])) : '';

// --- TASARIM BAŞLANGICI ---
require_once '../header.php';
?>

<div class="row mb-4 align-items-center">
    <div class="col-6">
        <h2 class="fw-bold mb-0 text-dark"><i class="bi bi-pencil-square text-primary me-2"></i>Deneme Düzenle: <span class="text-secondary fs-4"><?= htmlspecialchars($urun['name']) ?></span></h2>
    </div>
    <div class="col-6 text-end">
        <a href="index.php" class="btn btn-outline-secondary shadow-sm fw-bold"><i class="bi bi-arrow-left me-1"></i> İptal / Geri Dön</a>
    </div>
</div>

<?= $mesaj; ?>

<form action="duzenle.php?id=<?= $id ?>" method="POST" enctype="multipart/form-data" class="mb-5">
    <div class="row">
        <div class="col-md-8">
            <div class="card shadow-sm border-0 mb-4 border-start border-4 border-primary">
                <div class="card-header bg-dark text-white py-3">
                    <h5 class="card-title mb-0 fw-bold small text-uppercase"><i class="bi bi-info-circle me-2"></i>Deneme Temel Bilgileri</h5>
                </div>
                <div class="card-body p-4">
                    <div class="row mb-4">
                        <div class="col-md-8">
                            <label class="form-label fw-bold text-muted small text-uppercase">Deneme Adı *</label>
                            <input type="text" name="name" class="form-control form-control-lg border-2" required value="<?= htmlspecialchars($urun['name']) ?>">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label fw-bold text-muted small text-uppercase">Ürün Kodu (SKU)</label>
                            <input type="text" name="sku" class="form-control form-control-lg border-2" value="<?= htmlspecialchars($urun['sku']) ?>">
                        </div>
                    </div>
                    
                    <div class="row mb-4">
                        <div class="col-md-4">
                            <label class="form-label fw-bold text-muted small text-uppercase">Sınav Türü *</label>
                            <select name="exam_type" class="form-select border-2" required>
                                <option value="">Seçiniz...</option>
                                <option value="TYT" <?= $urun['exam_type'] == 'TYT' ? 'selected' : '' ?>>TYT</option>
                                <option value="AYT" <?= $urun['exam_type'] == 'AYT' ? 'selected' : '' ?>>AYT</option>
                                <option value="YKS" <?= $urun['exam_type'] == 'YKS' ? 'selected' : '' ?>>YKS (TYT + AYT)</option>
                                <option value="LGS" <?= $urun['exam_type'] == 'LGS' ? 'selected' : '' ?>>LGS</option>
                                <option value="KPSS" <?= $urun['exam_type'] == 'KPSS' ? 'selected' : '' ?>>KPSS</option>
                                <option value="Ara Sınıf" <?= $urun['exam_type'] == 'Ara Sınıf' ? 'selected' : '' ?>>Ara Sınıf</option>
                                <option value="DGS" <?= $urun['exam_type'] == 'DGS' ? 'selected' : '' ?>>DGS</option>
                            </select>
                        </div>
                        <div class="col-md-8">
                            <label class="form-label fw-bold text-muted small text-uppercase">Yayın Evi / Marka</label>
                            <select name="brand_id" class="form-select border-2">
                                <option value="">Seçiniz...</option>
                                <?php foreach($markalar as $marka): ?>
                                    <option value="<?= $marka['id']; ?>" <?= $urun['brand_id'] == $marka['id'] ? 'selected' : '' ?>><?= htmlspecialchars($marka['name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="row mb-4">
                        <div class="col-md-6">
                            <label class="form-label fw-bold text-muted small text-uppercase">Yayın Tarihi</label>
                            <input type="text" name="exam_publication_date" class="form-control border-2" value="<?= htmlspecialchars($urun['exam_publication_date']) ?>">
                            <div class="form-text small">Denemenin basıldığı veya müfredat yılı.</div>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold text-muted small text-uppercase">Uygulanma Tarihi</label>
                            <input type="date" name="exam_date" class="form-control border-2" value="<?= $urun['exam_date'] ?>">
                            <div class="form-text small">Eğer Türkiye Geneli ise sınavın yapıldığı tarih.</div>
                        </div>
                    </div>

                    <div class="mb-4">
                        <label class="form-label fw-bold text-muted small text-uppercase">Detaylı Açıklama</label>
                        <textarea name="description" id="editor" class="form-control border-2" rows="10"><?= htmlspecialchars($urun['description']) ?></textarea>
                    </div>

                    <?php if(count($urun_gorselleri) > 0): ?>
                    <div class="mb-3 p-3 bg-white rounded border border-1">
                        <label class="form-label fw-bold text-muted small text-uppercase d-block mb-3"><i class="bi bi-images me-1"></i>Mevcut Görseller</label>
                        <div class="d-flex flex-wrap gap-2">
                            <?php foreach($urun_gorselleri as $gorsel): ?>
                                <div class="position-relative border rounded p-1" style="width: 80px; height: 80px;">
                                    <img src="/magaza/<?= $gorsel['image_path'] ?>" class="w-100 h-100 object-fit-cover rounded">
                                    <?php if($gorsel['is_main'] == 1): ?>
                                        <span class="badge bg-success position-absolute bottom-0 start-0 w-100" style="font-size:0.6rem;">KAPAK</span>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        <small class="text-muted d-block mt-2">Not: Görsel silme ve kapak yapma işlemlerini ana "Ürünler" modülünden yönetebilirsiniz.</small>
                    </div>
                    <?php endif; ?>

                    <div class="mb-0 p-3 bg-light rounded border-2 border-dashed border-primary">
                        <label class="form-label fw-bold text-primary small text-uppercase"><i class="bi bi-plus-circle me-1"></i>Yeni Görsel İlave Et (Çoklu Seçim)</label>
                        <input type="file" name="images[]" class="form-control border-0 bg-transparent" accept="image/*" multiple>
                        <div class="form-text text-muted small mt-2">Seçtiğiniz görseller mevcut görsellerin yanına eklenecektir.</div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-4">
            <div class="card shadow-sm mb-4 border-success border-top border-4">
                <div class="card-header bg-success text-white py-3 text-center">
                    <h5 class="card-title mb-0 fw-bold small text-uppercase"><i class="bi bi-cash-stack me-2"></i>Fiyat & Stok</h5>
                </div>
                <div class="card-body p-4">
                    <div class="mb-4">
                        <label class="form-label fw-bold text-muted small text-uppercase">Satış Fiyatı (₺) *</label>
                        <div class="input-group">
                            <span class="input-group-text bg-light fw-bold border-2 border-end-0">₺</span>
                            <input type="number" step="0.01" name="price" class="form-control form-control-lg fw-bold text-success border-2 border-start-0" required value="<?= $urun['price'] ?>">
                        </div>
                    </div>
                    <div class="mb-4">
                        <label class="form-label fw-bold text-danger small text-uppercase">İndirimli Fiyat (₺)</label>
                        <div class="input-group">
                            <span class="input-group-text bg-light text-danger fw-bold border-2 border-end-0">₺</span>
                            <input type="number" step="0.01" name="discount_price" class="form-control fw-bold text-danger border-2 border-start-0" value="<?= $urun['discount_price'] ?>">
                        </div>
                    </div>
                    
                    <div class="row mb-4">
                        <div class="col-6">
                            <label class="form-label fw-bold text-muted small text-uppercase">KDV Oranı</label>
                            <div class="input-group">
                                <span class="input-group-text bg-light fw-bold border-2">%</span>
                                <select name="vat_rate" class="form-select fw-bold border-2">
                                    <option value="0" <?= $urun['vat_rate'] == 0 ? 'selected' : '' ?>>0</option>
                                    <option value="1" <?= $urun['vat_rate'] == 1 ? 'selected' : '' ?>>1</option>
                                    <option value="10" <?= $urun['vat_rate'] == 10 ? 'selected' : '' ?>>10</option>
                                    <option value="20" <?= $urun['vat_rate'] == 20 ? 'selected' : '' ?>>20</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-6">
                            <label class="form-label fw-bold text-muted small text-uppercase">KDV Durumu</label>
                            <select name="vat_included" class="form-select fw-bold border-2">
                                <option value="1" <?= $urun['vat_included'] == 1 ? 'selected' : '' ?>>KDV Dahil</option>
                                <option value="0" <?= $urun['vat_included'] == 0 ? 'selected' : '' ?>>KDV Hariç</option>
                            </select>
                        </div>
                    </div>

                    <div class="mb-0">
                        <label class="form-label fw-bold text-muted small text-uppercase">Mevcut Stok Adedi</label>
                        <input type="number" name="stock_quantity" class="form-control fw-bold border-2" value="<?= $urun['stock_quantity'] ?>">
                    </div>
                </div>
            </div>

            <div class="card shadow-sm mb-4">
                <div class="card-header bg-white border-bottom py-3">
                    <h5 class="card-title mb-0 fw-bold text-secondary small text-uppercase"><i class="bi bi-clock-history me-2 text-warning"></i>Zamanlama</h5>
                </div>
                <div class="card-body p-4">
                    <div class="mb-4">
                        <label class="form-label fw-bold text-muted small text-uppercase">Sitede Yayınlanma Tarihi</label>
                        <input type="datetime-local" name="publish_date" class="form-control border-2" value="<?= $formated_publish ?>">
                    </div>
                    <div class="mb-0">
                        <label class="form-label fw-bold text-muted small text-uppercase">Yayından Kalkış (Opsiyonel)</label>
                        <input type="datetime-local" name="end_date" class="form-control border-2" value="<?= $formated_end ?>">
                    </div>
                </div>
            </div>

            <div class="d-grid gap-2">
                <button type="submit" name="deneme_guncelle" class="btn btn-primary btn-lg fw-bold shadow-sm py-3">
                    <i class="bi bi-save-fill me-2"></i>GÜNCELLEMELERİ KAYDET
                </button>
            </div>
        </div>
    </div>
</form>

<script src="https://cdn.tiny.cloud/1/vrj5aef2zvyqm82vfs8ay0ltvq1l9v6bmkio7ovzkqj8trrq/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>
<script>
    tinymce.init({
        selector: '#editor',
        height: 350,
        menubar: false,
        plugins: 'lists link table code wordcount',
        toolbar: 'undo redo | formatselect | bold italic textcolor | alignleft aligncenter alignright alignjustify | bullist numlist | removeformat',
        language: 'tr'
    });
</script>

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