<?php
include 'include/header.php';

// Verify session
if (!isset($_SESSION['vendor_id'])) {
    header("Location: login.php");
    exit();
}

require_once '../config/conn.php';

$vendor_id = $_SESSION['vendor_id'];

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_FILES['profile_picture']) && $_FILES['profile_picture']['error'] == UPLOAD_ERR_OK) {
        // File upload configuration
        $target_dir = "../uploads/";
        $file_extension = pathinfo($_FILES["profile_picture"]["name"], PATHINFO_EXTENSION);
        $new_filename = "vendor_" . $vendor_id . "_" . time() . "." . $file_extension;
        $target_file = $target_dir . $new_filename;
        
        // Check if image file is an actual image
        $check = getimagesize($_FILES["profile_picture"]["tmp_name"]);
        if ($check === false) {
            $_SESSION['error'] = "File is not an image.";
        } else {
            // Check file size (max 2MB)
            if ($_FILES["profile_picture"]["size"] > 2000000) {
                $_SESSION['error'] = "Sorry, your file is too large (max 2MB).";
            } else {
                // Allow certain file formats
                $allowed_extensions = ["jpg", "jpeg", "png", "gif"];
                if (!in_array(strtolower($file_extension), $allowed_extensions)) {
                    $_SESSION['error'] = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
                } else {
                    // Upload file
                    if (move_uploaded_file($_FILES["profile_picture"]["tmp_name"], $target_file)) {
                        // Update database
                        $relative_path = "../uploads/" . $new_filename;
                        $update_stmt = $conn->prepare("UPDATE vendors SET profile_picture = ? WHERE id = ?");
                        $update_stmt->bind_param("si", $relative_path, $vendor_id);
                        
                        if ($update_stmt->execute()) {
                            $_SESSION['success'] = "Profile picture updated successfully";
                            // Delete old file if it exists and isn't the default
                            if (!empty($vendor['profile_picture']) && $vendor['profile_picture'] !== 'assets/images/default-avatar.png') {
                                @unlink("../" . $vendor['profile_picture']);
                            }
                            header("Location: profile.php");
                            exit();
                        } else {
                            $_SESSION['error'] = "Error updating profile picture";
                            @unlink($target_file); // Remove uploaded file if DB update failed
                        }
                    } else {
                        $_SESSION['error'] = "Sorry, there was an error uploading your file.";
                    }
                }
            }
        }
    } else {
        $_SESSION['error'] = "Please select an image file to upload.";
    }
}

// Fetch current profile picture
$stmt = $conn->prepare("SELECT profile_picture FROM vendors WHERE id = ?");
$stmt->bind_param("i", $vendor_id);
$stmt->execute();
$result = $stmt->get_result();
$vendor = $result->fetch_assoc();
?>

<main class="main-content flex-1 pb-8">
    <div class="max-w-md mx-auto py-6 sm:px-6 lg:px-8">
        <!-- Success/Error Messages -->
        <?php if (isset($_SESSION['success'])): ?>
        <div class="mb-4 bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative" role="alert">
            <span class="block sm:inline"><?= $_SESSION['success'] ?></span>
            <span class="absolute top-0 bottom-0 right-0 px-4 py-3" onclick="this.parentElement.style.display='none'">
                <svg class="fill-current h-6 w-6 text-green-500" role="button" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><title>Close</title><path d="M14.348 14.849a1.2 1.2 0 0 1-1.697 0L10 11.819l-2.651 3.029a1.2 1.2 0 1 1-1.697-1.697l2.758-3.15-2.759-3.152a1.2 1.2 0 1 1 1.697-1.697L10 8.183l2.651-3.031a1.2 1.2 0 1 1 1.697 1.697l-2.758 3.152 2.758 3.15a1.2 1.2 0 0 1 0 1.698z"/></svg>
            </span>
        </div>
        <?php unset($_SESSION['success']); ?>
        <?php endif; ?>
        
        <?php if (isset($_SESSION['error'])): ?>
        <div class="mb-4 bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative" role="alert">
            <span class="block sm:inline"><?= $_SESSION['error'] ?></span>
            <span class="absolute top-0 bottom-0 right-0 px-4 py-3" onclick="this.parentElement.style.display='none'">
                <svg class="fill-current h-6 w-6 text-red-500" role="button" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><title>Close</title><path d="M14.348 14.849a1.2 1.2 0 0 1-1.697 0L10 11.819l-2.651 3.029a1.2 1.2 0 1 1-1.697-1.697l2.758-3.15-2.759-3.152a1.2 1.2 0 1 1 1.697-1.697L10 8.183l2.651-3.031a1.2 1.2 0 1 1 1.697 1.697l-2.758 3.152 2.758 3.15a1.2 1.2 0 0 1 0 1.698z"/></svg>
            </span>
        </div>
        <?php unset($_SESSION['error']); ?>
        <?php endif; ?>

        <div class="bg-white dark:bg-gray-800 shadow overflow-hidden sm:rounded-lg">
            <div class="px-4 py-5 sm:px-6 border-b border-gray-200 dark:border-gray-700">
                <h3 class="text-lg leading-6 font-medium text-gray-900 dark:text-white">Update Profile Picture</h3>
                <p class="mt-1 max-w-2xl text-sm text-gray-500 dark:text-gray-400">Upload a new profile photo.</p>
            </div>
            <div class="px-4 py-5 sm:p-6">
                <form method="POST" action="" enctype="multipart/form-data">
                    <div class="space-y-6">
                        <div class="flex flex-col items-center">
                            <!-- Current Profile Picture -->
                            <div class="mb-4 relative">
                                <img src="<?= !empty($vendor['profile_picture']) ? '../' . htmlspecialchars($vendor['profile_picture']) : '../assets/images/default-avatar.png' ?>" 
                                     alt="Current Profile Picture" 
                                     class="w-32 h-32 rounded-full object-cover border-4 border-primary-100 dark:border-primary-800">
                            </div>
                            
                            <!-- File Upload -->
                            <div class="w-full">
                                <label for="profile_picture" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Choose new photo</label>
                                <input type="file" name="profile_picture" id="profile_picture" accept="image/*" required class="mt-1 block w-full text-sm text-gray-500 dark:text-gray-400
                                  file:mr-4 file:py-2 file:px-4
                                  file:rounded-md file:border-0
                                  file:text-sm file:font-semibold
                                  file:bg-primary-50 file:text-primary-700 dark:file:bg-primary-800 dark:file:text-primary-200
                                  hover:file:bg-primary-100 dark:hover:file:bg-primary-700">
                                <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">JPG, PNG or GIF (Max 2MB)</p>
                            </div>
                        </div>

                        <div class="flex items-center justify-end gap-x-4">
                            <a href="profile.php" class="bg-gray-200 dark:bg-gray-600 text-gray-800 dark:text-white py-2 px-4 rounded-md text-sm font-medium hover:bg-gray-300 dark:hover:bg-gray-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500">
                                Cancel
                            </a>
                            <button type="submit" class="bg-primary-600 border border-transparent rounded-md shadow-sm py-2 px-4 inline-flex justify-center text-sm font-medium text-white hover:bg-primary-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary-500">
                                Upload Photo
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</main>

<?php include 'include/footer.php'; ?>