<?php
// File: paintings.php (Public Gallery with Smart Links)
include 'header.php';

// --- 1. GET FILTER PARAMETERS FROM URL ---
$search_query = isset($_GET['search']) ? htmlspecialchars(trim($_GET['search'])) : '';
$category_id = isset($_GET['category']) ? intval($_GET['category']) : 0;
$max_price = isset($_GET['max_price']) ? intval($_GET['max_price']) : 50000; 

// Base URL (Update if needed)
$base_url = "https://unitedculturalforum.com/"; 

// --- 2. FETCH CATEGORIES ---
$categories = [];
$cat_result = $conn->query("SELECT id, name FROM categories ORDER BY name ASC");
if ($cat_result) {
    $categories = $cat_result->fetch_all(MYSQLI_ASSOC);
}

// --- 3. BUILD THE DYNAMIC SQL QUERY ---
// UPDATED: Added ap.shop_slug to the SELECT list
$sql = "SELECT DISTINCT
            p.id, p.title, p.image_path, p.price, p.sale_price, p.artist_id,
            ap.shop_slug,
            CONCAT(ap.first_name, ' ', ap.last_name) as artist_name 
        FROM paintings p 
        LEFT JOIN artist_profiles ap ON p.artist_id = ap.user_id
        LEFT JOIN painting_categories pc ON p.id = pc.painting_id";

$where_clauses = [];
$bind_params = [];
$types = '';

// Add search query filter
if (!empty($search_query)) {
    $where_clauses[] = "p.title LIKE ?";
    $types .= 's';
    $bind_params[] = '%' . $search_query . '%';
}

// Add category filter
if ($category_id > 0) {
    $where_clauses[] = "pc.category_id = ?";
    $types .= 'i';
    $bind_params[] = $category_id;
}

// Add price filter
$where_clauses[] = "COALESCE(p.sale_price, p.price) <= ?";
$types .= 'i';
$bind_params[] = $max_price;

if (!empty($where_clauses)) {
    $sql .= " WHERE " . implode(" AND ", $where_clauses);
}

$sql .= " ORDER BY p.uploaded_at DESC";

// --- 4. EXECUTE THE QUERY ---
$paintings = [];
$stmt = $conn->prepare($sql);
if ($stmt) {
    if (!empty($bind_params)) {
        $stmt->bind_param($types, ...$bind_params);
    }
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result) {
        $paintings = $result->fetch_all(MYSQLI_ASSOC);
    }
    $stmt->close();
}
?>

<style>
    .protected-media {
        -webkit-user-drag: none;
        user-select: none;
        -moz-user-select: none;
        -webkit-user-select: none;
        -ms-user-select: none;
        pointer-events: none; /* Clicks pass through to the parent link */
    }
    /* Transparent shield logic */
    .img-shield {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 10; /* Sits on top of image */
        background: rgba(255, 255, 255, 0); /* Transparent */
    }
</style>

<div class="bg-gray-50 py-12 md:py-20" oncontextmenu="return false;">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="text-center mb-12">
            <h1 class="text-4xl font-extrabold text-ucf-charcoal sm:text-5xl tracking-tight">Browse Artwork</h1>
            <p class="mt-4 max-w-2xl mx-auto text-xl text-gray-500">Discover unique paintings from talented artists.</p>
        </div>
        
        <div class="grid grid-cols-1 md:grid-cols-4 gap-8">
            <aside class="md:col-span-1">
                <div class="bg-white p-6 rounded-lg shadow-md sticky top-28">
                    <h3 class="text-xl font-bold text-ucf-charcoal mb-4">Search & Filter</h3>
                    <form action="paintings.php" method="GET" class="space-y-6">
                        <div>
                            <label for="search" class="block text-sm font-medium text-gray-700">Search by Name</label>
                            <input type="text" name="search" id="search" value="<?php echo $search_query; ?>" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:ring-ucf-green focus:border-ucf-green" placeholder="e.g., Sunset">
                        </div>
                        <div>
                            <label for="category" class="block text-sm font-medium text-gray-700">Category</label>
                            <select name="category" id="category" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:ring-ucf-green focus:border-ucf-green">
                                <option value="0">All Categories</option>
                                <?php foreach ($categories as $cat): ?>
                                    <option value="<?php echo $cat['id']; ?>" <?php if ($category_id == $cat['id']) echo 'selected'; ?>>
                                        <?php echo htmlspecialchars($cat['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div>
                            <label for="price-range" class="block text-sm font-medium text-gray-700">Max Price</label>
                            <input type="range" id="price-range" min="0" max="50000" value="<?php echo $max_price; ?>" step="100" class="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer mt-2">
                            <input type="hidden" name="max_price" id="max_price_hidden" value="<?php echo $max_price; ?>">
                            <div class="flex justify-between text-sm text-gray-600 mt-2">
                                <span>₹0</span>
                                <span id="price-display">₹<?php echo number_format($max_price); ?></span>
                            </div>
                        </div>

                        <button type="submit" class="w-full bg-ucf-green text-white font-bold py-2 px-4 rounded-lg hover:bg-ucf-green-dark transition-colors">Apply Filters</button>
                    </form>
                </div>
            </aside>

            <main class="md:col-span-3">
                <?php if (!empty($paintings)): ?>
                    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                        <?php foreach ($paintings as $painting): ?>
                            <div class="group relative bg-white rounded-lg shadow-md overflow-hidden transition-shadow duration-300 hover:shadow-xl flex flex-col">
                                
                                <a href="painting_single.php?id=<?php echo $painting['id']; ?>" class="relative w-full h-56 bg-gray-200 block">
                                    
                                    <img src="<?php echo htmlspecialchars($painting['image_path']); ?>" 
                                         alt="<?php echo htmlspecialchars($painting['title']); ?>" 
                                         class="w-full h-full object-cover protected-media"
                                         oncontextmenu="return false;">
                                    
                                    <div class="img-shield" oncontextmenu="return false;"></div>
                                </a>

                                <div class="p-4 flex flex-col flex-grow">
                                    <h3 class="text-lg font-bold text-ucf-charcoal">
                                        <a href="painting_single.php?id=<?php echo $painting['id']; ?>">
                                            <?php echo htmlspecialchars($painting['title']); ?>
                                        </a>
                                    </h3>
                                    
                                    <p class="text-sm text-gray-500 mt-1">
                                        by 
                                        <?php if(!empty($painting['artist_name'])): ?>
                                            <?php
                                                // SMART LINK LOGIC
                                                if (!empty($painting['shop_slug'])) {
                                                    $a_link = "artist/" . rawurlencode($painting['shop_slug']);
                                                } else {
                                                    $a_link = "artist_profile.php?id=" . $painting['artist_id'];
                                                }
                                            ?>
                                            <a href="<?php echo $a_link; ?>" class="text-ucf-green hover:underline font-semibold">
                                                <?php echo htmlspecialchars($painting['artist_name']); ?>
                                            </a>
                                        <?php else: ?>
                                            Unknown Artist
                                        <?php endif; ?>
                                    </p>

                                    <div class="mt-2 flex items-center justify-between">
                                        <p class="text-lg font-semibold text-ucf-green">
                                            <?php if (isset($painting['sale_price']) && $painting['sale_price'] > 0): ?>
                                                ₹<?php echo number_format($painting['sale_price'], 2); ?>
                                                <span class="text-sm text-gray-400 line-through ml-1">₹<?php echo number_format($painting['price'], 2); ?></span>
                                            <?php else: ?>
                                                ₹<?php echo number_format($painting['price'] ?? 0, 2); ?>
                                            <?php endif; ?>
                                        </p>
                                    </div>
                                    
                                    <div class="mt-4 pt-4 border-t border-gray-200 flex-grow flex items-end">
                                        <form action="cart_handler.php" method="POST" class="w-full">
                                            <input type="hidden" name="action" value="add">
                                            <input type="hidden" name="painting_id" value="<?php echo $painting['id']; ?>">
                                            <button type="submit" class="w-full bg-ucf-green text-white font-bold py-2 px-4 rounded-lg hover:bg-ucf-green-dark transition-colors flex items-center justify-center">
                                                <i class="fas fa-shopping-cart mr-2"></i>
                                                Add to Cart
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <div class="text-center py-16 bg-white rounded-lg shadow-md">
                        <i class="fas fa-search-minus fa-3x text-gray-400 mb-4"></i>
                        <h2 class="text-2xl font-bold text-ucf-charcoal">No Paintings Found</h2>
                        <p class="text-gray-500 mt-2">No artwork matched your filter criteria. Please try again.</p>
                    </div>
                <?php endif; ?>
            </main>
        </div>
    </div>
</div>

<script>
    // Price Range Slider Logic
    const priceRange = document.getElementById('price-range');
    const priceDisplay = document.getElementById('price-display');
    const maxPriceHidden = document.getElementById('max_price_hidden');

    if(priceRange) {
        priceRange.addEventListener('input', function() {
            const value = parseInt(this.value).toLocaleString('en-IN');
            priceDisplay.textContent = `₹${value}`;
            maxPriceHidden.value = this.value;
        });
    }

    // DISABLE IMAGE DRAGGING & RIGHT CLICK GLOBALLY ON IMAGES
    document.querySelectorAll('img').forEach(img => {
        img.addEventListener('dragstart', event => event.preventDefault());
        img.addEventListener('contextmenu', event => event.preventDefault());
    });
</script>

<?php include 'footer.php'; ?>