<?php
/**
 * Admin Marka / Yayınevi Yönetimi (Logo ve Varsayılan Kapak Zekası)
 * Konum: /magaza/admin/urunler/markalar.php
 */

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

adminCheck();

// Proje ana dizinini belirle
$kok_dizin = "/magaza/";

// ============================================================================
// 1. AJAX İLE HIZLI GÖRSEL YÜKLEME (LOGO VEYA KAPAK)
// ============================================================================
if (isset($_POST['ajax_upload']) && isset($_FILES['ajax_file']) && isset($_POST['brand_id']) && isset($_POST['upload_type'])) {
    header('Content-Type: application/json');
    $brand_id = (int)$_POST['brand_id'];
    $upload_type = $_POST['upload_type']; // 'logo' veya 'cover'
    
    $izin_verilen_uzantilar = ['jpg', 'jpeg', 'png', 'webp'];
    $dosya_uzantisi = strtolower(pathinfo($_FILES['ajax_file']['name'], PATHINFO_EXTENSION));
    
    if (!in_array($dosya_uzantisi, $izin_verilen_uzantilar)) {
        echo json_encode(['success' => false, 'message' => 'Sadece JPG, PNG veya WEBP.']);
        exit;
    }

    $brand = $db->prepare("SELECT slug, logo, default_cover FROM brands WHERE id = ?");
    $brand->execute([$brand_id]);
    $b = $brand->fetch();

    $tur_eki = ($upload_type == 'cover') ? '-cover-' : '-logo-';
    $yeni_dosya_adi = $b['slug'] . $tur_eki . time() . '.' . $dosya_uzantisi;
    $hedef_yol = '../../uploads/brands/' . $yeni_dosya_adi;

    if (!is_dir('../../uploads/brands/')) { mkdir('../../uploads/brands/', 0777, true); }

    if (move_uploaded_file($_FILES['ajax_file']['tmp_name'], $hedef_yol)) {
        $db_yolu = 'uploads/brands/' . $yeni_dosya_adi;
        
        if ($upload_type == 'logo') {
            if (!empty($b['logo']) && file_exists('../../' . $b['logo'])) unlink('../../' . $b['logo']);
            $db->prepare("UPDATE brands SET logo = ? WHERE id = ?")->execute([$db_yolu, $brand_id]);
        } else {
            if (!empty($b['default_cover']) && file_exists('../../' . $b['default_cover'])) unlink('../../' . $b['default_cover']);
            $db->prepare("UPDATE brands SET default_cover = ? WHERE id = ?")->execute([$db_yolu, $brand_id]);
        }
        
        // YENİ: $kok_dizin ile birleştirilerek döndürülüyor
        echo json_encode(['success' => true, 'new_url' => rtrim($kok_dizin, '/') . '/' . $db_yolu]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Sunucu hatası.']);
    }
    exit;
}

// ============================================================================
// 2. YENİ MARKA EKLEME FORMU
// ============================================================================
$mesaj = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['marka_ekle'])) {
    $name = trim($_POST['name']);
    $slug = seoLink($name); 
    $logo_path = NULL;
    $cover_path = NULL;

    if (empty($name)) {
        $mesaj = "<div class='alert alert-warning shadow-sm'><i class='bi bi-exclamation-triangle me-2'></i>Marka adı zorunludur.</div>";
    } else {
        // YENİ: Marka slug çakışma kontrolünde daha şık bir ek eklenmesi
        $check = $db->prepare("SELECT id FROM brands WHERE slug = ?");
        $check->execute([$slug]);
        if ($check->rowCount() > 0) { 
            $slug = $slug . '-' . substr(md5(uniqid()), 0, 4); 
        }

        // Logo Yükleme
        if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
            $ext = strtolower(pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION));
            $logo_name = $slug . '-logo-' . time() . '.' . $ext;
            if (move_uploaded_file($_FILES['logo']['tmp_name'], '../../uploads/brands/' . $logo_name)) {
                $logo_path = 'uploads/brands/' . $logo_name;
            }
        }
        
        // Varsayılan Kapak Yükleme
        if (isset($_FILES['cover']) && $_FILES['cover']['error'] === UPLOAD_ERR_OK) {
            $ext = strtolower(pathinfo($_FILES['cover']['name'], PATHINFO_EXTENSION));
            $cover_name = $slug . '-cover-' . time() . '.' . $ext;
            if (move_uploaded_file($_FILES['cover']['tmp_name'], '../../uploads/brands/' . $cover_name)) {
                $cover_path = 'uploads/brands/' . $cover_name;
            }
        }

        if (empty($mesaj)) {
            $stmt = $db->prepare("INSERT INTO brands (name, slug, logo, default_cover, status) VALUES (?, ?, ?, ?, 1)");
            if ($stmt->execute([$name, $slug, $logo_path, $cover_path])) {
                $mesaj = "<div class='alert alert-success shadow-sm'><i class='bi bi-check-circle me-2'></i>Marka başarıyla eklendi!</div>";
            }
        }
    }
}

// LİSTEYİ ÇEK
$markalar = $db->query("SELECT * FROM brands ORDER BY id DESC")->fetchAll();

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

<style>
.upload-box { position: relative; display: inline-block; cursor: pointer; overflow: hidden; border-radius: 6px; border: 2px dashed #dee2e6; background: #fff; transition: 0.3s; }
.upload-box:hover { border-color: #0d6efd; }
.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: 9px; font-weight: bold; text-align: center;}
.upload-box:hover .upload-overlay { opacity: 1; }
.loader { display: none; width: 16px; height: 16px; border: 2px solid rgba(255,255,255,0.3); border-radius: 50%; border-top-color: #fff; animation: spin 1s infinite; margin-bottom: 3px;}
@keyframes spin { to { transform: rotate(360deg); } }
</style>

<div class="row mb-4 align-items-center">
    <div class="col-12">
        <h2 class="fw-bold text-dark"><i class="bi bi-bookmark-star-fill text-warning me-2"></i>Marka & Yayınevi Yönetimi</h2>
        <p class="text-muted small mb-0">Ürünlerde özel resim olmadığında sistem <b>Varsayılan Kapak (600x800)</b> görselini kullanır. Görselleri değiştirmek için kutulara tıklayın.</p>
        <?= $mesaj; ?>
    </div>
</div>

<div class="row">
    <div class="col-md-4 mb-4">
        <div class="card shadow-sm border-0 rounded-4 position-sticky" style="top: 80px;">
            <div class="card-header bg-dark text-white py-3 border-0">
                <h5 class="card-title mb-0 fw-bold small text-uppercase"><i class="bi bi-plus-circle me-2"></i>Yeni Marka Ekle</h5>
            </div>
            <div class="card-body p-4 text-dark">
                <form action="markalar.php" method="POST" enctype="multipart/form-data">
                    <div class="mb-3">
                        <label class="form-label fw-bold text-muted small text-uppercase">Yayınevi Adı *</label>
                        <input type="text" name="name" class="form-control border-2 shadow-none" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold text-muted small text-uppercase">Marka Logosu (150x150)</label>
                        <input type="file" name="logo" class="form-control border-2 shadow-none" accept="image/*">
                        <div class="form-text mt-1" style="font-size: 11px;">Filtrelerde ve menülerde kullanılır.</div>
                    </div>
                    <div class="mb-4">
                        <label class="form-label fw-bold text-muted small text-uppercase">Joker Kapak (600x800)</label>
                        <input type="file" name="cover" class="form-control border-2 shadow-none border-primary" accept="image/*">
                        <div class="form-text mt-1 text-primary" style="font-size: 11px;">Resmi olmayan ürünlerde vitrinde bu görünür.</div>
                    </div>
                    <button type="submit" name="marka_ekle" class="btn btn-primary w-100 fw-bold py-2 shadow text-uppercase">
                        Markayı Kaydet
                    </button>
                </form>
            </div>
        </div>
    </div>

    <div class="col-md-8">
        <div class="card shadow-sm border-0 rounded-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-collection me-2"></i>Kayıtlı Yayınevleri</h5>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light text-uppercase small text-muted">
                            <tr>
                                <th class="ps-4 text-center">Yatay Logo<br><span style="font-size:9px">(150x150)</span></th>
                                <th class="text-center">Joker Kapak<br><span style="font-size:9px; color:#0d6efd;">(600x800)</span></th>
                                <th>Yayınevi Bilgisi</th>
                                <th class="text-center">Durum</th>
                                <th class="text-end pe-4">İşlemler</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(count($markalar) > 0): ?>
                                <?php foreach($markalar as $row): ?>
                                <tr>
                                    <td class="ps-4 text-center">
                                        <div class="upload-box shadow-sm" onclick="triggerUpload(<?= $row['id'] ?>, 'logo')" title="Logo Değiştir">
                                            <?php if($row['logo']): ?>
                                                <img src="<?= $kok_dizin ?><?= htmlspecialchars($row['logo']); ?>" id="img-logo-<?= $row['id'] ?>" style="height: 40px; width: 70px; object-fit: contain; padding: 2px;">
                                            <?php else: ?>
                                                <div id="img-logo-<?= $row['id'] ?>" class="text-muted d-flex align-items-center justify-content-center" style="height: 40px; width: 70px; font-size: 9px;">LOGO YOK</div>
                                            <?php endif; ?>
                                            <div class="upload-overlay" id="overlay-logo-<?= $row['id'] ?>">
                                                <div class="loader" id="loader-logo-<?= $row['id'] ?>"></div>
                                                <span id="text-logo-<?= $row['id'] ?>">Yükle</span>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="text-center">
                                        <div class="upload-box shadow-sm border-primary border-opacity-50" onclick="triggerUpload(<?= $row['id'] ?>, 'cover')" title="Joker Kapak Değiştir">
                                            <?php if($row['default_cover']): ?>
                                                <img src="<?= $kok_dizin ?><?= htmlspecialchars($row['default_cover']); ?>" id="img-cover-<?= $row['id'] ?>" style="height: 55px; width: 40px; object-fit: cover;">
                                            <?php else: ?>
                                                <div id="img-cover-<?= $row['id'] ?>" class="text-primary d-flex align-items-center justify-content-center" style="height: 55px; width: 40px; font-size: 8px; text-align:center; line-height:1;">KAPAK<br>YOK</div>
                                            <?php endif; ?>
                                            <div class="upload-overlay" id="overlay-cover-<?= $row['id'] ?>">
                                                <div class="loader" id="loader-cover-<?= $row['id'] ?>"></div>
                                                <span id="text-cover-<?= $row['id'] ?>">Kapak</span>
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="fw-bold text-dark fs-6"><?= htmlspecialchars($row['name']); ?></div>
                                        <small class="text-muted font-monospace">/<?= $row['slug']; ?></small>
                                    </td>
                                    <td class="text-center">
                                        <span class="badge <?= $row['status'] == 1 ? 'bg-success' : 'bg-danger' ?> rounded-pill px-3">
                                            <?= $row['status'] == 1 ? 'Aktif' : 'Pasif' ?>
                                        </span>
                                    </td>
                                    <td class="text-end pe-4">
                                        <div class="btn-group shadow-sm">
                                            <a href="marka_duzenle.php?id=<?= $row['id']; ?>" class="btn btn-sm btn-light border" title="Düzenle"><i class="bi bi-pencil-fill text-warning"></i></a>
                                            <a href="marka_sil.php?id=<?= $row['id']; ?>" class="btn btn-sm btn-light border" onclick="return confirm('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="5" class="text-center py-5 text-muted fw-bold">Henüz marka eklenmemiş.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

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

<script>
let currentBrandId = null;
let currentUploadType = null; // 'logo' veya 'cover'
const fileInput = document.getElementById('ajaxFileInput');

function triggerUpload(brandId, type) {
    currentBrandId = brandId;
    currentUploadType = type;
    fileInput.click();
}

fileInput.addEventListener('change', function() {
    if (!this.files.length) return;
    
    const file = this.files[0];
    const formData = new FormData();
    formData.append('ajax_upload', '1');
    formData.append('brand_id', currentBrandId);
    formData.append('upload_type', currentUploadType);
    formData.append('ajax_file', file);

    const textEl = document.getElementById('text-' + currentUploadType + '-' + currentBrandId);
    const loader = document.getElementById('loader-' + currentUploadType + '-' + currentBrandId);
    textEl.style.display = 'none';
    loader.style.display = 'block';

    fetch('markalar.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            let imgElement = document.getElementById('img-' + currentUploadType + '-' + currentBrandId);
            
            if (imgElement.tagName.toLowerCase() !== 'img') {
                const newImg = document.createElement('img');
                newImg.id = 'img-' + currentUploadType + '-' + currentBrandId;
                if(currentUploadType === 'logo') {
                    newImg.style = 'height: 40px; width: 70px; object-fit: contain; padding: 2px;';
                } else {
                    newImg.style = 'height: 55px; width: 40px; object-fit: cover;';
                }
                imgElement.parentNode.replaceChild(newImg, imgElement);
                imgElement = newImg;
            }
            imgElement.src = data.new_url + '?t=' + new Date().getTime();
        } else {
            alert('Hata: ' + data.message);
        }
    })
    .catch(error => { console.error('Upload Error:', error); })
    .finally(() => {
        textEl.style.display = 'block';
        loader.style.display = 'none';
        fileInput.value = ''; 
    });
});
</script>

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