<?php 
// File: /artist/profile.php
include 'header.php'; 
include '../db.php';

$artist_user_id = $_SESSION['user_id'];

// 1. Fetch Profile Data
$sql = "SELECT * FROM artist_profiles WHERE user_id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $artist_user_id);
$stmt->execute();
$result = $stmt->get_result();
$profile = $result->fetch_assoc();

if (!$profile) {
    $profile = array_fill_keys(['first_name', 'last_name', 'shop_name', 'shop_slug', 'phone', 'address', 'bio', 'achievements', 'artist_statement', 'art_specialization', 'subjects', 'awards', 'additional_notes', 'bank_name', 'bank_account_iban', 'profile_image_path'], '');
}
$stmt->close();

// 2. Fetch Achievement Photos (NEW)
$ach_photos = [];
$ach_stmt = $conn->prepare("SELECT id, image_path FROM artist_achievements WHERE user_id = ? ORDER BY uploaded_at DESC");
$ach_stmt->bind_param("i", $artist_user_id);
$ach_stmt->execute();
$ach_res = $ach_stmt->get_result();
if($ach_res) $ach_photos = $ach_res->fetch_all(MYSQLI_ASSOC);
$ach_stmt->close();

// Social Link Logic
$base_url = "https://unitedculturalforum.com/artist_profile.php?name=";
$shop_url = $base_url . urlencode($profile['shop_slug'] ?: 'your-shop-name');
?>

<div class="flex justify-between items-center mb-6">
    <h1 class="text-3xl font-bold text-ucf-charcoal">Manage Your Profile</h1>
    <?php if(!empty($profile['shop_slug'])): ?>
        <a href="../artist_profile.php?name=<?php echo htmlspecialchars($profile['shop_slug']); ?>" target="_blank" class="text-ucf-green hover:underline">
            View Public Profile <i class="fas fa-external-link-alt"></i>
        </a>
    <?php endif; ?>
</div>

<?php if (isset($_GET['status'])): ?>
    <div class="mb-6 p-4 rounded-md <?php echo $_GET['status']=='success' || $_GET['status']=='deleted' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'; ?>">
        <strong><?php echo ($_GET['status']=='success' || $_GET['status']=='deleted') ? 'Success!' : 'Error!'; ?></strong> 
        <?php 
            if($_GET['status']=='success') echo 'Profile updated.'; 
            if($_GET['status']=='deleted') echo 'Photo deleted successfully.'; 
            if($_GET['status']=='error') echo 'Something went wrong.'; 
        ?>
    </div>
<?php endif; ?>

<form action="profile_handler.php" method="POST" enctype="multipart/form-data" class="space-y-8 pb-20">

    <div class="bg-white p-6 rounded-lg shadow-md">
        <h2 class="text-2xl font-bold text-ucf-charcoal mb-4 border-b pb-2">Public Profile</h2>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
                <label class="block text-sm font-medium text-gray-700">First Name</label>
                <input type="text" name="first_name" required value="<?php echo htmlspecialchars($profile['first_name']); ?>" class="input-field mt-1 block w-full border p-2 rounded border-gray-300">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700">Last Name</label>
                <input type="text" name="last_name" required value="<?php echo htmlspecialchars($profile['last_name']); ?>" class="input-field mt-1 block w-full border p-2 rounded border-gray-300">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700">Phone</label>
                <input type="tel" name="phone" value="<?php echo htmlspecialchars($profile['phone']); ?>" class="input-field mt-1 block w-full border p-2 rounded border-gray-300">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700">Profile Picture</label>
                <?php if (!empty($profile['profile_image_path'])): ?>
                    <img src="<?php echo htmlspecialchars($profile['profile_image_path']); ?>" class="h-12 w-12 rounded-full mb-2 object-cover border">
                <?php endif; ?>
                <input type="file" name="profile_image" accept="image/*" class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:bg-green-50 file:text-green-700 hover:file:bg-green-100">
            </div>
            <div class="md:col-span-2">
                <label class="block text-sm font-medium text-gray-700">Address</label>
                <textarea name="address" rows="2" class="input-field mt-1 block w-full border p-2 rounded border-gray-300"><?php echo htmlspecialchars($profile['address']); ?></textarea>
            </div>
        </div>
    </div>

    <div class="bg-white p-6 rounded-lg shadow-md">
        <h2 class="text-2xl font-bold text-ucf-charcoal mb-4 border-b pb-2">Artist Details</h2>
        <div class="space-y-4">
            <div>
                <label class="block text-sm font-medium text-gray-700">Biography</label>
                <textarea name="bio" rows="5" class="input-field mt-1 block w-full border p-2 rounded border-gray-300"><?php echo htmlspecialchars($profile['bio']); ?></textarea>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label class="block text-sm font-medium text-gray-700">Art Specialization</label>
                    <input type="text" name="art_specialization" value="<?php echo htmlspecialchars($profile['art_specialization']); ?>" class="input-field mt-1 block w-full border p-2 rounded border-gray-300">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700">Main Subjects</label>
                    <input type="text" name="subjects" value="<?php echo htmlspecialchars($profile['subjects']); ?>" class="input-field mt-1 block w-full border p-2 rounded border-gray-300">
                </div>
            </div>

            <div class="border-t border-gray-100 pt-4 mt-4">
                <label class="block text-sm font-bold text-gray-800 mb-2">Achievements / Exhibitions</label>
                <textarea name="achievements" rows="3" class="input-field mt-1 block w-full border p-2 rounded border-gray-300 mb-4"><?php echo htmlspecialchars($profile['achievements']); ?></textarea>

                <?php if (!empty($ach_photos)): ?>
                    <label class="block text-xs font-bold text-gray-500 uppercase mb-2">Your Uploaded Photos:</label>
                    <div class="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-6 gap-4 mb-4">
                        <?php foreach($ach_photos as $photo): ?>
                            <div class="relative group h-24 w-full bg-gray-100 rounded border overflow-hidden">
                                <img src="../<?php echo htmlspecialchars($photo['image_path']); ?>" class="w-full h-full object-cover">
                                
                                <button type="submit" name="delete_photo_id" value="<?php echo $photo['id']; ?>" 
                                        class="absolute top-1 right-1 bg-red-600 text-white rounded-full w-6 h-6 flex items-center justify-center opacity-75 hover:opacity-100 transition shadow-sm"
                                        onclick="return confirm('Delete this photo?');"
                                        title="Delete Photo">
                                    <i class="fas fa-times text-xs"></i>
                                </button>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>

                <div class="bg-blue-50 p-4 rounded border border-blue-200">
                    <label class="block text-sm font-medium text-gray-700 mb-1">Add New Photos</label>
                    <input type="file" name="achievement_photos[]" multiple accept="image/*" 
                           class="block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:bg-white file:text-blue-700 hover:file:bg-blue-100"
                           onchange="validateFileSize(this)">
                    <p class="text-xs text-red-500 mt-1 hidden" id="size-error">⚠️ One or more files exceed 100KB!</p>
                </div>
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mt-4">Awards</label>
                <textarea name="awards" rows="3" class="input-field mt-1 block w-full border p-2 rounded border-gray-300"><?php echo htmlspecialchars($profile['awards']); ?></textarea>
            </div>
        </div>
    </div>

    <div class="bg-white p-6 rounded-lg shadow-md">
        <h2 class="text-2xl font-bold text-ucf-charcoal mb-4 border-b pb-2">Shop Settings</h2>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
                <label class="block text-sm font-medium text-gray-700">Shop Name</label>
                <input type="text" name="shop_name" required value="<?php echo htmlspecialchars($profile['shop_name']); ?>" class="input-field mt-1 block w-full border p-2 rounded border-gray-300">
            </div>
            <div>
                <label class="block text-sm font-medium text-gray-700">Shop URL (Slug)</label>
                <input type="text" name="shop_slug" required value="<?php echo htmlspecialchars($profile['shop_slug']); ?>" class="input-field mt-1 block w-full border p-2 rounded border-gray-300">
            </div>
        </div>
    </div>
    
    <div class="flex justify-end">
        <button type="submit" class="bg-ucf-green text-white font-bold py-3 px-8 rounded-lg hover:bg-ucf-green-dark shadow-lg">
            Save Changes
        </button>
    </div>

</form>

<script>
function validateFileSize(input) {
    const errorMsg = document.getElementById('size-error');
    errorMsg.classList.add('hidden');
    if (input.files) {
        for (let i = 0; i < input.files.length; i++) {
            if (input.files[i].size > 102400) {
                errorMsg.classList.remove('hidden');
                alert("File '" + input.files[i].name + "' is too large! Max 100KB.");
                input.value = ""; 
                return;
            }
        }
    }
}
function copyLink() {
    var copyText = document.getElementById("myLink");
    navigator.clipboard.writeText(copyText.innerText);
    alert("Profile link copied!");
}
</script>

<?php 
$conn->close();
include 'footer.php'; 
?>