<?php
// File: profiles.php (Direct Link Version)

ini_set('display_errors', 1);
error_reporting(E_ALL);

include 'header.php';

// Base URL (Update to real domain)
$base_url = "https://unitedculturalforum.com/"; 

// --- 1. FETCH ARTIST PROFILES ---
$artists = [];
if (isset($conn) && $conn) {
    $sql = "SELECT 
                u.id as user_id, u.email,
                ap.first_name, ap.last_name, ap.shop_name, ap.profile_image_path,
                ap.shop_slug,
                ap.address, ap.phone, ap.bio, ap.achievements, ap.artist_statement,
                ap.art_specialization, ap.subjects, ap.awards, ap.additional_notes,
                ap.social_facebook, ap.social_instagram, ap.social_twitter, ap.social_linkedin
            FROM users u
            JOIN artist_profiles ap ON u.id = ap.user_id
            WHERE u.role = 'artist' AND ap.subscription_status = 'active'
            ORDER BY u.created_at DESC";

    $result = $conn->query($sql);
    if ($result) $artists = $result->fetch_all(MYSQLI_ASSOC);

    // Check Follow Status
    $followed_artists = []; 
    if (isset($_SESSION['user_id'])) {
        $current_user_id = $_SESSION['user_id'];
        $stmt = $conn->prepare("SELECT artist_id FROM followers WHERE customer_id = ?");
        if ($stmt) {
            $stmt->bind_param("i", $current_user_id);
            $stmt->execute();
            $res = $stmt->get_result();
            while($row = $res->fetch_assoc()) $followed_artists[] = $row['artist_id'];
            $stmt->close();
        }
    }
}
?>

<div class="bg-gray-50 py-12 md:py-20">
    <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">Meet Our Artists</h1>
            <p class="mt-4 max-w-2xl mx-auto text-xl text-gray-500">Discover the talented individuals behind the amazing artwork.</p>
        </div>

        <?php if (!empty($artists)): ?>
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-8">
                <?php foreach ($artists as $artist): 
                    $full_name = htmlspecialchars(($artist['first_name'] ?? '') . ' ' . ($artist['last_name'] ?? ''));
                    $is_following = in_array($artist['user_id'], $followed_artists);
                    
                    // Generate Direct Link (Slug or ID)
                    if (!empty($artist['shop_slug'])) {
                        $profile_link = $base_url . "artist/" . rawurlencode($artist['shop_slug']);
                        // Note: If .htaccess isn't working yet, use: 
                        // $profile_link = $base_url . "artist_profile.php?name=" . rawurlencode($artist['shop_slug']);
                    } else {
                        $profile_link = $base_url . "artist_profile.php?id=" . $artist['user_id'];
                    }
                    
                    $spec = htmlspecialchars($artist['art_specialization'] ?? 'Artist');
                    
                    // Share Data
                    $share_msg  = "🎨 Meet " . $full_name . "!\n";
                    $share_msg .= "Specialization: " . $spec . "\n";
                    $share_msg .= "Check out their full portfolio on UCF: " . $profile_link;
                ?>
                    <div class="bg-white rounded-lg shadow-lg overflow-hidden transform hover:-translate-y-2 transition-transform duration-300 flex flex-col h-full">
                        
                        <div class="p-6 flex-1">
                            <div class="flex items-center space-x-4">
                                <div class="flex-shrink-0">
                                    <a href="<?php echo $profile_link; ?>">
                                        <img class="h-20 w-20 rounded-full object-cover border-4 border-ucf-green-light hover:opacity-90 transition" 
                                             src="<?php echo htmlspecialchars($artist['profile_image_path'] ?? '/images/default_avatar.png'); ?>" 
                                             alt="<?php echo htmlspecialchars($artist['shop_name']); ?>">
                                    </a>
                                </div>
                                
                                <div class="flex-1 min-w-0">
                                    <h3 class="text-2xl font-bold text-ucf-charcoal truncate">
                                        <a href="<?php echo $profile_link; ?>" class="hover:text-ucf-green-dark transition-colors">
                                            <?php echo htmlspecialchars($artist['shop_name']); ?>
                                        </a>
                                    </h3>
                                    <p class="text-sm text-gray-500 truncate"><?php echo $full_name; ?></p>
                                    <p class="text-xs text-ucf-green font-semibold mt-1 truncate">
                                        <?php echo $spec; ?>
                                    </p>
                                </div>
                            </div>

                            <div class="mt-6 pt-4 border-t border-gray-100 flex items-center justify-between gap-2">
                                
                                <a href="<?php echo $profile_link; ?>" class="flex-1 text-center bg-gray-100 text-gray-700 font-bold py-2 rounded text-sm hover:bg-gray-200 transition">
                                    View Profile
                                </a>

                                <button onclick="openShareModal(this)" 
                                        data-url="<?php echo htmlspecialchars($profile_link); ?>"
                                        data-title="<?php echo htmlspecialchars($artist['shop_name']); ?>"
                                        data-msg="<?php echo htmlspecialchars($share_msg, ENT_QUOTES); ?>"
                                        data-image="<?php echo htmlspecialchars($artist['profile_image_path'] ?? '/images/default_avatar.png'); ?>"
                                        class="bg-blue-50 text-blue-600 px-3 py-2 rounded hover:bg-blue-100 transition"
                                        title="Share Artist">
                                    <i class="fas fa-share-alt"></i>
                                </button>

                                <form action="follow_handler.php" method="POST" class="inline-block">
                                    <input type="hidden" name="artist_id" value="<?php echo $artist['user_id']; ?>">
                                    <?php if (isset($_SESSION['user_id'])): ?>
                                        <?php if ($is_following): ?>
                                            <button type="submit" name="unfollow" class="bg-gray-200 text-gray-500 px-3 py-2 rounded hover:bg-gray-300 transition" title="Unfollow">
                                                <i class="fas fa-user-check"></i>
                                            </button>
                                        <?php else: ?>
                                            <button type="submit" name="follow" class="bg-ucf-green text-white px-3 py-2 rounded hover:bg-ucf-green-dark transition" title="Follow">
                                                <i class="fas fa-user-plus"></i>
                                            </button>
                                        <?php endif; ?>
                                    <?php else: ?>
                                        <a href="login.php" class="bg-ucf-green text-white px-3 py-2 rounded hover:bg-ucf-green-dark inline-block"><i class="fas fa-user-plus"></i></a>
                                    <?php endif; ?>
                                </form>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <div class="text-center bg-white p-12 rounded-lg shadow-md">
                <h2 class="text-2xl font-bold text-ucf-charcoal">No Artists Found</h2>
            </div>
        <?php endif; ?>
    </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 Artist
            </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>
        
        <p class="text-xs font-bold text-gray-500 uppercase tracking-wide mb-3">Share Link via:</p>
        <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: '', title: '', text: '', image: '' };

    function openShareModal(