<?php
/**
 * Admin Tekli Deneme Listesi (Akıllı Marka Logosu Gösterimi & AJAX WEBP)
 * Konum: /magaza/admin/deneme/index.php
 */

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

adminCheck(); 

// 1. AJAX: HIZLI DURUM (AKTİF/PASİF) GÜNCELLEME MOTORU
if (isset($_POST['ajax_status_toggle']) && isset($_POST['product_id'])) {
    header('Content-Type: application/json');
    $product_id = (int)$_POST['product_id'];
    $new_status = (int)$_POST['new_status'];
    
    $stmt = $db->prepare("UPDATE products SET status = ? WHERE id = ? AND type = 'single_exam'");
    if ($stmt->execute([$new_status, $product_id])) {
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Veritabanı hatası.']);
    }
    exit;
}

// YENİ AJAX: PAKET SATIŞI (GEÇMİŞ DENEMELER İÇİN İZİN) GÜNCELLEME MOTORU
if (isset($_POST['ajax_package_toggle']) && isset($_POST['product_id'])) {
    header('Content-Type: application/json');
    $product_id = (int)$_POST['product_id'];
    $new_status = (int)$_POST['new_status'];
    
    $stmt = $db->prepare("UPDATE products SET allow_custom_package = ? WHERE id = ? AND type = 'single_exam'");
    if ($stmt->execute([$new_status, $product_id])) {
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Veritabanı hatası.']);
    }
    exit;
}

// 2. AJAX: HIZLI GÖRSEL YÜKLEME, WEBP DÖNÜŞTÜRME
if (isset($_POST['ajax_image_upload']) && isset($_FILES['ajax_file']) && isset($_POST['product_id'])) {
    header('Content-Type: application/json');
    $product_id = (int)$_POST['product_id'];
    
    $izin_verilen_uzantilar = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
    $dosya_uzantisi = strtolower(pathinfo($_FILES['ajax_file']['name'], PATHINFO_EXTENSION));
    $tmp_name = $_FILES['ajax_file']['tmp_name'];
    
    if (!in_array($dosya_uzantisi, $izin_verilen_uzantilar)) {
        echo json_encode(['success' => false, 'message' => 'Sadece JPG, PNG veya WEBP yüklenebilir.']);
        exit;
    }

    $yil = date('Y');
    $ay = date('m');
    $upload_dir = '../../uploads/products/' . $yil . '/' . $ay . '/';
    $db_dir = 'uploads/products/' . $yil . '/' . $ay . '/';

    if (!is_dir($upload_dir)) { mkdir($upload_dir, 0755, true); }

    $yeni_dosya_adi = 'deneme-' . $product_id . '-' . time() . '.webp';
    $hedef_yol = $upload_dir . $yeni_dosya_adi;

    $image = null;
    if ($dosya_uzantisi == 'jpg' || $dosya_uzantisi == 'jpeg') {
        $image = @imagecreatefromjpeg($tmp_name);
    } elseif ($dosya_uzantisi == 'png') {
        $image = @imagecreatefrompng($tmp_name);
        if ($image) {
            imagepalettetotruecolor($image);
            imagealphablending($image, true);
            imagesavealpha($image, true);
        }
    } elseif ($dosya_uzantisi == 'webp') {
        $image = @imagecreatefromwebp($tmp_name);
    } elseif ($dosya_uzantisi == 'gif') {
        $image = @imagecreatefromgif($tmp_name);
    }

    if ($image) {
        if (imagewebp($image, $hedef_yol, 80)) {
            imagedestroy($image);
            $db_yolu = $db_dir . $yeni_dosya_adi;
            
            $eski_img_stmt = $db->prepare("SELECT id, image_path FROM product_images WHERE product_id = ? AND is_main = 1");
            $eski_img_stmt->execute([$product_id]);
            $eski_img = $eski_img_stmt->fetch();

            if ($eski_img) {
                if (!empty($eski_img['image_path']) && file_exists('../../' . $eski_img['image_path'])) {
                    unlink('../../' . $eski_img['image_path']);
                }
                $db->prepare("UPDATE product_images SET image_path = ? WHERE id = ?")->execute([$db_yolu, $eski_img['id']]);
            } else {
                $db->prepare("INSERT INTO product_images (product_id, image_path, is_main, sort_order) VALUES (?, ?, 1, 0)")->execute([$product_id, $db_yolu]);
            }

            echo json_encode(['success' => true, 'new_image_url' => '/magaza/' . $db_yolu]);
        } else {
            echo json_encode(['success' => false, 'message' => 'WEBP dönüştürme işlemi başarısız oldu.']);
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Geçersiz veya bozuk görsel dosyası.']);
    }
    exit;
}

// --- FİLTRELEME VE ARAMA AYARLARI ---
$where_clauses = ["p.type = 'single_exam'"];
$params = [];

$arama = isset($_GET['q']) ? trim($_GET['q']) : '';
if ($arama !== '') {
    $where_clauses[] = "(p.name LIKE ? OR p.sku LIKE ?)";
    $params[] = "%$arama%";
    $params[] = "%$arama%";
}

$tur_filtre = isset($_GET['tur']) ? $_GET['tur'] : '';
if ($tur_filtre !== '') {
    $where_clauses[] = "p.exam_type = ?";
    $params[] = $tur_filtre;
}

$marka_filtre = (isset($_GET['marka']) && $_GET['marka'] !== '') ? (int)$_GET['marka'] : '';
if ($marka_filtre !== '') {
    $where_clauses[] = "p.brand_id = ?";
    $params[] = $marka_filtre;
}

$where_sql = count($where_clauses) > 0 ? "WHERE " . implode(" AND ", $where_clauses) : "";

// --- SAYFALAMA ---
$sayfa = isset($_GET['s']) ? (int)$_GET['s'] : 1;
if ($sayfa < 1) $sayfa = 1;
$limit = 20;
$offset = ($sayfa - 1) * $limit;

$toplam_sorgu = $db->prepare("SELECT COUNT(p.id) FROM products p $where_sql");
$toplam_sorgu->execute($params);
$toplam_urun = $toplam_sorgu->fetchColumn();
$toplam_sayfa = ceil($toplam_urun / $limit);

// --- TEKLİ DENEMELERİ ÇEKME ---
$sql = "
    SELECT 
        p.id, p.name, p.price, p.stock_quantity, p.status, p.sku, 
        p.exam_type, p.exam_publication_date, p.allow_custom_package,
        b.name as brand_name, b.logo as brand_logo,
        (SELECT image_path FROM product_images WHERE product_id = p.id AND is_main = 1 LIMIT 1) as main_image
    FROM products p
    LEFT JOIN brands b ON p.brand_id = b.id
    $where_sql
    ORDER BY p.id DESC
    LIMIT $limit OFFSET $offset
";

$stmt = $db->prepare($sql);
$stmt->execute($params);
$urunler = $stmt->fetchAll();

$markalar = $db->query("SELECT id, name FROM brands ORDER BY name ASC")->fetchAll();
$turler = $db->query("SELECT DISTINCT exam_type FROM products WHERE type = 'single_exam' AND exam_type IS NOT NULL")->fetchAll(PDO::FETCH_COLUMN);

require_once '../header.php';
?>

<style>
.image-upload-box { position: relative; display: inline-block; cursor: pointer; overflow: hidden; border-radius: 6px; border: 2px dashed transparent; transition: 0.3s; background: #fff; }
.image-upload-box:hover { border-color: #0d6efd; }
.image-upload-overlay { position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.6); color: #fff; display: flex; flex-direction: column; align-items: center; justify-content: center; opacity: 0; transition: 0.2s; font-size: 10px; font-weight: bold; }
.image-upload-box:hover .image-upload-overlay { opacity: 1; }
.loader-spinner { display: none; width: 20px; height: 20px; border: 3px solid rgba(255,255,255,0.3); border-radius: 50%; border-top-color: #fff; animation: spin 1s infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
.cursor-pointer { cursor: pointer; }
</style>

<div class="row mb-4 align-items-center">
    <div class="col-md-6">
        <h2 class="fw-bold text-dark"><i class="bi bi-journal-text text-primary me-2"></i>Tekli Deneme Havuzu</h2>
        <span class="badge bg-secondary shadow-sm"><?= $toplam_urun ?> Kayıt Mevcut</span>
        <p class="text-muted small mt-2 mb-0">Paket Satışı butonu kapalı olanlar "Kendi Paketini Oluştur" sayfasında satın alınamaz (Eğer yayın tarihi geçmişse).</p>
    </div>
    <div class="col-md-6 text-md-end mt-3 mt-md-0 d-flex justify-content-md-end gap-2">
        <a href="excel_yukle.php" class="btn btn-outline-success shadow-sm fw-bold"><i class="bi bi-file-earmark-excel me-1"></i> Excel ile Yükle</a>
        <a href="ekle.php" class="btn btn-primary shadow-sm fw-bold"><i class="bi bi-plus-lg me-1"></i> Yeni Deneme Ekle</a>
    </div>
</div>

<div class="card shadow-sm border-0 mb-4 rounded-4">
    <div class="card-body bg-light rounded-4 p-4">
        <form action="index.php" method="GET" class="row g-3 align-items-end">
            <div class="col-md-4">
                <label class="form-label small fw-bold text-muted text-uppercase">Deneme Adı veya SKU</label>
                <input type="text" name="q" class="form-control border-0 shadow-sm" value="<?= htmlspecialchars($arama) ?>" placeholder="Arama yapın...">
            </div>
            <div class="col-md-3">
                <label class="form-label small fw-bold text-muted text-uppercase">Sınav Türü</label>
                <select name="tur" class="form-select border-0 shadow-sm">
                    <option value="">Tümü</option>
                    <?php foreach($turler as $t): ?>
                        <option value="<?= htmlspecialchars($t) ?>" <?= ($tur_filtre == $t) ? 'selected' : '' ?>><?= htmlspecialchars($t) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label small fw-bold text-muted text-uppercase">Yayın Evi</label>
                <select name="marka" class="form-select border-0 shadow-sm">
                    <option value="">Tümü</option>
                    <?php foreach($markalar as $m): ?>
                        <option value="<?= $m['id'] ?>" <?= ($marka_filtre === $m['id']) ? 'selected' : '' ?>><?= htmlspecialchars($m['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-primary w-100 fw-bold shadow"><i class="bi bi-filter me-1"></i> Filtrele</button>
            </div>
        </form>
    </div>
</div>

<div class="card shadow-sm border-0 mb-5 rounded-4 overflow-hidden">
    <div class="card-body p-0">
        <div class="table-responsive text-dark">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-dark">
                    <tr>
                        <th class="ps-3" width="50">ID</th>
                        <th width="80" class="text-center">Kapak</th>
                        <th>Deneme Bilgisi</th>
                        <th>Türü / Yayın</th>
                        <th>Yayın Tarihi</th>
                        <th class="text-center">Stok</th>
                        <th class="text-center" width="100" title="Genel Mağazada Görünürlük">Durum</th>
                        <th class="text-center" width="100" title="Paket Oluşturma Ekranında Geçmişse Satışa Aç">Paket Satışı</th>
                        <th width="100" class="text-end pe-4">İşlemler</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(count($urunler) > 0): ?>
                        <?php foreach($urunler as $urun): 
                            $gorsel = $urun['main_image'] ?: $urun['brand_logo'];
                            $is_brand_logo = empty($urun['main_image']) && !empty($urun['brand_logo']);
                        ?>
                        <tr id="row-<?= $urun['id'] ?>">
                            <td class="ps-3 text-muted fw-bold"><?= $urun['id'] ?></td>
                            <td class="text-center">
                                <div class="image-upload-box shadow-sm border" onclick="triggerImageUpload(<?= $urun['id'] ?>)" title="Kapağı Değiştir">
                                    <?php if($gorsel): ?>
                                        <img src="/magaza/<?= htmlspecialchars($gorsel) ?>" id="img-<?= $urun['id'] ?>" style="width: 50px; height: 65px; object-fit: <?= $is_brand_logo ? 'contain' : 'cover' ?>; padding: <?= $is_brand_logo ? '5px' : '0' ?>;">
                                    <?php else: ?>
                                        <div id="img-<?= $urun['id'] ?>" class="bg-light text-muted d-flex align-items-center justify-content-center" style="width: 50px; height: 65px; font-size: 9px;">YOK</div>
                                    <?php endif; ?>
                                    
                                    <div class="image-upload-overlay" id="overlay-<?= $urun['id'] ?>">
                                        <i class="bi bi-camera fs-5" id="icon-<?= $urun['id'] ?>"></i>
                                        <div class="loader-spinner" id="loader-<?= $urun['id'] ?>"></div>
                                        <span>Yükle</span>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <div class="fw-bold text-dark fs-6"><?= htmlspecialchars($urun['name']) ?></div>
                                <small class="text-muted">SKU: <span class="fw-semibold text-primary"><?= $urun['sku'] ?: '-' ?></span></small><br>
                                <strong class="text-success" style="font-size:0.8rem;"><?= number_format($urun['price'], 2, ',', '.') ?> ₺</strong>
                            </td>
                            <td>
                                <span class="badge bg-info text-dark shadow-sm"><?= $urun['exam_type'] ?: '-' ?></span><br>
                                <small class="text-secondary fw-bold text-uppercase"><?= $urun['brand_name'] ?: '-' ?></small>
                            </td>
                            <td>
                                <div class="text-dark small fw-bold"><?= htmlspecialchars($urun['exam_publication_date']) ?: '<span class="text-muted fw-normal">Belirtilmemiş</span>' ?></div>
                            </td>
                            <td class="text-center">
                                <span class="badge <?= $urun['stock_quantity'] > 10 ? 'bg-success' : 'bg-danger' ?> shadow-sm rounded-pill px-3"><?= $urun['stock_quantity'] ?></span>
                            </td>
                            <td class="text-center">
                                <div class="form-check form-switch d-flex justify-content-center" title="Sitede Listelenme">
                                    <input class="form-check-input cursor-pointer border-secondary" type="checkbox" role="switch" id="statusSwitch<?= $urun['id'] ?>" <?= $urun['status'] == 1 ? 'checked' : '' ?> onchange="toggleStatus(<?= $urun['id'] ?>, this)">
                                </div>
                            </td>
                            <td class="text-center border-start">
                                <div class="form-check form-switch d-flex justify-content-center" title="Geçmiş olsa bile Özel Pakette satılabilir">
                                    <input class="form-check-input cursor-pointer border-primary" type="checkbox" role="switch" id="pkgSwitch<?= $urun['id'] ?>" <?= $urun['allow_custom_package'] == 1 ? 'checked' : '' ?> onchange="togglePackageStatus(<?= $urun['id'] ?>, this)">
                                </div>
                            </td>
                            <td class="text-end pe-4 border-start">
                                <div class="btn-group shadow-sm">
                                    <a href="duzenle.php?id=<?= $urun['id'] ?>" class="btn btn-sm btn-light border" title="Düzenle"><i class="bi bi-pencil-fill text-warning"></i></a>
                                    <a href="sil.php?id=<?= $urun['id'] ?>" class="btn btn-sm btn-light border" onclick="return confirm('Bu denemeyi silmek istediğinize emin misiniz?');" title="Sil"><i class="bi bi-trash-fill text-danger"></i></a>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="9" class="text-center py-5 text-muted fw-bold"><i class="bi bi-search fs-1 d-block mb-3 opacity-50"></i>Aranan kriterlere uygun deneme bulunamadı.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php if($toplam_sayfa > 1): ?>
<nav aria-label="Page navigation" class="mb-5">
    <ul class="pagination justify-content-center">
        <?php for($i = 1; $i <= $toplam_sayfa; $i++): ?>
            <li class="page-item <?= ($sayfa == $i) ? 'active' : '' ?>">
                <a class="page-link shadow-sm fw-bold <?= ($sayfa == $i) ? 'border-primary' : 'border-0 text-dark' ?>" href="?s=<?= $i ?>&q=<?= urlencode($arama) ?>&tur=<?= urlencode($tur_filtre) ?>&marka=<?= $marka_filtre ?>"><?= $i ?></a>
            </li>
        <?php endfor; ?>
    </ul>
</nav>
<?php endif; ?>

<input type="file" id="ajaxFileInput" accept="image/*" style="display: none;">

<script>
// GENEL DURUM GÜNCELLEME
function toggleStatus(productId, checkbox) {
    const newStatus = checkbox.checked ? 1 : 0;
    const formData = new FormData();
    formData.append('ajax_status_toggle', '1');
    formData.append('product_id', productId);
    formData.append('new_status', newStatus);

    fetch('index.php', { method: 'POST', body: formData })
    .then(response => response.json())
    .then(data => {
        if (!data.success) { alert('Hata: ' + data.message); checkbox.checked = !checkbox.checked; }
    })
    .catch(error => { console.error('Error:', error); checkbox.checked = !checkbox.checked; });
}

// PAKET SATIŞ İZNİ GÜNCELLEME
function togglePackageStatus(productId, checkbox) {
    const newStatus = checkbox.checked ? 1 : 0;
    const formData = new FormData();
    formData.append('ajax_package_toggle', '1');
    formData.append('product_id', productId);
    formData.append('new_status', newStatus);

    fetch('index.php', { method: 'POST', body: formData })
    .then(response => response.json())
    .then(data => {
        if (!data.success) { alert('Hata: ' + data.message); checkbox.checked = !checkbox.checked; }
    })
    .catch(error => { console.error('Error:', error); checkbox.checked = !checkbox.checked; });
}

// GÖRSEL YÜKLEME 
let currentProductId = null;
const fileInput = document.getElementById('ajaxFileInput');

function triggerImageUpload(productId) {
    currentProductId = productId;
    fileInput.click();
}

fileInput.addEventListener('change', function() {
    if (!this.files.length) return;
    const file = this.files[0];
    const formData = new FormData();
    formData.append('ajax_image_upload', '1');
    formData.append('product_id', currentProductId);
    formData.append('ajax_file', file);

    const icon = document.getElementById('icon-' + currentProductId);
    const loader = document.getElementById('loader-' + currentProductId);
    icon.style.display = 'none'; loader.style.display = 'block';

    fetch('index.php', { method: 'POST', body: formData })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            let imgElement = document.getElementById('img-' + currentProductId);
            if (imgElement.tagName.toLowerCase() !== 'img') {
                const newImg = document.createElement('img');
                newImg.id = 'img-' + currentProductId;
                imgElement.parentNode.replaceChild(newImg, imgElement);
                imgElement = newImg;
            }
            imgElement.style = 'width: 50px; height: 65px; object-fit: cover; padding: 0;';
            imgElement.src = data.new_image_url + '?t=' + new Date().getTime();
        } else { alert('Hata: ' + data.message); }
    })
    .finally(() => { icon.style.display = 'block'; loader.style.display = 'none'; fileInput.value = ''; });
});
</script>

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