<?php
/**
 * Admin Ürün Listesi (AJAX Vitrin/Durum, Sütun Sıralama, Joker Kapak)
 * Konum: /magaza/admin/urunler/index.php
 */

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

adminCheck(); 

// ============================================================================
// 1. AJAX: HIZLI DURUM VE VİTRİN GÜNCELLEME MOTORU
// ============================================================================
if (isset($_POST['ajax_toggle'])) {
    header('Content-Type: application/json');
    $product_id = (int)$_POST['product_id'];
    $new_value = (int)$_POST['new_value'];
    $field = $_POST['field'] === 'is_featured' ? 'is_featured' : 'status'; // Sadece izin verilen 2 sütun
    
    $stmt = $db->prepare("UPDATE products SET $field = ? WHERE id = ?");
    if ($stmt->execute([$new_value, $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 VE KLASÖRLEME
// ============================================================================
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 = 'urun-' . $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 = [];
$params = [];

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

$kat_filtre = isset($_GET['kat']) ? (int)$_GET['kat'] : '';
if ($kat_filtre !== '') {
    // Hem ana kategori hem de çoklu kategoriler tablosunda ara
    $where_clauses[] = "(p.category_id = ? OR p.id IN (SELECT product_id FROM product_categories WHERE category_id = ?))";
    $params[] = $kat_filtre;
    $params[] = $kat_filtre;
}

$tip_filtre = isset($_GET['tip']) ? $_GET['tip'] : '';
if ($tip_filtre !== '') {
    $where_clauses[] = "p.type = ?";
    $params[] = $tip_filtre;
}

$vitrin_filtre = isset($_GET['vitrin']) ? $_GET['vitrin'] : '';
if ($vitrin_filtre !== '') {
    $where_clauses[] = "p.is_featured = ?";
    $params[] = (int)$vitrin_filtre;
}

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

// --- SÜTUN SIRALAMA (ORDER BY) ---
$order_col = isset($_GET['ob']) ? $_GET['ob'] : 'id';
$order_dir = (isset($_GET['od']) && strtolower($_GET['od']) === 'asc') ? 'ASC' : 'DESC';

$allowed_cols = ['id', 'name', 'price', 'stock_quantity', 'status', 'is_featured'];
if (!in_array($order_col, $allowed_cols)) {
    $order_col = 'id';
}

$order_sql = "ORDER BY p.{$order_col} {$order_dir}";

// --- SAYFALAMA (PAGINATION) AYARLARI ---
$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(DISTINCT p.id) FROM products p $where_sql");
$toplam_sorgu->execute($params);
$toplam_urun = $toplam_sorgu->fetchColumn();
$toplam_sayfa = ceil($toplam_urun / $limit);

// --- ÜRÜNLERİ ÇEKME (Joker Kapak Zekası, Vitrin Durumu) ---
$sql = "
    SELECT DISTINCT
        p.id, p.name, p.type, p.price, p.vat_rate, p.vat_included, p.stock_quantity, p.status, p.is_featured, p.publish_date, p.sku, p.total_deliveries,
        c.name as category_name,
        b.name as brand_name, b.default_cover 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 categories c ON p.category_id = c.id
    LEFT JOIN brands b ON p.brand_id = b.id
    $where_sql
    $order_sql
    LIMIT $limit OFFSET $offset
";

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

$kategoriler = $db->query("SELECT id, name FROM categories ORDER BY name ASC")->fetchAll();

// Sıralama Linki Oluşturucu Fonksiyon
function sortLink($col, $current_col, $current_dir) {
    $params = $_GET;
    $params['ob'] = $col;
    if ($current_col === $col && $current_dir === 'DESC') {
        $params['od'] = 'asc';
        $icon = '<i class="bi bi-sort-down-alt"></i>';
    } elseif ($current_col === $col && $current_dir === 'ASC') {
        $params['od'] = 'desc';
        $icon = '<i class="bi bi-sort-up"></i>';
    } else {
        $params['od'] = 'desc'; // Varsayılan yeni tıklamada büyükten küçüğe
        $icon = '<i class="bi bi-arrow-down-up text-muted" style="font-size:0.7rem; opacity:0.5;"></i>';
    }
    // Sadece sütun aktifse iconu belirgin yap
    if ($current_col !== $col) $icon = '<i class="bi bi-arrow-down-up text-muted" style="font-size:0.7rem; opacity:0.5;"></i>';
    
    return '<a href="?' . http_build_query($params) . '" class="text-white text-decoration-none d-flex align-items-center justify-content-between">' . 
           '<span>' . getColumnTitle($col) . '</span> ' . $icon . '</a>';
}

function getColumnTitle($col) {
    $titles = [
        'id' => 'ID', 'name' => 'Ürün Bilgisi', 'price' => 'Fiyat', 
        'stock_quantity' => 'Stok', 'status' => 'Durum', 'is_featured' => 'Vitrin'
    ];
    return isset($titles[$col]) ? $titles[$col] : $col;
}

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

<style>
/* Hızlı Resim Yükleme Efektleri */
.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; text-align: center; }
.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; margin-bottom: 2px;}
@keyframes spin { to { transform: rotate(360deg); } }
.cursor-pointer { cursor: pointer; }
.table-dark th a:hover { color: #0dcaf0 !important; }
</style>

<div class="row mb-4 align-items-center">
    <div class="col-md-6">
        <h2 class="fw-bold text-dark"><i class="bi bi-box-seam text-primary me-2"></i>Ürün ve Paket Listesi</h2>
        <span class="badge bg-secondary shadow-sm"><?= $toplam_urun ?> Kayıt Mevcut</span>
        <p class="text-muted small mt-2 mb-0">Görselleri üzerine tıklayarak değiştirebilirsiniz. "Vitrin" butonu ürünü ana sayfaya alır.</p>
    </div>
    <div class="col-md-6 text-md-end mt-3 mt-md-0">
        <a href="ekle.php" class="btn btn-success shadow-sm fw-bold"><i class="bi bi-plus-lg me-1"></i> Yeni Ürün/Paket Ekle</a>
    </div>
</div>

<?php if(isset($_GET['islem'])): ?>
    <div class="row mb-3">
        <div class="col-12 text-dark">
            <?php if($_GET['islem'] == 'pasif_yapildi'): ?>
                <div class="alert alert-warning shadow-sm alert-dismissible fade show border-start border-4 border-warning mb-0">
                    <i class="bi bi-exclamation-triangle-fill text-warning fs-5 me-2" style="vertical-align: middle;"></i> 
                    Bu ürün geçmiş siparişlerde kullanıldığı için tamamen silinemez, fatura ve raporların bozulmaması için <b>Pasif (Gizli)</b> duruma alındı.
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php elseif($_GET['islem'] == 'tamamen_silindi'): ?>
                <div class="alert alert-success shadow-sm alert-dismissible fade show border-start border-4 border-success mb-0">
                    <i class="bi bi-check-circle-fill text-success fs-5 me-2" style="vertical-align: middle;"></i> 
                    Ürün daha önce hiç satılmadığı için; veritabanından, resim galerisinden ve sunucudaki klasörlerden <b>tamamen ve kalıcı olarak silindi</b>.
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
        </div>
    </div>
<?php endif; ?>

<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">
            <input type="hidden" name="ob" value="<?= $order_col ?>">
            <input type="hidden" name="od" value="<?= strtolower($order_dir) ?>">
            
            <div class="col-md-3">
                <label class="form-label small fw-bold text-muted text-uppercase">Arama (Ad / SKU)</label>
                <input type="text" name="q" class="form-control border-0 shadow-sm" value="<?= htmlspecialchars($arama) ?>" placeholder="Kelime veya Kodu...">
            </div>
            <div class="col-md-2">
                <label class="form-label small fw-bold text-muted text-uppercase">Kategori</label>
                <select name="kat" class="form-select border-0 shadow-sm">
                    <option value="">Tümü</option>
                    <?php foreach($kategoriler as $k): ?>
                        <option value="<?= $k['id'] ?>" <?= ($kat_filtre == $k['id']) ? 'selected' : '' ?>><?= htmlspecialchars($k['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label small fw-bold text-muted text-uppercase">Ürün Tipi</label>
                <select name="tip" class="form-select border-0 shadow-sm">
                    <option value="">Tümü</option>
                    <option value="exam_package" <?= ($tip_filtre === 'exam_package') ? 'selected' : '' ?>>Deneme Paketi</option>
                    <option value="subscription" <?= ($tip_filtre === 'subscription') ? 'selected' : '' ?>>Abonelik</option>
                    <option value="physical" <?= ($tip_filtre === 'physical') ? 'selected' : '' ?>>Fiziksel Ürün</option>
                    <option value="digital" <?= ($tip_filtre === 'digital') ? 'selected' : '' ?>>Dijital Ürün</option>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label small fw-bold text-muted text-uppercase">Vitrin</label>
                <select name="vitrin" class="form-select border-0 shadow-sm">
                    <option value="">Tümü</option>
                    <option value="1" <?= ($vitrin_filtre === '1') ? 'selected' : '' ?>>Öne Çıkanlar</option>
                    <option value="0" <?= ($vitrin_filtre === '0') ? 'selected' : '' ?>>Vitrin Dışı</option>
                </select>
            </div>
            <div class="col-md-3 d-flex gap-2">
                <button type="submit" class="btn btn-primary flex-grow-1 fw-bold shadow"><i class="bi bi-filter me-1"></i> Filtrele</button>
                <a href="index.php" class="btn btn-light border fw-bold shadow-sm" title="Filtreleri Temizle"><i class="bi bi-x-lg"></i></a>
            </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="70"><?= sortLink('id', $order_col, $order_dir) ?></th>
                        <th width="80" class="text-center">Görsel</th>
                        <th><?= sortLink('name', $order_col, $order_dir) ?></th>
                        <th>Kategori / Marka</th>
                        <th width="120"><?= sortLink('price', $order_col, $order_dir) ?></th>
                        <th width="100" class="text-center"><?= sortLink('stock_quantity', $order_col, $order_dir) ?></th>
                        <th width="120" class="text-center"><?= sortLink('is_featured', $order_col, $order_dir) ?></th>
                        <th width="100" class="text-center"><?= sortLink('status', $order_col, $order_dir) ?></th>
                        <th width="120" 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="Görseli 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 if($is_brand_logo): ?>
                                            <span id="badge-<?= $urun['id'] ?>" class="position-absolute bottom-0 start-0 w-100 bg-dark text-white text-center" style="font-size: 7px; opacity: 0.85; padding: 2px 0;">MARKA</span>
                                        <?php endif; ?>
                                    <?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'] ? htmlspecialchars($urun['sku']) : '-' ?></span> | 
                                    Tip: <span class="text-primary fw-bold"><?= ucfirst(str_replace('_', ' ', $urun['type'])) ?></span>
                                </small>
                                <?php if($urun['type'] == 'subscription' || $urun['type'] == 'exam_package'): ?>
                                    <div class="mt-1"><span class="badge bg-warning text-dark" style="font-size: 0.65rem;"><i class="bi bi-truck me-1"></i> <?= $urun['total_deliveries'] ?> Aylık Gönderim</span></div>
                                <?php endif; ?>
                            </td>
                            <td>
                                <span class="badge bg-info text-dark shadow-sm"><?= $urun['category_name'] ? htmlspecialchars($urun['category_name']) : 'Genel' ?></span><br>
                                <small class="text-secondary fw-bold text-uppercase"><?= $urun['brand_name'] ? htmlspecialchars($urun['brand_name']) : '' ?></small>
                            </td>
                            <td>
                                <strong class="text-success fs-6"><?= number_format($urun['price'], 2, ',', '.') ?> ₺</strong>
                                <div class="mt-1">
                                    <span class="badge bg-light text-secondary border shadow-sm" style="font-size: 0.65rem;">
                                        %<?= $urun['vat_rate'] ?> KDV <?= $urun['vat_included'] == 1 ? 'Dahil' : 'Hariç' ?>
                                    </span>
                                </div>
                            </td>
                            <td class="text-center">
                                <?php if($urun['type'] == 'digital'): ?>
                                    <span class="badge bg-secondary opacity-75 shadow-sm">Sınırsız</span>
                                <?php else: ?>
                                    <span class="badge <?= $urun['stock_quantity'] > 10 ? 'bg-success' : 'bg-danger' ?> shadow-sm rounded-pill px-3"><?= $urun['stock_quantity'] ?></span>
                                <?php endif; ?>
                            </td>
                            <td class="text-center bg-light">
                                <div class="form-check form-switch d-flex justify-content-center" title="Ana Sayfada Öne Çıkanlar'da Göster">
                                    <input class="form-check-input cursor-pointer border-secondary" type="checkbox" role="switch" <?= $urun['is_featured'] == 1 ? 'checked' : '' ?> onchange="toggleSwitch(<?= $urun['id'] ?>, this, 'is_featured')">
                                </div>
                            </td>
                            <td class="text-center">
                                <div class="form-check form-switch d-flex justify-content-center" title="Sitede Aktif/Pasif Yap">
                                    <input class="form-check-input cursor-pointer border-secondary" type="checkbox" role="switch" <?= $urun['status'] == 1 ? 'checked' : '' ?> onchange="toggleSwitch(<?= $urun['id'] ?>, this, 'status')">
                                </div>
                            </td>
                            <td class="text-end pe-4">
                                <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 ürünü silmek istediğinize emin misiniz? (Satış geçmişi varsa sadece pasife alınır)');" 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 ürün 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 
        $query_params = $_GET; 
        for($i = 1; $i <= $toplam_sayfa; $i++): 
            $query_params['s'] = $i;
            $link = '?' . http_build_query($query_params);
        ?>
            <li class="page-item <?= ($sayfa == $i) ? 'active' : '' ?>">
                <a class="page-link shadow-sm fw-bold <?= ($sayfa == $i) ? 'border-primary bg-primary text-white' : 'text-dark border-1' ?>" href="<?= $link ?>">
                    <?= $i ?>
                </a>
            </li>
        <?php endfor; ?>
    </ul>
</nav>
<?php endif; ?>

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

<script>
// --- AJAX DURUM / VİTRİN GÜNCELLEME (ORTAK SWITCH) ---
function toggleSwitch(productId, checkbox, field) {
    const newValue = checkbox.checked ? 1 : 0;
    const formData = new FormData();
    formData.append('ajax_toggle', '1');
    formData.append('product_id', productId);
    formData.append('new_value', newValue);
    formData.append('field', field); // status veya is_featured

    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;
    });
}

// --- AJAX 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;';
            const badge = document.getElementById('badge-' + currentProductId);
            if(badge) badge.remove();

            imgElement.src = data.new_image_url + '?t=' + new Date().getTime();
        } else {
            alert('Hata: ' + data.message);
        }
    })
    .catch(error => { console.error('Upload Error:', error); })
    .finally(() => {
        icon.style.display = 'block';
        loader.style.display = 'none';
        fileInput.value = ''; 
    });
});
</script>

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