<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Panel</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link rel="stylesheet" href="css/main/main.css?ver=<?php echo time(); ?>">
    <script src="js/main/main.js?ver=<?php echo time(); ?>" defer></script>
    <script src="https://api.squizee.in/datatable/main.js?ver=<?php echo time(); ?>" defer></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>


    <style>
        #data-table-container {
            margin-top: 20px;
            max-height: calc(100vh - 200px) !important;
            overflow: auto;
            border-radius: 3px;
        }

        .address-column {
            min-width: 250px;
        }

        .action-column {
            max-width: 70px;
        }

        .final-order-status-column {
            min-width: 200px;
        }

        .customer-name-column {
            min-width: 150px;
        }

        /* Style for Action buttons */
        .btn i {
            margin-right: 8px;
        }

        /* Edit Button Style */
        .edit-button {
            color: white;
            background-color: #107b7d;
            border: 1px solid #28a745;
            padding: 8px 16px;
            border-radius: 5px;
            font-weight: bold;
            transition: background-color 0.3s ease;
            cursor: pointer;
        }

        .edit-button:hover {
            background-color: #218838;
            border-color: #218838;
        }

        /* Delete Button Style */
        .delete-button {
            color: white;
            background-color: #bc505b;
            border: 1px solid #dc3545;
            padding: 8px 16px;
            border-radius: 5px;
            font-weight: bold;
            transition: background-color 0.3s ease;
            cursor: pointer;

        }

        .delete-button:hover {
            background-color: #c82333;
            border-color: #c82333;
        }

        /* Modal Styles */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.6);
            overflow: auto;
            backdrop-filter: blur(5px);
            animation: fadeIn 0.3s ease-in-out;
        }

        .modal-content {
            background-color: #fff;
            margin: 5% auto;
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
            width: 90%;
            max-width: 600px;
            position: relative;
            transform: translateY(-50px);
            animation: slideIn 0.3s ease-in-out forwards;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
            }

            to {
                opacity: 1;
            }
        }

        @keyframes slideIn {
            from {
                transform: translateY(-50px);
                opacity: 0;
            }

            to {
                transform: translateY(0);
                opacity: 1;
            }
        }

        .close {
            color: #aaa;
            float: right;
            font-size: 32px;
            font-weight: bold;
            transition: color 0.3s ease;
        }

        .close:hover,
        .close:focus {
            color: #333;
            text-decoration: none;
            cursor: pointer;
        }

        .modal-header {
            border-bottom: 2px solid #eee;
            margin-bottom: 20px;
            padding-bottom: 10px;
        }

        .modal-header h2 {
            margin: 0;
            color: #333;
        }

        .modal-body {
            margin: 10px 0;
        }

        .modal label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #555;
            margin-top: 15px;
        }

        .modal input,
        .modal select {
            width: 100%;
            padding: 12px;
            margin: 5px 0;
            border: 1px solid #ddd;
            border-radius: 8px;
            box-sizing: border-box;
            transition: border-color 0.3s ease;
        }

        .modal input:focus,
        .modal select:focus {
            outline: none;
            border-color: #107b7d;
        }

        .modal-footer {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
        }

        .modal .btn {
            padding: 10px 20px;
            border-radius: 5px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s ease, transform 0.2s ease;
        }

        .modal .btn:hover {
            transform: translateY(-2px);
        }

        .add-user-btn {
            background-color: #107b7d;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            margin-bottom: 20px;
        }

        .add-user-btn:hover {
            background-color: #0d5f61;
        }

        .submit-btn,
        .update-btn {
            background-color: #107b7d;
            color: white;
            border: none;
        }

        .submit-btn:hover,
        .update-btn:hover {
            background-color: #0d5f61;
        }

        .clear-btn {
            background-color: #f4f4f4;
            color: #555;
            border: 1px solid #ddd;
        }

        .clear-btn:hover {
            background-color: #e2e2e2;
        }
    </style>
</head>

<body>

    <div class="left-panel left-panel-show" id="left-panel">
    </div>

    <div class="main-content main-content-normal" id="main-content">
        <div id="content">
            <button class="add-user-btn" onclick="openAddModal()"><i class="fas fa-plus"></i> Add New User</button>
            <div id="data-table-wrapper"></div>
        </div>
    </div>

    <div id="editModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <span class="close" onclick="closeModal()">×</span>
                <h2 id="modalTitle">Edit User</h2>
            </div>
            <form id="editForm">
                <div class="modal-body">
                    <label for="userName">Name:</label>
                    <input type="text" id="userName" name="userName" required>

                    <label for="userPhone">Phone:</label>
                    <input type="text" id="userPhone" name="userPhone" required>

                    <label for="userEmail">Email:</label>
                    <input type="email" id="userEmail" name="userEmail" required>

                    <label for="userPassword">Password:</label>
                    <input type="text" id="userPassword" name="userPassword">

                    <label for="userRole">Role:</label>
                    <select id="userRole" name="userRole" required></select>
                </div>
                <div class="modal-footer">
                    <button type="button" id="clearBtn" class="btn clear-btn" onclick="openAddModal()">Clear</button>
                    <button type="button" id="updateBtn" class="btn update-btn" style="display:none;" onclick="updateUser()">Update</button>
                    <button type="button" id="submitBtn" class="btn submit-btn" onclick="saveUser()">Submit</button>
                </div>
            </form>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <script>
        // Get modal elements
        const modal = document.getElementById('editModal');
        const modalTitle = document.getElementById('modalTitle');
        const userNameInput = document.getElementById('userName');
        const userPhoneInput = document.getElementById('userPhone');
        const userEmailInput = document.getElementById('userEmail');
        const userPasswordInput = document.getElementById('userPassword'); // Added new element reference
        const userRoleSelect = document.getElementById('userRole');
        const submitBtn = document.getElementById('submitBtn');
        const updateBtn = document.getElementById('updateBtn');
        const clearBtn = document.getElementById('clearBtn');
        const editForm = document.getElementById('editForm');

        let currentEmail = null;
        let wasConfirmed = false; // <-- FIX: Declare the variable here

        // Define a comprehensive configuration object.
        const tableConfig = {
            column_config: {
                "Action": {
                    type: 'button',
                    disabled: false,
                    class: 'action-column',
                    buttons: [{
                            label: '<i class="fas fa-edit"></i>',
                            class: 'edit-button btn',
                            action: `openEditModal('{{Email}}');`
                        },
                        {
                            label: '<i class="fas fa-trash"></i>',
                            class: 'delete-button btn',
                            action: `confirmAndDeleteUser('{{Email}}');`
                        }
                    ]
                }
            },
            create_columns: [{
                header: "Action",
                position: 'start'
            }]
        };


        function openAddModal() {
            modalTitle.textContent = "Add User";
            submitBtn.style.display = 'block';
            updateBtn.style.display = 'none';
            editForm.reset();
            userEmailInput.readOnly = false;
            // The password field is required for a new user
            userPasswordInput.required = true;
            currentEmail = null;
            modal.style.display = 'block';
        }

        function openEditModal(email) {
            modalTitle.textContent = "Edit User";
            submitBtn.style.display = 'none';
            updateBtn.style.display = 'block';
            currentEmail = email;
            // The password field is not required for an update
            userPasswordInput.required = false;
            fetchUserDataByEmail(email);
            modal.style.display = 'block';
        }

        async function fetchUserDataByEmail(email) {
            showProcessingMessage('Fetching user data...');
            try {
                const response = await fetch(`../php/fetch_user_by_email.php?email=${email}`);
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                const data = await response.json();

                if (data.error) {
                    showErrorMessage(data.error);
                    modal.style.display = 'none';
                } else {
                    closeSwal();
                    userNameInput.value = data.name;
                    userPhoneInput.value = data.phone;
                    userEmailInput.value = data.email;
                    userEmailInput.readOnly = true;
                    // Resetting the password field for security
                    userPasswordInput.value = data.password; 
                    userRoleSelect.value = data.role;
                }
            } catch (error) {
                console.error('There was a problem with the fetch operation:', error);
                showErrorMessage('Error fetching user data. Please try again.');
                modal.style.display = 'none';
            }
        }

        async function fetchRoles() {
            try {
                const response = await fetch('../php/fetch_roles.php');
                const data = await response.json();
                userRoleSelect.innerHTML = '';
                data.forEach(roleData => {
                    const option = document.createElement('option');
                    option.value = roleData.role;
                    option.textContent = roleData.role;
                    userRoleSelect.appendChild(option);
                });
            } catch (error) {
                console.error('Error fetching roles:', error);
            }
        }

        function closeModal() {
            modal.style.display = "none";
            userEmailInput.disabled = false;
            editForm.reset();
        }

        // --- NEW FUNCTION FOR CONFIRMATION ---
        async function confirmAndDeleteUser(email) {
            const result = await Swal.fire({
                title: 'Are you sure?',
                text: "You won't be able to revert this!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#bc505b',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, delete it!'
            });
            if (result.isConfirmed) {
                deleteUser(email);
            } else {
                showErrorMessage('Deletion cancelled.', true);
            }
        }
        // --- NEW FUNCTIONS FOR CRUD OPERATIONS ---

        // Function to save a new user
        async function saveUser() {
            // Validate form before submitting
            if (!editForm.checkValidity()) {
                editForm.reportValidity();
                return;
            }

            showProcessingMessage('Adding user...');
            const formData = new FormData(editForm);
            try {
                const response = await fetch('../php/save_user.php', {
                    method: 'POST',
                    body: formData
                });
                const result = await response.json();

                if (result.success) {
                    showSuccessMessage('User added successfully!');
                    closeModal();
                    fetchData();
                } else {
                    showErrorMessage(result.message || 'Failed to add user.');
                }
            } catch (error) {
                console.error('Error adding user:', error);
                showErrorMessage('An error occurred. Please try again.');
            }
        }

        async function updateUser() {
            if (!editForm.checkValidity()) {
                editForm.reportValidity();
                return;
            }
        
            showProcessingMessage('Updating user...');
            const formData = new FormData(editForm);
        
            console.log([...formData]); // Debug: log form fields
        
            try {
                const response = await fetch('../php/update_user.php', {
                    method: 'POST',
                    body: formData
                });
        
                const result = await response.json();
                console.log('Update response:', result); // Debug
        
                if (result.success) {
                    showSuccessMessage('User updated successfully!');
                    closeModal();
                    fetchData();
                } else {
                    showErrorMessage(result.message || 'Failed to update user.');
                }
            } catch (error) {
                console.error('Error updating user:', error);
                showErrorMessage('An error occurred. Please try again.');
            }
        }
                
        
        // Function to delete a user
        async function deleteUser(email) {
            showProcessingMessage('Deleting user...');
            const formData = new FormData();
            formData.append('email', email);
            try {
                const response = await fetch('../php/delete_user.php', {
                    method: 'POST',
                    body: formData
                });
                const result = await response.json();

                if (result.success) {
                    showSuccessMessage('User deleted successfully!');
                    fetchData();
                } else {
                    showErrorMessage(result.message || 'Failed to delete user.');
                }
            } catch (error) {
                console.error('Error deleting user:', error);
                showErrorMessage('An error occurred during deletion.');
            }
        }

        // --- EVENT LISTENERS ---

        editForm.addEventListener('submit', function(e) {
            e.preventDefault();
        });


        window.onclick = function(event) {
            if (event.target == modal) {
                closeModal();
            }
        }

        document.addEventListener("DOMContentLoaded", function() {
            fetchRoles();
            fetchData();
        });

        async function fetchData() {
            try {
                const response = await fetch('../php/fetch_users.php');
                const data = await response.json();
                const options = {
                    replace_headers: [
                        ['name', 'User Name'],
                        ['email', 'Email'],
                        ['phone', 'Phone'],
                        ['role', 'Role'],
                        ['password', 'Password'],
                    ],
                    arrange_columns: [
                        'User Name',
                        'Email',
                        'Phone',
                        'Role',
                        'Password'
                    ]
                };
                loadData(data, 'json', options);
            } catch (error) {
                console.error('Error fetching users:', error);
                showErrorMessage('Error loading user data.');
            }
        }
    </script>
</body>

</html>
