<x-app-layout>
    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Subscription Plans Management</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.0.0/dist/tailwind.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js"></script>
    <style>
        .card {
            border: 1px solid #ddd;
            border-radius: 0.5rem;
            padding: 1rem;
            margin: 1rem;
        }
        .card img {
            max-width: 100%;
            border-radius: 0.5rem;
        }
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0,0,0,0.5);
        }
        .modal-content {
            background-color: #fff;
            margin: 15% auto;
            padding: 20px;
            border-radius: 5px;
            width: 80%;
        }
        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
        }
        .close:hover,
        .close:focus {
            color: black;
            text-decoration: none;
            cursor: pointer;
        }
        #imagePreview {
            display: none;
            margin-top: 1rem;
            width: 100px;
            height: 100px;
            object-fit: cover;
        }
        #loader {
            display: none;
            border: 4px solid rgba(0, 0, 0, 0.1);
            border-radius: 50%;
            border-top: 4px solid #3498db;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body class="bg-gray-100">

    <div class="container mx-auto p-4">
        <h1 class="text-2xl font-bold mb-4">Subscription Plans Management</h1>

        <!-- Form for Creating/Updating Subscription Plans -->
        <div class="card">
            <h2 class="text-xl font-semibold mb-2">Create/Update Subscription Plan</h2>
            <form id="subscriptionForm" enctype="multipart/form-data">
                <input type="hidden" id="planId" name="id">
                
                <div class="mb-4">
                    <label class="block text-gray-700">Plan Name</label>
                    <select id="name" name="name" class="form-select mt-1 block w-full" required>
                        <option value="" disabled selected>Select Plan Name</option>
                        <option value="Basic">Basic</option>
                        <option value="Premium">Premium</option>
                        <option value="Media">Media</option>
                    </select>
                </div>

                <div class="mb-4">
                    <label class="block text-gray-700">Description</label>
                    <textarea id="description" name="description" class="form-textarea mt-1 block w-full" required></textarea>
                </div>

                <div class="mb-4">
                    <label class="block text-gray-700">Price</label>
                    <input type="number" id="price" name="price" class="form-input mt-1 block w-full" step="0.01" required>
                </div>

                <div class="mb-4">
                    <label class="block text-gray-700">User Type</label>
                    <select id="user_type" name="user_type" class="form-select mt-1 block w-full" required>
                        <option value="" disabled selected>Select User Type</option>
                        <option value="user">User</option>
                        <option value="vendor">Vendor</option>
                        <option value="driver">Driver</option>
                    </select>
                </div>

                <div class="mb-4">
                    <label class="block text-gray-700">Image (JPG/PNG)</label>
                    <input type="file" id="image" name="image" class="form-input mt-1 block w-full" accept="image/jpeg, image/png" onchange="previewImage(event)">
                    <img id="imagePreview" src="" alt="Image Preview">
                    <div id="loader"></div>
                </div>

                <button type="submit" class="bg-blue-500 text-white px-4 py-2 rounded">Submit</button>
            </form>
        </div>

        <!-- Display Subscription Plans -->
        <div class="card">
            <h2 class="text-xl font-semibold mb-2">Subscription Plans</h2>
            <div id="plansList"></div>
        </div>
    </div>

    <!-- Modal for Viewing Images -->
    <div id="imageModal" class="modal">
        <div class="modal-content">
            <span class="close">&times;</span>
            <img id="modalImage" src="" alt="Plan Image" class="w-full">
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', fetchPlans);

        const form = document.getElementById('subscriptionForm');
        const plansList = document.getElementById('plansList');
        const modal = document.getElementById('imageModal');
        const modalImage = document.getElementById('modalImage');
        const closeModal = document.querySelector('.modal .close');
        const imagePreview = document.getElementById('imagePreview');
        const loader = document.getElementById('loader');

        function fetchPlans() {
            axios.get('https://drycleaneo.com/update/subscription_api.php?action=read')
                .then(response => {
                    const plans = response.data;
                    plansList.innerHTML = `<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 tracking-wider">Name</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Description</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Price</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">User Type</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Image</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            ${plans.map(plan => `
                                <tr>
                                    <td class="px-6 py-4 whitespace-nowrap">${plan.name}</td>
                                    <td class="px-6 py-4 whitespace-nowrap">${plan.description}</td>
                                    <td class="px-6 py-4 whitespace-nowrap">$${plan.price}</td>
                                    <td class="px-6 py-4 whitespace-nowrap">${plan.user_type}</td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        ${plan.image ? `<button class="text-blue-500" onclick="showImage('${plan.image}')">View</button>` : 'No Image'}
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <button class="bg-red-500 text-white px-2 py-1 rounded" onclick="deletePlan(${plan.id})">Delete</button>
                                        <button class="bg-yellow-500 text-white px-2 py-1 rounded" onclick="editPlan(${plan.id}, '${plan.name}', '${plan.description}', ${plan.price}, '${plan.user_type}', '${plan.image}')">Edit</button>
                                    </td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>`;
                })
                .catch(error => console.error('Error fetching plans:', error));
        }

        function showImage(imageUrl) {
            modalImage.src = imageUrl;
            modal.style.display = 'block';
        }

        function closeModalHandler() {
            modal.style.display = 'none';
        }

        closeModal.addEventListener('click', closeModalHandler);
        window.addEventListener('click', (event) => {
            if (event.target == modal) {
                closeModalHandler();
            }
        });

        form.addEventListener('submit', (event) => {
            event.preventDefault();
            const formData = new FormData(form);
            const planId = document.getElementById('planId').value;
            loader.style.display = 'block';

            axios.post('https://drycleaneo.com/update/subscription_api.php?action=create', formData)
                .then(response => {
                    loader.style.display = 'none';
                    if (response.data.success) {
                        fetchPlans();
                        form.reset();
                        document.getElementById('planId').value = '';
                        imagePreview.style.display = 'none';
                        swal("Success", "Plan has been updated!", "success");
                    } else {
                        swal("Error", response.data.message, "error");
                    }
                })
                .catch(error => {
                    loader.style.display = 'none';
                    console.error('Error submitting form:', error);
                    swal("Error", "An error occurred. Please try again.", "error");
                });
        });

        function editPlan(id, name, description, price, user_type, image) {
            document.getElementById('planId').value = id;
            document.getElementById('name').value = name;
            document.getElementById('description').value = description;
            document.getElementById('price').value = price;
            document.getElementById('user_type').value = user_type;
            if (image) {
                imagePreview.src = image;
                imagePreview.style.display = 'block';
            }
        }

        function deletePlan(id) {
            swal({
                title: "Are you sure?",
                text: "Once deleted, you will not be able to recover this plan!",
                icon: "warning",
                buttons: true,
                dangerMode: true,
            }).then((willDelete) => {
                if (willDelete) {
                    axios.post('https://drycleaneo.com/update/subscription_api.php?action=delete', { action: 'delete', id: id })
                        .then(response => {
                            if (response.data.success) {
                                fetchPlans();
                                swal("Deleted!", "The plan has been deleted.", "success");
                            } else {
                                swal("Error", response.data.message, "error");
                            }
                        })
                        .catch(error => {
                            console.error('Error deleting plan:', error);
                            swal("Error", "An error occurred. Please try again.", "error");
                        });
                }
            });
        }

        function previewImage(event) {
            const file = event.target.files[0];
            if (file && file.type.startsWith('image/')) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    imagePreview.src = e.target.result;
                    imagePreview.style.display = 'block';
                };
                reader.readAsDataURL(file);
            } else {
                imagePreview.style.display = 'none';
            }
        }
    </script>
</body>
</html>
</x-app-layout>
