<?php
// File: /artist/paintings.php
include 'header.php'; 

$artist_id = $_SESSION['user_id'];
$action = $_GET['action'] ?? 'list'; 
$edit_mode = false;
$painting_to_edit = null;

// Domain configuration
$base_url = "https://unitedculturalforum.com/"; 

// 1. FETCH ARTIST NAME
$artist_name = "an Artist"; 
$name_stmt = $conn->prepare("SELECT CONCAT(first_name, ' ', last_name) as full_name FROM artist_profiles WHERE user_id = ?");
$name_stmt->bind_param("i", $artist_id);
$name_stmt->execute();
$name_res = $name_stmt->get_result();
if($row = $name_res->fetch_assoc()) {
    $artist_name = $row['full_name'];
}

// --- HANDLE EDIT MODE ---
if ($action === 'edit' && isset($_GET['id'])) {
    $edit_mode = true;
    $painting_id = filter_var($_GET['id'], FILTER_SANITIZE_NUMBER_INT);
    $stmt = $conn->prepare("SELECT * FROM paintings WHERE id = ? AND artist_id = ?");
    $stmt->bind_param("ii", $painting_id, $artist_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) $painting_to_edit = $result->fetch_assoc();
    else { header('Location: paintings.php?error=not_found'); exit(); }
    $stmt->close();
}

// Fetch Paintings
$paintings = [];
$stmt = $conn->prepare("SELECT id, title, price, sale_price, image_path, description FROM paintings WHERE artist_id = ? ORDER BY uploaded_at DESC");
$stmt->bind_param("i", $artist_id);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows > 0) $paintings = $result->fetch_all(MYSQLI_ASSOC);
$stmt->close();
?>

<div class="p-6 md:p-8">
    <div class="flex justify-between items-center mb-6">
        <h1 class="text-3xl font-bold text-ucf-charcoal">My Paintings</h1>
        <?php if ($action !== 'add' && !$edit_mode): ?>
            <a href="paintings.php?action=add" class="bg-ucf-green text-white font-bold py-2 px-4 rounded-lg hover:bg-ucf-green-dark transition-colors flex items-center">
                <i class="fas fa-plus-circle mr-2"></i> Add New Painting
            </a>
        <?php endif; ?>
    </div>

    <?php if ($action === 'add' || $edit_mode): ?>
    <div class="bg-white p-6 rounded-lg shadow-md mb-8">
        <h2 class="text-2xl font-bold text-ucf-charcoal mb-4">
            <?php echo $edit_mode ? 'Edit Painting Details' : 'Upload a New Painting'; ?>
        </h2>

        <form action="paintings_handler.php" method="POST" enctype="multipart/form-data" class="space-y-6">
            
            <?php if ($edit_mode && $painting_to_edit): ?>
                <input type="hidden" name="painting_id" value="<?php echo htmlspecialchars($painting_to_edit['id']); ?>">
                <input type="hidden" name="existing_image_path" value="<?php echo htmlspecialchars($painting_to_edit['image_path']); ?>">
            <?php endif; ?>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                
                <div class="md:col-span-2">
                    <label class="block text-sm font-medium text-gray-700">Painting Title *</label>
                    <input type="text" name="title" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm p-2 border" 
                           value="<?php echo $edit_mode ? htmlspecialchars($painting_to_edit['title']) : ''; ?>">
                </div>

                <div class="md:col-span-2">
                    <label class="block text-sm font-medium text-gray-700">Painting Image *</label>
                    <input type="file" name="painting_image" class="mt-1 block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:bg-ucf-green-light file:text-ucf-green-dark" 
                           <?php echo !$edit_mode ? 'required' : ''; ?>>
                    <?php if ($edit_mode && !empty($painting_to_edit['image_path'])): ?>
                        <p class="text-xs text-gray-500 mt-2">Current image:</p>
                        <img src="../<?php echo htmlspecialchars($painting_to_edit['image_path']); ?>" class="h-24 w-auto mt-1 rounded border">
                    <?php endif; ?>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700">Size (Height x Width) *</label>
                    <input type="text" name="size_dimensions" required placeholder="e.g., 24 x 36 inches" 
                           class="mt-1 block w-full rounded-md border-gray-300 shadow-sm p-2 border"
                           value="<?php echo $edit_mode ? htmlspecialchars($painting_to_edit['size_dimensions'] ?? '') : ''; ?>">
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700">Medium *</label>
                    <input type="text" name="medium" required placeholder="e.g., Oil, Acrylic, Watercolor" 
                           class="mt-1 block w-full rounded-md border-gray-300 shadow-sm p-2 border"
                           value="<?php echo $edit_mode ? htmlspecialchars($painting_to_edit['medium'] ?? '') : ''; ?>">
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700">Category / Subject *</label>
                    <select name="subject_category" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm p-2 border bg-white">
                        <option value="">Select Category</option>
                        <?php 
                            $categories = ['Portrait', 'Abstract', 'Still Life', 'Figurative', 'Landscape', 'Seascape', 'Cityscape', 'Digital Art', 'Mythological', 'Other'];
                            $current_cat = $edit_mode ? ($painting_to_edit['subject_category'] ?? '') : '';
                            foreach($categories as $cat) {
                                $selected = ($current_cat === $cat) ? 'selected' : '';
                                echo "<option value='$cat' $selected>$cat</option>";
                            }
                        ?>
                    </select>
                </div>

                <div class="md:col-span-2">
                    <label class="block text-sm font-medium text-gray-700">Tags (Keywords)</label>
                    <input type="text" name="tags" placeholder="#blue, #calm, #realistic, #large" 
                           class="mt-1 block w-full rounded-md border-gray-300 shadow-sm p-2 border"
                           value="<?php echo $edit_mode ? htmlspecialchars($painting_to_edit['tags'] ?? '') : ''; ?>">
                    <p class="text-xs text-gray-500 mt-1">Separate keywords with commas or spaces.</p>
                </div>

                <div class="md:col-span-2">
                    <label class="block text-sm font-medium text-gray-700">Description *</label>
                    <textarea name="description" rows="4" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm p-2 border"><?php echo $edit_mode ? htmlspecialchars($painting_to_edit['description']) : ''; ?></textarea>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700">Regular Price (₹) *</label>
                    <input type="number" name="price" step="0.01" required class="mt-1 block w-full rounded-md border-gray-300 shadow-sm p-2 border"
                           value="<?php echo $edit_mode ? htmlspecialchars($painting_to_edit['price']) : ''; ?>">
                </div>
                 <div>
                    <label class="block text-sm font-medium text-gray-700">Sale Price (₹) (Optional)</label>
                    <input type="number" name="sale_price" step="0.01" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm p-2 border"
                           value="<?php echo $edit_mode ? htmlspecialchars($painting_to_edit['sale_price']) : ''; ?>">
                </div>

                <div class="md:col-span-2 bg-gray-50 p-4 rounded border border-gray-200">
                    <div class="flex items-start">
                        <div class="flex items-center h-5">
                            <input id="copyright" name="copyright" type="checkbox" class="focus:ring-ucf-green h-5 w-5 text-ucf-green border-gray-300 rounded"
                            <?php echo ($edit_mode && isset($painting_to_edit['copyright_confirmed']) && $painting_to_edit['copyright_confirmed'] == 1) ? 'checked' : ''; ?>>
                        </div>
                        <div class="ml-3 text-sm">
                            <label for="copyright" class="font-medium text-gray-700">Copyright Declaration</label>
                            <p class="text-gray-500">I confirm that I hold the full copyright for this painting, including the right to authorize its display, promotion, and sale on United Cultural Forum.</p>
                        </div>
                    </div>
                </div>

            </div>

            <div class="flex justify-end space-x-3 pt-4">
                <a href="paintings.php" class="bg-gray-200 text-gray-700 font-bold py-2 px-4 rounded-lg hover:bg-gray-300">Cancel</a>
                <button type="submit" name="<?php echo $edit_mode ? 'edit_painting' : 'add_painting'; ?>" class="bg-ucf-green text-white font-bold py-2 px-6 rounded-lg hover:bg-ucf-green-dark shadow-md">
                    <?php echo $edit_mode ? 'Update Painting' : 'Upload Painting'; ?>
                </button>
            </div>
        </form>
    </div>
    <?php endif; ?>


    <div class="bg-white p-6 rounded-lg shadow-md">
        <h2 class="text-2xl font-bold text-ucf-charcoal mb-4">Your Uploaded Artwork</h2>
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Image</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Title</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Price</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Actions</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php foreach ($paintings as $painting): ?>
                        <?php 
                            // 1. Prepare Data
                            $p_id = $painting['id'];
                            $p_title = $painting['title'];
                            $p_price = $painting['sale_price'] ? $painting['sale_price'] : $painting['price'];
                            $share_link = $base_url . "painting_single.php?id=" . $p_id;
                            $img_relative = "../" . $painting['image_path']; 
                            
                            $share_msg  = "Check out this artwork by " . $artist_name . "!\n";
                            $share_msg .= "'" . $p_title . "' - ₹" . number_format($p_price) . "\n";
                            $share_msg .= "View here: " . $share_link;
                        ?>
                        <tr>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <img src="<?php echo htmlspecialchars($img_relative); ?>" class="h-16 w-16 object-cover rounded shadow-sm">
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                                <?php echo htmlspecialchars($p_title); ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                ₹<?php echo number_format($p_price, 2); ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium flex items-center space-x-3">
                                
                                <button onclick="openShareModal(this)" 
                                        data-url="<?php echo htmlspecialchars($share_link); ?>"
                                        data-title="<?php echo htmlspecialchars($p_title); ?>"
                                        data-msg="<?php echo htmlspecialchars($share_msg, ENT_QUOTES); ?>"
                                        data-image="<?php echo htmlspecialchars($img_relative); ?>"
                                        class="bg-blue-600 text-white px-3 py-1.5 rounded hover:bg-blue-700 flex items-center transition shadow-sm cursor-pointer" 
                                        title="Share Image & Text">
                                    <i class="fas fa-share-alt mr-2"></i> Share
                                </button>

                                <span class="text-gray-300">|</span>

                                <a href="paintings.php?action=edit&id=<?php echo $p_id; ?>" class="text-indigo-600 hover:text-indigo-900">Edit</a>
                                
                                <form action="paintings_handler.php" method="POST" class="inline" onsubmit="return confirm('Delete this painting?');">
                                    <input type="hidden" name="painting_id" value="<?php echo $p_id; ?>">
                                    <button type="submit" name="delete_painting" class="text-red-600 hover:text-red-900 ml-2">Delete</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div id="shareModal" class="fixed inset-0 bg-black bg-opacity-60 hidden items-center justify-center z-50 backdrop-blur-sm">
    <div class="bg-white rounded-xl shadow-2xl p-6 w-full max-w-md mx-4 transform transition-all scale-100 relative">
        
        <div class="flex justify-between items-center mb-6 border-b pb-2">
            <h3 class="text-xl font-bold text-ucf-charcoal">Share Artwork</h3>
            <button onclick="closeShareModal()" class="text-gray-400 hover:text-gray-600 text-3xl font-bold leading-none">&times;</button>
        </div>

        <div id="nativeShareContainer" class="mb-6 hidden">
            <button onclick="processImageShare()" id="btnNative" class="w-full bg-gray-800 text-white font-bold py-3 rounded-lg flex items-center justify-center hover:bg-black transition shadow-lg">
                <i class="fas fa-image mr-2"></i> Share Image File & Text
            </button>
            <p class="text-xs text-center text-gray-500 mt-1">Best for Mobile (WhatsApp/Instagram)</p>
        </div>
        
        <p class="text-sm font-bold text-gray-700 mb-3">Share Link via:</p>
        <div class="grid grid-cols-2 gap-4 mb-6">
            <a id="waShare" href="#" target="_blank" class="flex items-center justify-center p-3 rounded-lg bg-[#25D366] text-white hover:opacity-90 transition shadow-sm font-bold">
                <i class="fab fa-whatsapp text-xl mr-2"></i> WhatsApp
            </a>
            <a id="fbShare" href="#" target="_blank" class="flex items-center justify-center p-3 rounded-lg bg-[#1877F2] text-white hover:opacity-90 transition shadow-sm font-bold">
                <i class="fab fa-facebook-f text-xl mr-2"></i> Facebook
            </a>
            <a id="twShare" href="#" target="_blank" class="flex items-center justify-center p-3 rounded-lg bg-black text-white hover:opacity-90 transition shadow-sm font-bold">
                <i class="fab fa-x-twitter text-xl mr-2"></i> X / Twitter
            </a>
            <a id="liShare" href="#" target="_blank" class="flex items-center justify-center p-3 rounded-lg bg-[#0077b5] text-white hover:opacity-90 transition shadow-sm font-bold">
                <i class="fab fa-linkedin-in text-xl mr-2"></i> LinkedIn
            </a>
        </div>

        <div class="relative">
            <input type="text" id="shareInput" readonly class="w-full bg-gray-100 border border-gray-300 text-gray-500 text-sm rounded p-2 pr-16 focus:outline-none">
            <button onclick="copyShareLink()" class="absolute right-1 top-1 bottom-1 bg-white text-ucf-green font-bold text-xs px-3 rounded border border-gray-200 hover:bg-gray-50">COPY</button>
        </div>
    </div>
</div>

<script>
    const modal = document.getElementById('shareModal');
    const shareInput = document.getElementById('shareInput');
    const nativeContainer = document.getElementById('nativeShareContainer');
    const btnNative = document.getElementById('btnNative');

    let currentData = { url: '', title: '', text: '', image: '' };

    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);

        const isMobile = /iPhone|Android/i.test(navigator.userAgent);
        if (isMobile) {
            document.getElementById('waShare').href = `whatsapp://send?text=${encText}`;
        } else {
            document.getElementById('waShare').href = `https://web.whatsapp.com/send?text=${encText}`;
        }
        
        document.getElementById('fbShare').href = `https://www.facebook.com/sharer/sharer.php?u=${encUrl}`;
        document.getElementById('twShare').href = `https://twitter.com/intent/tweet?text=${encText}&url=${encUrl}`;
        document.getElementById('liShare').href = `https://www.linkedin.com/sharing/share-offsite/?url=${encUrl}`;

        if (navigator.share) {
            nativeContainer.classList.remove('hidden');
            btnNative.innerHTML = '<i class="fas fa-image mr-2"></i> Share Image File & Text';
        } else {
            nativeContainer.classList.add('hidden');
        }

        modal.classList.remove('hidden');
        modal.classList.add('flex');
    }

    async function processImageShare() {
        if (!navigator.share) return;

        try {
            btnNative.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i> Processing...';
            const response = await fetch(currentData.image);
            const blob = await response.blob();
            const file = new File([blob], "art_share.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
                });
            } else {
                await navigator.share({
                    title: currentData.title,
                    text: currentData.text,
                    url: currentData.url
                });
            }
        } catch (err) {
            console.log("Share failed or cancelled:", err);
        } finally {
            btnNative.innerHTML = '<i class="fas fa-image mr-2"></i> Share Image File & Text';
        }
    }

    function closeShareModal() {
        modal.classList.add('hidden');
        modal.classList.remove('flex');
    }

    function copyShareLink() {
        shareInput.select();
        shareInput.setSelectionRange(0, 99999);
        navigator.clipboard.writeText(shareInput.value).then(() => alert("Link copied!"));
    }

    window.onclick = function(e) { if (e.target == modal) closeShareModal(); }
</script>

<?php include 'footer.php'; ?>