<?php
// File: painting_single.php
// Shows full details of a painting + Share Option

require_once __DIR__ . '/db.php';

// Get ID
$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;

if ($id <= 0) {
    header("Location: paintings.php");
    exit;
}

// 2. FETCH PAINTING DETAILS
$sql = "SELECT p.*, 
               CONCAT(ap.first_name, ' ', ap.last_name) as artist_name,
               ap.shop_name,
               ap.shop_slug,
               ap.user_id as artist_user_id
        FROM paintings p
        LEFT JOIN artist_profiles ap ON p.artist_id = ap.user_id
        WHERE p.id = ? LIMIT 1";

$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $id);
$stmt->execute();
$result = $stmt->get_result();
$painting = $result->fetch_assoc();

if (!$painting) {
    header("Location: paintings.php");
    exit;
}

// --- DATA PREPARATION ---
$page_title = $painting['title'] . " by " . $painting['artist_name'];
$page_url = "https://unitedculturalforum.com/painting_single.php?id=" . $id;
$image_url = "https://unitedculturalforum.com/" . $painting['image_path'];
$price_display = $painting['sale_price'] ? $painting['sale_price'] : $painting['price'];

// Smart Artist Link
if (!empty($painting['shop_slug'])) {
    $artist_link = "artist_profile.php?name=" . rawurlencode($painting['shop_slug']);
} else {
    $artist_link = "artist_profile.php?id=" . $painting['artist_user_id'];
}

$share_text = "Check out '" . $painting['title'] . "' by " . $painting['artist_name'] . " on UCF! Price: ₹" . number_format($price_display);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta property="og:title" content="<?php echo htmlspecialchars($page_title); ?>">
    <meta property="og:description" content="<?php echo htmlspecialchars($share_text); ?>">
    <meta property="og:image" content="<?php echo htmlspecialchars($image_url); ?>">
    <meta property="og:url" content="<?php echo htmlspecialchars($page_url); ?>">
    <meta property="og:type" content="product">
    
    <?php include 'header.php'; ?>
</head>

<style>
    /* Image Protection Styles */
    .protected-img { pointer-events: none; -webkit-user-select: none; user-select: none; }
    .img-shield { position: absolute; top:0; left:0; width:100%; height:100%; z-index:10; }
</style>

<div class="bg-gray-50 py-8 md:py-12">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        
        <nav class="text-sm mb-6 text-gray-500">
            <a href="index.php" class="hover:underline">Home</a> > 
            <a href="paintings.php" class="hover:underline">Gallery</a> > 
            <span class="text-gray-800 font-bold"><?php echo htmlspecialchars($painting['title']); ?></span>
        </nav>

        <div class="bg-white rounded-xl shadow-lg overflow-hidden">
            <div class="grid grid-cols-1 lg:grid-cols-2">
                
                <div class="bg-gray-100 relative flex items-center justify-center w-full min-h-[400px]" oncontextmenu="return false;">
                    <img src="<?php echo htmlspecialchars($painting['image_path']); ?>" 
                         alt="<?php echo htmlspecialchars($painting['title']); ?>" 
                         class="w-full h-auto max-h-[85vh] object-contain shadow-sm protected-img">
                    <div class="img-shield"></div>
                </div>

                <div class="p-8 lg:p-12 flex flex-col h-full bg-white border-l border-gray-100">
                    
                    <div class="mb-4">
                        <span class="bg-ucf-green-light text-ucf-green-dark text-xs font-bold px-3 py-1 rounded-full uppercase tracking-wider">
                            <?php echo htmlspecialchars($painting['subject_category'] ?? 'Artwork'); ?>
                        </span>
                    </div>

                    <h1 class="text-3xl md:text-4xl font-extrabold text-ucf-charcoal mb-2">
                        <?php echo htmlspecialchars($painting['title']); ?>
                    </h1>
                    <p class="text-lg text-gray-500 mb-6">
                        Created by 
                        <a href="<?php echo $artist_link; ?>" class="text-ucf-green hover:underline font-semibold">
                            <?php echo htmlspecialchars($painting['artist_name']); ?>
                        </a>
                    </p>

                    <div class="mb-8 pb-6 border-b border-gray-100">
                        <div class="flex items-end space-x-3">
                            <span class="text-3xl font-bold text-ucf-charcoal">₹<?php echo number_format($price_display); ?></span>
                            <?php if ($painting['sale_price']): ?>
                                <span class="text-lg text-gray-400 line-through mb-1">₹<?php echo number_format($painting['price']); ?></span>
                                <span class="text-sm text-green-600 font-bold mb-2 bg-green-100 px-2 py-0.5 rounded">On Sale</span>
                            <?php endif; ?>
                        </div>
                        <p class="text-xs text-gray-400 mt-1">Includes taxes. Free shipping available.</p>
                    </div>

                    <div class="grid grid-cols-2 gap-4 mb-8">
                        <div class="bg-gray-50 p-3 rounded-lg">
                            <p class="text-xs text-gray-400 uppercase font-bold">Dimensions</p>
                            <p class="text-gray-800 font-medium"><?php echo htmlspecialchars($painting['size_dimensions'] ?? 'N/A'); ?></p>
                        </div>
                        <div class="bg-gray-50 p-3 rounded-lg">
                            <p class="text-xs text-gray-400 uppercase font-bold">Medium</p>
                            <p class="text-gray-800 font-medium"><?php echo htmlspecialchars($painting['medium'] ?? 'Mixed Media'); ?></p>
                        </div>
                    </div>

                    <div class="mb-8">
                        <h3 class="text-sm font-bold text-gray-900 uppercase mb-2">About the Artwork</h3>
                        <div class="prose text-gray-600 leading-relaxed text-sm">
                            <?php echo nl2br(htmlspecialchars($painting['description'])); ?>
                        </div>
                    </div>

                    <?php if (!empty($painting['tags'])): ?>
                        <div class="mb-8 flex flex-wrap gap-2">
                            <?php 
                                $tags = explode(',', $painting['tags']); 
                                foreach($tags as $tag): 
                                    $tag = trim($tag);
                                    if(empty($tag)) continue;
                            ?>
                                <span class="text-xs bg-gray-100 text-gray-600 px-2 py-1 rounded">#<?php echo htmlspecialchars($tag); ?></span>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>

                    <div class="mt-auto flex flex-col sm:flex-row gap-4">
                        <form action="cart_handler.php" method="POST" class="flex-1">
                            <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-3 px-6 rounded-lg hover:bg-ucf-green-dark transition shadow-lg flex items-center justify-center transform hover:scale-105 duration-200">
                                <i class="fas fa-shopping-bag mr-2"></i> Buy Now
                            </button>
                        </form>

                        <button onclick="openShareModal(this)" 
                                data-url="<?php echo htmlspecialchars($page_url); ?>"
                                data-title="<?php echo htmlspecialchars($painting['title']); ?>"
                                data-msg="<?php echo htmlspecialchars($share_text, ENT_QUOTES); ?>"
                                data-image="<?php echo $painting['image_path']; ?>" 
                                class="flex-1 bg-blue-50 text-blue-600 font-bold py-3 px-6 rounded-lg hover:bg-blue-100 transition border border-blue-200 flex items-center justify-center">
                            <i class="fas fa-share-alt mr-2"></i> Share
                        </button>
                    </div>

                    <?php if ($painting['copyright_confirmed']): ?>
                        <div class="mt-8 bg-green-50 border-l-4 border-green-500 p-4 rounded-r-lg flex items-start shadow-sm animate-fade-in">
                            <div class="flex-shrink-0">
                                <i class="fas fa-certificate text-green-600 text-xl mt-0.5"></i>
                            </div>
                            <div class="ml-3">
                                <h3 class="text-sm font-bold text-green-800 uppercase tracking-wide">
                                    Copyright Verified
                                </h3>
                                <div class="mt-1 text-sm text-green-700 font-medium">
                                    <p>
                                        Original work with confirmed copyright (©).<br>
                                        All Rights Reserved by <span class="font-bold"><?php echo htmlspecialchars($painting['artist_name']); ?></span>.
                                    </p>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                    </div>
            </div>
        </div>
    </div>
</div>

<div id="share-popup" class="fixed inset-0 z-[1000] hidden items-center justify-center bg-black bg-opacity-60 backdrop-blur-sm p-4">
    <div class="bg-white rounded-xl shadow-2xl p-6 w-full max-w-sm relative mx-auto transform transition-all scale-100">
        
        <div class="flex items-center justify-between mb-6 border-b border-gray-100 pb-3">
            <h3 class="text-lg font-bold text-ucf-charcoal flex items-center">
                <i class="fas fa-share-alt mr-2 text-ucf-green"></i> Share Artwork
            </h3>
            <button onclick="closeSharePopup()" class="text-gray-400 hover:text-red-500 transition-colors p-2 rounded-full hover:bg-gray-100 focus:outline-none">
                <i class="fas fa-times text-xl"></i>
            </button>
        </div>

        <div id="native-share-section" class="mb-6 hidden">
            <button id="btn-native-share" onclick="processNativeShare()" class="w-full bg-gray-900 text-white font-bold py-3 rounded-lg flex items-center justify-center hover:bg-black transition shadow-lg border border-gray-800 active:scale-95 transform duration-150">
                <i class="fas fa-image mr-2 text-yellow-400"></i> Share Image & Text
            </button>
            <p class="text-xs text-center text-gray-500 mt-2">Best for WhatsApp & Instagram Stories</p>
        </div>
        
        <div class="grid grid-cols-2 gap-3 mb-6">
            <a id="waShare" href="#" target="_blank" class="flex items-center justify-center p-3 rounded-lg bg-green-50 text-green-700 border border-green-200 hover:bg-green-100 transition font-bold text-sm">
                <i class="fab fa-whatsapp text-lg mr-2"></i> WhatsApp
            </a>
            <a id="fbShare" href="#" target="_blank" class="flex items-center justify-center p-3 rounded-lg bg-blue-50 text-blue-700 border border-blue-200 hover:bg-blue-100 transition font-bold text-sm">
                <i class="fab fa-facebook-f text-lg mr-2"></i> Facebook
            </a>
        </div>

        <div class="relative group">
            <input type="text" id="shareInput" readonly class="w-full bg-gray-50 border border-gray-300 text-gray-600 text-xs rounded-lg p-3 pr-20 focus:outline-none focus:ring-2 focus:ring-ucf-green focus:border-transparent">
            <button onclick="copyShareLink()" class="absolute right-1 top-1 bottom-1 bg-white text-ucf-green hover:text-green-700 font-bold text-xs px-4 rounded-md border border-gray-200 shadow-sm hover:bg-gray-50 transition-colors">
                COPY
            </button>
        </div>
    </div>
</div>

<script>
    const sharePopup = document.getElementById('share-popup');
    const shareInput = document.getElementById('shareInput');
    const nativeSection = document.getElementById('native-share-section');
    const btnNative = document.getElementById('btn-native-share');
    const waShare = document.getElementById('waShare');
    const fbShare = document.getElementById('fbShare');

    let currentData = { url: '', text: '', image: '', title: '' };

    function openShareModal(btn) {
        currentData.url = btn.getAttribute('data-url');
        currentData.title = btn.getAttribute('data-title');
        currentData.text = btn.getAttribute('data-msg');
        currentData.image = btn.getAttribute('data-image');

        shareInput.value = currentData.url;
        
        const encText = encodeURIComponent(currentData.text);
        const encUrl = encodeURIComponent(currentData.url);

        // WhatsApp: Text + Link
        const waText = `${encText}%0A${encUrl}`;

        const isMobile = /iPhone|Android/i.test(navigator.userAgent);
        if (isMobile) {
            waShare.href = `whatsapp://send?text=${waText}`;
        } else {
            waShare.href = `https://web.whatsapp.com/send?text=${waText}`;
        }
        
        fbShare.href = `https://www.facebook.com/sharer/sharer.php?u=${encUrl}`;

        if (navigator.share) {
            nativeSection.classList.remove('hidden');
        } else {
            nativeSection.classList.add('hidden');
        }

        sharePopup.classList.remove('hidden');
        sharePopup.classList.add('flex');
    }

    async function processNativeShare() {
        if (!navigator.share) return;
        try {
            btnNative.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i> Loading...';
            // Only try to fetch image if it is local (starts with /)
            if(currentData.image && !currentData.image.startsWith('http')) {
                 const response = await fetch(currentData.image);
                 const blob = await response.blob();
                 const file = new File([blob], "artwork.jpg", { type: "image/jpeg" });
                 if (navigator.canShare && navigator.canShare({ files: [file] })) {
                    await navigator.share({
                        title: currentData.title,
                        text: currentData.text,
                        files: [file],
                        url: currentData.url
                    });
                    btnNative.innerHTML = '<i class="fas fa-image mr-2"></i> Share Image & Text';
                    return;
                 }
            }
            await navigator.share({ title: currentData.title, text: currentData.text, url: currentData.url });
        } catch (err) {
            console.log('Share cancelled', err);
        } finally {
            btnNative.innerHTML = '<i class="fas fa-image mr-2"></i> Share Image & Text';
        }
    }

    function closeSharePopup() {
        sharePopup.classList.add('hidden');
        sharePopup.classList.remove('flex');
    }

    function copyShareLink() {
        shareInput.select();
        shareInput.setSelectionRange(0, 99999);
        navigator.clipboard.writeText(shareInput.value).then(() => alert("Link copied!"));
    }

    document.addEventListener('keydown', (e) => {
        if (e.key === "Escape" && !sharePopup.classList.contains('hidden')) closeSharePopup();
    });
    
    window.onclick = function(e) { if (e.target == sharePopup) closeSharePopup(); }
</script>

<?php include 'footer.php'; ?>