<?php
// File: artist_profile.php
// Displays a single artist profile with Achievement Photos

ini_set('display_errors', 1);
error_reporting(E_ALL);

include 'db.php';

// 1. INITIALIZE VARIABLES
$artist = null;
$artist_id = 0;

// 2. DETERMINE SEARCH METHOD
if (isset($_GET['name']) && !empty($_GET['name'])) {
    // Search by Slug
    $slug = $_GET['name'];
    $stmt = $conn->prepare("SELECT * FROM artist_profiles WHERE shop_slug = ? AND subscription_status = 'active'");
    $stmt->bind_param("s", $slug);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows > 0) {
        $artist = $result->fetch_assoc();
    } else {
        // Forgiving Search
        $slug_clean = str_replace([' ', '+', '%20'], '', $slug); 
        $stmt = $conn->prepare("SELECT * FROM artist_profiles WHERE REPLACE(shop_slug, ' ', '') = ? AND subscription_status = 'active'");
        $stmt->bind_param("s", $slug_clean);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result->num_rows > 0) $artist = $result->fetch_assoc();
    }
    $stmt->close();

    if ($artist) $artist_id = $artist['user_id'];

} elseif (isset($_GET['id']) && !empty($_GET['id'])) {
    // Search by ID
    $artist_id = intval($_GET['id']);
    $stmt = $conn->prepare("SELECT * FROM artist_profiles WHERE user_id = ? AND subscription_status = 'active'");
    $stmt->bind_param("i", $artist_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) $artist = $result->fetch_assoc();
    $stmt->close();
}

// 3. IF ARTIST NOT FOUND
if (!$artist) {
    include 'header.php';
    echo "<div class='max-w-4xl mx-auto px-4 py-24 text-center'><h1 class='text-3xl font-bold text-ucf-charcoal'>Profile Unavailable</h1></div>";
    include 'footer.php';
    exit();
}

// 4. FETCH PAINTINGS
$paintings = [];
$p_stmt = $conn->prepare("SELECT id, title, image_path, price, sale_price FROM paintings WHERE artist_id = ? ORDER BY uploaded_at DESC");
$p_stmt->bind_param("i", $artist_id);
$p_stmt->execute();
$p_result = $p_stmt->get_result();
if ($p_result) $paintings = $p_result->fetch_all(MYSQLI_ASSOC);
$p_stmt->close();

// 5. FETCH ACHIEVEMENT PHOTOS (NEW)
$ach_photos = [];
$a_stmt = $conn->prepare("SELECT image_path FROM artist_achievements WHERE user_id = ? ORDER BY uploaded_at DESC");
$a_stmt->bind_param("i", $artist_id);
$a_stmt->execute();
$a_res = $a_stmt->get_result();
if ($a_res) $ach_photos = $a_res->fetch_all(MYSQLI_ASSOC);
$a_stmt->close();

// --- DATA PREPARATION ---
$full_name = htmlspecialchars($artist['first_name'] . ' ' . $artist['last_name']);
$shop_name = htmlspecialchars($artist['shop_name']);
$bio = htmlspecialchars(strip_tags($artist['bio'] ?? ''));
$short_bio = mb_substr($bio, 0, 150) . '...';
$image_url = "https://unitedculturalforum.com/" . ($artist['profile_image_path'] ?? 'images/default_avatar.png');

if (!empty($artist['shop_slug'])) {
    $page_url = "https://unitedculturalforum.com/artist/" . rawurlencode($artist['shop_slug']);
} else {
    $page_url = "https://unitedculturalforum.com/artist_profile.php?id=" . $artist['user_id'];
}

$share_text = "Check out the artwork of $full_name on UCF!";

include 'header.php';
?>

<head>
    <meta property="og:title" content="<?php echo $shop_name; ?> - Artist Profile">
    <meta property="og:description" content="<?php echo $short_bio; ?>">
    <meta property="og:image" content="<?php echo $image_url; ?>">
    <meta property="og:url" content="<?php echo $page_url; ?>">
    <meta property="og:type" content="profile">
</head>

<div class="bg-gray-50 min-h-screen pb-20">
    
    <div class="bg-white shadow-sm border-b border-gray-200">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
            <div class="md:flex items-center md:space-x-10">
                
                <div class="flex-shrink-0 text-center md:text-left">
                    <img class="h-40 w-40 rounded-full object-cover border-4 border-ucf-green mx-auto shadow-lg" 
                         src="<?php echo htmlspecialchars($artist['profile_image_path'] ?? 'images/default_avatar.png'); ?>" 
                         alt="<?php echo $shop_name; ?>">
                </div>

                <div class="mt-6 md:mt-0 text-center md:text-left flex-1">
                    <h1 class="text-4xl font-extrabold text-ucf-charcoal"><?php echo $shop_name; ?></h1>
                    <p class="text-xl text-gray-500 mt-1"><?php echo $full_name; ?></p>
                    <span class="inline-block bg-ucf-green-light text-ucf-green-dark text-sm font-bold px-3 py-1 rounded-full mt-2 uppercase tracking-wide">
                        <?php echo htmlspecialchars($artist['art_specialization'] ?? 'Artist'); ?>
                    </span>

                    <div class="mt-6 flex justify-center md:justify-start space-x-5">
                        <?php if(!empty($artist['social_facebook'])): ?><a href="<?php echo $artist['social_facebook']; ?>" target="_blank" class="text-gray-400 hover:text-blue-600 transition"><i class="fab fa-facebook fa-2x"></i></a><?php endif; ?>
                        <?php if(!empty($artist['social_instagram'])): ?><a href="<?php echo $artist['social_instagram']; ?>" target="_blank" class="text-gray-400 hover:text-pink-600 transition"><i class="fab fa-instagram fa-2x"></i></a><?php endif; ?>
                        <?php if(!empty($artist['social_twitter'])): ?><a href="<?php echo $artist['social_twitter']; ?>" target="_blank" class="text-gray-400 hover:text-blue-400 transition"><i class="fab fa-twitter fa-2x"></i></a><?php endif; ?>
                        <?php if(!empty($artist['social_linkedin'])): ?><a href="<?php echo $artist['social_linkedin']; ?>" target="_blank" class="text-gray-400 hover:text-blue-700 transition"><i class="fab fa-linkedin fa-2x"></i></a><?php endif; ?>
                    </div>
                </div>

                <div class="mt-8 md:mt-0 flex flex-col space-y-3">
                    <button onclick="openShareModal()" class="bg-blue-600 text-white font-bold py-2 px-6 rounded-lg hover:bg-blue-700 transition shadow flex items-center justify-center w-full md:w-auto">
                        <i class="fas fa-share-alt mr-2"></i> Share Profile
                    </button>
                    
                    <form action="follow_handler.php" method="POST">
                        <input type="hidden" name="artist_id" value="<?php echo $artist_id; ?>">
                        <?php 
                            $is_following = false;
                            if(isset($_SESSION['user_id'])) {
                                $chk = $conn->query("SELECT id FROM followers WHERE customer_id=".$_SESSION['user_id']." AND artist_id=".$artist_id);
                                if($chk && $chk->num_rows > 0) $is_following = true;
                            }
                        ?>
                        <?php if(isset($_SESSION['user_id'])): ?>
                            <?php if($is_following): ?>
                                <button type="submit" name="unfollow" class="w-full bg-gray-200 text-gray-700 font-bold py-2 px-6 rounded-lg hover:bg-gray-300 transition">Following</button>
                            <?php else: ?>
                                <button type="submit" name="follow" class="w-full bg-ucf-green text-white font-bold py-2 px-6 rounded-lg hover:bg-ucf-green-dark transition">Follow</button>
                            <?php endif; ?>
                        <?php else: ?>
                            <a href="login.php" class="block w-full text-center bg-gray-100 text-gray-600 font-bold py-2 px-6 rounded-lg hover:bg-gray-200">Login to Follow</a>
                        <?php endif; ?>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-12">
            
            <div class="lg:col-span-1 space-y-8">
                
                <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-100">
                    <h3 class="text-lg font-bold text-ucf-charcoal border-b pb-2 mb-4">Biography</h3>
                    <p class="text-gray-600 whitespace-pre-line leading-relaxed">
                        <?php echo !empty($bio) ? nl2br($bio) : 'No biography available.'; ?>
                    </p>
                </div>

                <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-100">
                    <h3 class="text-lg font-bold text-ucf-charcoal border-b pb-2 mb-4">Details</h3>
                    
                    <?php if(!empty($artist['subjects'])): ?>
                        <div class="mb-4">
                            <span class="block text-xs font-bold text-gray-400 uppercase">Subjects</span>
                            <span class="text-gray-700"><?php echo htmlspecialchars($artist['subjects']); ?></span>
                        </div>
                    <?php endif; ?>

                    <?php if(!empty($artist['achievements'])): ?>
                        <div class="mb-4">
                            <span class="block text-xs font-bold text-gray-400 uppercase">Achievements</span>
                            <span class="text-gray-700"><?php echo nl2br(htmlspecialchars($artist['achievements'])); ?></span>
                        </div>
                    <?php endif; ?>

                    <?php if(!empty($ach_photos)): ?>
                        <div class="mb-4">
                            <span class="block text-xs font-bold text-gray-400 uppercase mb-2">Achievement Photos</span>
                            <div class="grid grid-cols-3 gap-2">
                                <?php foreach($ach_photos as $photo): ?>
                                    <a href="https://unitedculturalforum.com/<?php echo htmlspecialchars($photo['image_path']); ?>" target="_blank" class="block h-16 w-full rounded overflow-hidden border hover:opacity-75 transition">
                                        <img src="https://unitedculturalforum.com/<?php echo htmlspecialchars($photo['image_path']); ?>" class="w-full h-full object-cover">
                                    </a>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endif; ?>

                    <div class="pt-4 border-t border-gray-100">
                        <p class="text-sm text-gray-500"><i class="fas fa-map-marker-alt mr-2 text-ucf-green"></i> <?php echo htmlspecialchars($artist['address'] ?? 'Unknown Location'); ?></p>
                    </div>
                </div>
            </div>

            <div class="lg:col-span-2">
                <h2 class="text-2xl font-bold text-ucf-charcoal mb-6 flex items-center">
                    <i class="fas fa-palette mr-3 text-ucf-green"></i> Artwork Gallery
                </h2>

                <?php if (!empty($paintings)): ?>
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
                        <?php foreach ($paintings as $painting): ?>
                            <div class="group bg-white rounded-lg shadow-md overflow-hidden hover:shadow-xl transition-all duration-300">
                                <a href="painting_single.php?id=<?php echo $painting['id']; ?>" class="block relative h-64 bg-gray-200">
                                    <img src="<?php echo htmlspecialchars($painting['image_path']); ?>" 
                                         alt="<?php echo htmlspecialchars($painting['title']); ?>" 
                                         class="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105">
                                    <div class="absolute inset-0 bg-black bg-opacity-0 group-hover:bg-opacity-20 transition-all"></div>
                                </a>
                                <div class="p-4">
                                    <h3 class="text-lg font-bold text-ucf-charcoal truncate">
                                        <a href="painting_single.php?id=<?php echo $painting['id']; ?>">
                                            <?php echo htmlspecialchars($painting['title']); ?>
                                        </a>
                                    </h3>
                                    <div class="mt-2 flex justify-between items-center">
                                        <span class="text-ucf-green font-bold">
                                            ₹<?php echo number_format($painting['sale_price'] ?: $painting['price']); ?>
                                        </span>
                                        <a href="painting_single.php?id=<?php echo $painting['id']; ?>" class="text-sm text-blue-600 hover:underline">View Details</a>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <div class="text-center py-12 bg-white rounded-lg shadow-sm border border-gray-100">
                        <i class="fas fa-image fa-3x text-gray-300 mb-3"></i>
                        <p class="text-gray-500">This artist hasn't uploaded any artwork yet.</p>
                    </div>
                <?php endif; ?>
            </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 Profile
            </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 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-mobile-alt mr-2 text-yellow-400"></i> Share to Apps
            </button>
            <p class="text-xs text-center text-gray-500 mt-2">Share via WhatsApp, Instagram, etc.</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" value="<?php echo htmlspecialchars($page_url); ?>">
            <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 nativeSection = document.getElementById('native-share-section');
    const shareUrl = "<?php echo $page_url; ?>";
    const shareTitle = "<?php echo htmlspecialchars($shop_name); ?>";
    const shareText = "<?php echo htmlspecialchars($share_text); ?>";

    function openShareModal() {
        if (navigator.share) { nativeSection.classList.remove('hidden'); } else { nativeSection.classList.add('hidden'); }
        const waBtn = document.getElementById('waShare');
        const fbBtn = document.getElementById('fbShare');
        const encodedText = encodeURIComponent(shareText + " " + shareUrl);
        const isMobile = /iPhone|Android/i.test(navigator.userAgent);
        
        if (isMobile) { waBtn.href = `whatsapp://send?text=${encodedText}`; } 
        else { waBtn.href = `https://web.whatsapp.com/send?text=${encodedText}`; }
        
        fbBtn.href = `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(shareUrl)}`;
        sharePopup.classList.remove('hidden');
        sharePopup.classList.add('flex');
    }

    async function processNativeShare() {
        if (navigator.share) {
            try { await navigator.share({ title: shareTitle, text: shareText, url: shareUrl }); } 
            catch (err) { console.log('Error sharing', err); }
        }
    }

    function closeSharePopup() { sharePopup.classList.add('hidden'); sharePopup.classList.remove('flex'); }
    function copyShareLink() {
        const input = document.getElementById('shareInput');
        input.select();
        input.setSelectionRange(0, 99999);
        navigator.clipboard.writeText(input.value).then(() => alert("Link copied!"));
    }
    window.onclick = function(e) { if (e.target == sharePopup) closeSharePopup(); }
</script>

<?php include 'footer.php'; ?>