<?php
/**
 * Gallery Management
 * Aegean Dominance Admin Panel
 */

session_start();
require_once __DIR__ . '/../config/config.php';

$auth = new Auth();
$auth->requireLogin();

$db = Database::getInstance();

// AJAX İşlemleri
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    header('Content-Type: application/json');
    $input = json_decode(file_get_contents('php://input'), true);
    $action = $input['action'] ?? '';
    
    try {
        switch ($action) {
            case 'update_alt':
                $id = (int)($input['id'] ?? 0);
                $alt = trim($input['alt_text'] ?? '');
                $db->execute("UPDATE service_images SET alt_text = ? WHERE id = ?", [$alt, $id]);
                echo json_encode(['success' => true, 'message' => 'Alt text güncellendi.']);
                break;
                
            case 'delete':
                $id = (int)($input['id'] ?? 0);
                $db->execute("DELETE FROM service_images WHERE id = ?", [$id]);
                echo json_encode(['success' => true, 'message' => 'Görsel silindi.']);
                break;
                
            case 'set_featured':
                $id = (int)($input['id'] ?? 0);
                $serviceId = (int)($input['service_id'] ?? 0);
                $db->execute("UPDATE service_images SET is_featured = 0 WHERE service_id = ?", [$serviceId]);
                $db->execute("UPDATE service_images SET is_featured = 1 WHERE id = ?", [$id]);
                echo json_encode(['success' => true, 'message' => 'Öne çıkan görsel güncellendi.']);
                break;
                
            default:
                echo json_encode(['success' => false, 'error' => 'Geçersiz işlem.']);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

// Filtre
$serviceId = (int)($_GET['service'] ?? 0);
$where = $serviceId ? "WHERE si.service_id = ?" : "";
$params = $serviceId ? [$serviceId] : [];

$images = $db->fetchAll(
    "SELECT si.*, s.name as service_name 
     FROM service_images si 
     LEFT JOIN services s ON si.service_id = s.id 
     {$where} 
     ORDER BY si.service_id, si.display_order",
    $params
);

$services = $db->fetchAll("SELECT id, name FROM services ORDER BY name");
$totalImages = $db->fetchColumn("SELECT COUNT(*) FROM service_images");

include 'partials/header.php';
?>

<div class="p-6">
    <div class="flex flex-wrap items-center justify-between gap-4 mb-6">
        <div>
            <h2 class="text-xl font-semibold text-white">Galeri Yönetimi</h2>
            <p class="text-white/60 text-sm"><?= $totalImages ?> görsel</p>
        </div>
        
        <div class="flex gap-3">
            <select id="service_filter" onchange="filterByService(this.value)" class="bg-dark-800 border border-white/10 rounded-lg px-4 py-2 text-white">
                <option value="">Tüm Hizmetler</option>
                <?php foreach ($services as $s): ?>
                <option value="<?= $s['id'] ?>" <?= $serviceId == $s['id'] ? 'selected' : '' ?>><?= htmlspecialchars($s['name']) ?></option>
                <?php endforeach; ?>
            </select>
        </div>
    </div>
    
    <!-- Bulk Alt Text Update -->
    <div class="glass-card rounded-2xl p-6 mb-6">
        <h3 class="text-lg font-semibold text-white mb-4">Toplu Alt-Tag Düzenleme</h3>
        <p class="text-white/60 text-sm mb-4">Seçili hizmetteki tüm görsellere otomatik alt-tag atayın.</p>
        <div class="flex gap-3">
            <input type="text" id="bulk_alt" class="flex-1 bg-dark-800 border border-white/10 rounded-lg px-4 py-2 text-white" placeholder="Örn: İzmir Bioklimatik Pergola">
            <button onclick="bulkUpdateAlt()" class="gold-gradient text-dark-900 font-semibold py-2 px-6 rounded-lg hover:opacity-90">Uygula</button>
        </div>
    </div>
    
    <!-- Gallery Grid -->
    <div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
        <?php foreach ($images as $img): ?>
        <div class="glass-card rounded-xl overflow-hidden group" data-id="<?= $img['id'] ?>" data-service="<?= $img['service_id'] ?>">
            <div class="relative aspect-square">
                <img 
                    src="<?= BASE_URL ?>/<?= htmlspecialchars($img['image_path']) ?>" 
                    alt="<?= htmlspecialchars($img['alt_text']) ?>"
                    class="w-full h-full object-cover"
                    loading="lazy"
                >
                
                <?php if ($img['is_featured']): ?>
                <span class="absolute top-2 left-2 bg-gold text-dark-900 text-xs font-bold px-2 py-0.5 rounded">Öne Çıkan</span>
                <?php endif; ?>
                
                <div class="absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-2">
                    <button onclick="setFeatured(<?= $img['id'] ?>, <?= $img['service_id'] ?>)" class="p-2 rounded-lg bg-gold text-dark-900">
                        <i data-lucide="star" class="w-4 h-4"></i>
                    </button>
                    <button onclick="deleteImage(<?= $img['id'] ?>)" class="p-2 rounded-lg bg-red-500 text-white">
                        <i data-lucide="trash-2" class="w-4 h-4"></i>
                    </button>
                </div>
            </div>
            
            <div class="p-2">
                <input 
                    type="text" 
                    value="<?= htmlspecialchars($img['alt_text']) ?>"
                    onblur="updateAlt(<?= $img['id'] ?>, this.value)"
                    class="w-full bg-transparent border-b border-white/10 text-white/70 text-xs py-1 focus:border-gold focus:outline-none"
                    placeholder="Alt text..."
                >
                <p class="text-white/30 text-xs mt-1 truncate"><?= htmlspecialchars($img['service_name'] ?? 'Atamasız') ?></p>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    
    <?php if (empty($images)): ?>
    <div class="glass-card rounded-2xl p-12 text-center">
        <i data-lucide="image" class="w-16 h-16 mx-auto mb-4 text-white/20"></i>
        <p class="text-white/40">Bu kategoride görsel yok</p>
    </div>
    <?php endif; ?>
</div>

<script>
function filterByService(id) {
    window.location.href = id ? `gallery.php?service=${id}` : 'gallery.php';
}

async function updateAlt(id, alt) {
    await apiRequest('gallery.php', { action: 'update_alt', id, alt_text: alt });
}

async function setFeatured(id, serviceId) {
    const result = await apiRequest('gallery.php', { action: 'set_featured', id, service_id: serviceId });
    if (result.success) { showToast(result.message, 'success'); location.reload(); }
}

async function deleteImage(id) {
    const confirmed = await confirmAction('Bu görseli silmek istediğinize emin misiniz?');
    if (!confirmed) return;
    const result = await apiRequest('gallery.php', { action: 'delete', id });
    if (result.success) { showToast(result.message, 'success'); location.reload(); }
}

async function bulkUpdateAlt() {
    const alt = document.getElementById('bulk_alt').value;
    const serviceId = document.getElementById('service_filter').value;
    
    if (!alt) { showToast('Alt text girin', 'warning'); return; }
    if (!serviceId) { showToast('Önce bir hizmet seçin', 'warning'); return; }
    
    const images = document.querySelectorAll(`[data-service="${serviceId}"]`);
    let i = 1;
    
    for (const img of images) {
        const id = img.dataset.id;
        const numberedAlt = `${alt} ${i}`;
        await apiRequest('gallery.php', { action: 'update_alt', id, alt_text: numberedAlt });
        img.querySelector('input').value = numberedAlt;
        i++;
    }
    
    showToast(`${i-1} görsel güncellendi`, 'success');
}
</script>

<?php include 'partials/footer.php'; ?>
