
document.addEventListener('DOMContentLoaded', function () {
    const sidebarToggler = document.getElementById('sidebar-toggler');

    if (sidebarToggler) {
        sidebarToggler.addEventListener('click', function () {
            const isCollapsed = document.body.classList.toggle('sidebar-collapsed');
            localStorage.setItem('sidebarCollapsed', isCollapsed);
            sidebarToggler.setAttribute('aria-expanded', !isCollapsed);
        });

        // Set initial aria-expanded state
        const isInitiallyCollapsed = localStorage.getItem('sidebarCollapsed') === 'true';
        sidebarToggler.setAttribute('aria-expanded', !isInitiallyCollapsed);
    }

    // --- The rest of your original main.js --- //

    $(document).ready(function() {
        // Handler for showing the edit person modal
        $('#editPersonModal').on('show.bs.modal', function (event) {
            var button = $(event.relatedTarget); // Button that triggered the modal
            var personId = button.data('person-id'); // Extract info from data-* attributes
            var modal = $(this);
    
            // Clear previous data
            modal.find('form').trigger('reset');
            modal.find('#editPersonId').val('');
            modal.find('#editRoles').empty();
            modal.find('#followUpSummaryContainer').empty(); // Clear summary container
            // Clear file paths
            modal.find('#editCompanyLogoPath, #editPersonPhotoPath, #editGainsSheetPath, #editTopWantedPath, #editTopOwnedPath').text('');
    
            if (personId) {
                // AJAX request to get person details
                $.ajax({
                    url: '_get_person_details.php',
                    type: 'GET',
                    data: { id: personId },
                    dataType: 'json',
                    success: function(response) {
                        if (response.error) {
                            alert('Error fetching person details: ' + response.error);
                            return;
                        }
    
                        var person = response.person;
                        var all_functions = response.all_functions;
                        var person_functions = response.person_functions;
                        var followUpSummary = response.follow_up_summary;
    
                        if (!person) {
                             alert('Could not find person data.');
                             return;
                        }
    
                        // Populate the Follow-up Summary
                        var summaryContainer = modal.find('#followUpSummaryContainer');
                        if (followUpSummary) {
                            let summaryHtml = '<h5>Follow-up Process Summary</h5>';
                            summaryHtml += '<dl class="row">';
                            
                            if (followUpSummary.last_call_outcome) {
                                summaryHtml += `<dt class="col-sm-4">Last Call Outcome</dt><dd class="col-sm-8">${followUpSummary.last_call_outcome.replace(/_/g, ' ')}</dd>`;
                            }
                            if (followUpSummary.last_call_date) {
                                summaryHtml += `<dt class="col-sm-4">Last Call Date</dt><dd class="col-sm-8">${new Date(followUpSummary.last_call_date).toLocaleString()}</dd>`;
                            }
                            if (followUpSummary.next_contact_date) {
                                summaryHtml += `<dt class="col-sm-4">Next Contact Date</dt><dd class="col-sm-8">${new Date(followUpSummary.next_contact_date).toLocaleString()}</dd>`;
                            }
                            if (followUpSummary.final_outcome) {
                                summaryHtml += `<dt class="col-sm-4">Final Status</dt><dd class="col-sm-8">${followUpSummary.final_outcome} (${followUpSummary.reason || 'N/A'})</dd>`;
                            }
    
                            summaryHtml += '</dl>';
                            summaryContainer.html(summaryHtml);
                        } else {
                            summaryContainer.html('<p class="text-muted">No Follow-up process data found for this person.</p>');
                        }
    
                        // Populate the form fields
                        modal.find('#editPersonId').val(person.id);
                        modal.find('#editFirstName').val(person.first_name);
                        modal.find('#editLastName').val(person.last_name);
                        modal.find('#editPhone').val(person.phone);
                        modal.find('#editEmail').val(person.email);
                        modal.find('#editRole').val(person.role);
                        modal.find('#editBniGroup').val(person.bni_group_id);
                        modal.find('#editCompanyName').val(person.company_name);
                        modal.find('#editNip').val(person.nip);
                        modal.find('#editIndustry').val(person.industry);
                        modal.find('#editCompanySize').val(person.company_size_revenue);
                        modal.find('#editBusinessDescription').val(person.business_description);
                        
                        // Populate file paths
                        if (person.company_logo_path) {
                            modal.find('#editCompanyLogoPath').text('Current file: ' + person.company_logo_path.split('/').pop());
                        }
                        if (person.person_photo_path) {
                            modal.find('#editPersonPhotoPath').text('Current file: ' + person.person_photo_path.split('/').pop());
                        }
                        if (person.gains_sheet_path) {
                            modal.find('#editGainsSheetPath').text('Current file: ' + person.gains_sheet_path.split('/').pop());
                        }
                        if (person.top_wanted_contacts_path) {
                            modal.find('#editTopWantedPath').text('Current file: ' + person.top_wanted_contacts_path.split('/').pop());
                        }
                        if (person.top_owned_contacts_path) {
                            modal.find('#editTopOwnedPath').text('Current file: ' + person.top_owned_contacts_path.split('/').pop());
                        }
    
                        // Populate functions/roles dropdown and select assigned ones
                        var rolesSelect = modal.find('#editRoles');
                        rolesSelect.empty(); // Clear existing options
    
                        if (all_functions && all_functions.length > 0) {
                            const groupedFunctions = all_functions.reduce((acc, func) => {
                                const groupName = func.group_name || 'General';
                                if (!acc[groupName]) {
                                    acc[groupName] = [];
                                }
                                acc[groupName].push(func);
                                return acc;
                            }, {});
    
                            for (const groupName in groupedFunctions) {
                                const optgroup = $('<optgroup>').attr('label', groupName);
                                groupedFunctions[groupName].forEach(function(func) {
                                    var option = $('<option></option>').val(func.id).text(func.name);
                                    if (person_functions && person_functions.includes(String(func.id))) {
                                        option.prop('selected', true);
                                    }
                                    optgroup.append(option);
                                });
                                rolesSelect.append(optgroup);
                            }
                        }
    
                        // Trigger change to show/hide conditional fields
                        modal.find('#editRole').trigger('change');
                        
                        // Also set up the delete button
                        $('#deleteUserBtn').data('person-id', person.id);
                        $('#personNameToDelete').text(person.firstName + ' ' + person.lastName);
    
                    },
                    error: function(xhr, status, error) {
                        alert('An error occurred while fetching person data. Please try again.');
                        console.error("AJAX Error:", status, error);
                    }
                });
            }
        });
        
        // Show/hide group selection based on role for both Edit and Create modals
        $(document).on('change', '#editRole, #createRole', function() {
            const role = $(this).val();
            const isMember = role === 'member';
            
            // Find the correct context (modal) for the elements
            const modal = $(this).closest('.modal-content');
            
            modal.find('.member-only-fields').toggle(isMember);
            modal.find('#edit-group-selection-div, #create-group-selection-div').toggle(isMember);
        });
    
        // Handle Delete Person confirmation
        $('#confirmDeleteBtn').on('click', function() {
            var personId = $('#deleteUserBtn').data('person-id');
            if (personId) {
                 // Use a form submission to perform the delete
                var form = $('<form></form>');
                form.attr("method", "post");
                form.attr("action", "_delete_person.php");
    
                var field = $('<input></input>');
                field.attr("type", "hidden");
                field.attr("name", "id");
                field.attr("value", personId);
                form.append(field);
    
                $(document.body).append(form);
                form.submit();
            }
        });
    
        // Set initial state for create form
        $('#createPersonModal').on('show.bs.modal', function () {
            $('#createRole').trigger('change');
        });
    
        function handleFormSubmit(form, errorContainer, successCallback) {
            event.preventDefault();
            const formData = new FormData(form);
            const errorDiv = $(errorContainer).hide();
    
            fetch(form.action, {
                method: 'POST',
                body: formData
            })
            .then(response => {
                // Clone the response so we can read it twice (once as JSON, once as text if needed)
                const responseClone = response.clone();
                return response.json()
                    .then(data => ({ status: response.status, ok: response.ok, body: data }))
                    .catch(() => responseClone.text().then(text => ({ status: response.status, ok: response.ok, body: text, isText: true })));
            })
            .then(res => {
                const { status, ok, body, isText } = res;
    
                if (!ok) {
                    if (isText) {
                        throw new Error(`Server Error: ${status}. Response: ${body}`);
                    }
                    throw new Error(body.error?.message || `An unknown server error occurred (Status: ${status})`);
                }
                
                if (isText) {
                     console.error("Received non-JSON response:", body);
                     throw new Error("The server sent an invalid response that could not be parsed. See console for details.");
                }
    
                if (body.success) {
                    if (successCallback) {
                        successCallback(body);
                    } else {
                        // Default success behavior: close modal and reload
                        $(form).closest('.modal').modal('hide');
                        window.location.reload();
                    }
                } else {
                    throw new Error(body.error?.message || 'An operation error occurred.');
                }
            })
            .catch(error => {
                errorDiv.text(error.message).show();
            });
        }
    
        $('#createPersonForm').on('submit', function(event) {
            handleFormSubmit(this, '#createPersonError');
        });
    
        $('#editPersonForm').on('submit', function(event) {
            handleFormSubmit(this, '#editPersonError', function(data) {
                // close modal and reload page
                $('#editPersonModal').modal('hide');
                window.location.reload();
            });
        });
    });
});
