
(function() {
    'use strict';
    
    // Configuration from Blade
    const config = window.stationDetailsConfig || {};
    const STATION_ID = config.stationId;
    const CSRF_TOKEN = config.csrfToken;
    
    // API endpoints
    const API = {
        employees: (id) => `/employees/${id}`,
        schedules: (id) => `/payments/schedules/${id}`,
        providers: '/api/internet-providers',
        provider: (id) => `/api/internet-providers/${id}`,
        vendors: '/api/vendors',
        vendor: (id) => `/api/vendors/${id}`,
        assignProvider: `/stations/${STATION_ID}/assign-provider`,
        assignVendor: `/stations/${STATION_ID}/assign-vendor`,
        providerAssignment: (providerId) => `/stations/${STATION_ID}/provider-assignment/${providerId}`,
        vendorAssignment: (vendorId) => `/stations/${STATION_ID}/vendor-assignment/${vendorId}`,
        updateProvider: (providerId) => `/stations/${STATION_ID}/update-provider-assignment/${providerId}`,
        updateVendor: (vendorId) => `/stations/${STATION_ID}/update-vendor-assignment/${vendorId}`,
        removeProvider: (providerId) => `/stations/${STATION_ID}/remove-provider/${providerId}`,
        removeVendor: (vendorId) => `/stations/${STATION_ID}/remove-vendor/${vendorId}`
    };
    
    // ========== HELPER FUNCTIONS ==========
    function showLoading(message = 'Please wait...') {
        Swal.fire({
            title: 'Loading...',
            text: message,
            allowOutsideClick: false,
            didOpen: () => Swal.showLoading()
        });
    }
    
    function showSuccess(message, reload = true) {
        Swal.fire({
            title: 'Success!',
            text: message,
            icon: 'success',
            timer: reload ? 2000 : undefined,
            showConfirmButton: !reload
        }).then(() => {
            if (reload) location.reload();
        });
    }
    
    function showError(message) {
        Swal.fire({
            title: 'Error!',
            text: message,
            icon: 'error',
            confirmButtonText: 'OK'
        });
    }
    
    function getHeaders() {
        return {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': CSRF_TOKEN,
            'Accept': 'application/json',
            'X-Requested-With': 'XMLHttpRequest'
        };
    }
    
    // ========== EMPLOYEE FUNCTIONS ==========
    function viewEmployee(employeeId) {
        const modal = new bootstrap.Modal(document.getElementById('employeeModal'));
        const modalBody = document.getElementById('employeeModalBody');
        
        modalBody.innerHTML = '<div class="text-center"><div class="spinner-border" role="status"></div></div>';
        modal.show();
        
        fetch(API.employees(employeeId), { headers: getHeaders() })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const emp = data.data;
                    modalBody.innerHTML = `
                        <div class="row">
                            <div class="col-md-6">
                                <h6>Personal Information</h6>
                                <table class="table table-sm">
                                    <tr><th>Full Name:</th><td>${emp.first_name || ''} ${emp.last_name || ''}</td></tr>
                                    <tr><th>ID Number:</th><td>${emp.id_number || 'N/A'}</td></tr>
                                    <tr><th>Position:</th><td>${emp.position || 'N/A'}</td></tr>
                                    <tr><th>Department:</th><td>${emp.department || 'N/A'}</td></tr>
                                    <tr><th>Hire Date:</th><td>${emp.hire_date || 'N/A'}</td></tr>
                                </table>
                            </div>
                            <div class="col-md-6">
                                <h6>Contact Information</h6>
                                <table class="table table-sm">
                                    <tr><th>Phone:</th><td>${emp.phone || 'N/A'}</td></tr>
                                    <tr><th>Email:</th><td>${emp.email || 'N/A'}</td></tr>
                                    <tr><th>Emergency Contact:</th><td>${emp.emergency_contact || 'N/A'}</td></tr>
                                    <tr><th>Salary:</th><td>${emp.salary ? 'KES ' + parseFloat(emp.salary).toLocaleString() : 'N/A'}</td></tr>
                                    <tr><th>Status:</th><td><span class="badge bg-${emp.status == 'active' ? 'success' : 'secondary'}">${emp.status || 'Active'}</span></td></tr>
                                </table>
                            </div>
                        </div>
                        ${emp.notes ? `<div class="row mt-3"><div class="col-12"><h6>Notes</h6><p>${emp.notes}</p></div></div>` : ''}
                    `;
                } else {
                    modalBody.innerHTML = `<div class="alert alert-danger">${data.message || 'Error loading employee details'}</div>`;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                modalBody.innerHTML = '<div class="alert alert-danger">Error loading employee details</div>';
            });
    }
    
    // ========== SCHEDULE FUNCTIONS ==========
    function viewSchedule(scheduleId) {
        const modal = new bootstrap.Modal(document.getElementById('scheduleModal'));
        const modalBody = document.getElementById('scheduleModalBody');
        
        modalBody.innerHTML = '<div class="text-center"><div class="spinner-border" role="status"></div></div>';
        modal.show();
        
        fetch(API.schedules(scheduleId), { headers: getHeaders() })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const schedule = data.data;
                    modalBody.innerHTML = `
                        <div class="row">
                            <div class="col-md-6">
                                <h6>Schedule Information</h6>
                                <table class="table table-sm">
                                    <tr><th>Payment Type:</th><td>${schedule.payment_type || 'N/A'}</td></tr>
                                    <tr><th>Amount:</th><td>KES ${parseFloat(schedule.scheduled_amount || 0).toLocaleString()}</td></tr>
                                    <tr><th>Scheduled Date:</th><td>${schedule.scheduled_date || 'N/A'}</td></tr>
                                    <tr><th>Frequency:</th><td>${schedule.frequency || 'N/A'}</td></tr>
                                </table>
                            </div>
                            <div class="col-md-6">
                                <h6>Settings</h6>
                                <table class="table table-sm">
                                    <tr><th>Recurring:</th><td>${schedule.is_recurring ? 'Yes' : 'No'}</td></tr>
                                    <tr><th>Auto Pay:</th><td>${schedule.auto_pay ? 'Enabled' : 'Disabled'}</td></tr>
                                    <tr><th>Created:</th><td>${schedule.created_at || 'N/A'}</td></tr>
                                    <tr><th>Last Updated:</th><td>${schedule.updated_at || 'N/A'}</td></tr>
                                </table>
                            </div>
                        </div>
                        ${schedule.description ? `<div class="row mt-3"><div class="col-12"><h6>Description</h6><p>${schedule.description}</p></div></div>` : ''}
                    `;
                } else {
                    modalBody.innerHTML = `<div class="alert alert-danger">${data.message || 'Error loading schedule details'}</div>`;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                modalBody.innerHTML = '<div class="alert alert-danger">Error loading schedule details</div>';
            });
    }
    
    // ========== PROVIDER FUNCTIONS ==========
    function assignProvider() {
        Swal.fire({
            title: 'Assign Internet Service Provider',
            html: `
                <form id="assignProviderForm" class="text-start">
                    <div class="mb-3">
                        <label class="form-label fw-bold">Select Provider <span class="text-danger">*</span></label>
                        <select class="form-select" id="provider_id" required>
                            <option value="">-- Choose provider --</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold">Contract Number</label>
                        <input type="text" class="form-control" id="contract_number" placeholder="e.g., INV-2024-001">
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold">Start Date</label>
                            <input type="date" class="form-control" id="start_date">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold">End Date</label>
                            <input type="date" class="form-control" id="end_date">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold">Status</label>
                        <select class="form-select" id="status">
                            <option value="active">Active</option>
                            <option value="inactive">Inactive</option>
                        </select>
                    </div>
                </form>
            `,
            width: '600px',
            showCancelButton: true,
            confirmButtonText: 'Assign Provider',
            cancelButtonText: 'Cancel',
            didOpen: () => {
                const select = document.getElementById('provider_id');
                select.innerHTML = '<option value="">-- Loading providers... --</option>';
                select.disabled = true;
                
                fetch(API.providers, { headers: getHeaders() })
                    .then(response => response.json())
                    .then(data => {
                        select.disabled = false;
                        select.innerHTML = '<option value="">-- Choose provider --</option>';
                        
                        const providers = data.data || data;
                        if (Array.isArray(providers) && providers.length > 0) {
                            providers.forEach(provider => {
                                const option = document.createElement('option');
                                option.value = provider.internet_provider_id || provider.id;
                                option.textContent = `${provider.name} ${provider.code ? '(' + provider.code + ')' : ''}`;
                                select.appendChild(option);
                            });
                        } else {
                            select.innerHTML = '<option value="">-- No providers available --</option>';
                            Swal.showValidationMessage('No providers available. Please add providers first.');
                        }
                    })
                    .catch(error => {
                        console.error('Error loading providers:', error);
                        select.disabled = false;
                        select.innerHTML = '<option value="">-- Error loading providers --</option>';
                        Swal.showValidationMessage('Error loading providers. Please refresh the page.');
                    });
            },
            preConfirm: () => {
                const providerId = document.getElementById('provider_id').value;
                if (!providerId) {
                    Swal.showValidationMessage('Please select a provider');
                    return false;
                }
                return {
                    provider_id: providerId,
                    contract_number: document.getElementById('contract_number').value,
                    start_date: document.getElementById('start_date').value,
                    end_date: document.getElementById('end_date').value,
                    status: document.getElementById('status').value
                };
            }
        }).then((result) => {
            if (result.isConfirmed) {
                showLoading('Assigning provider...');
                
                fetch(API.assignProvider, {
                    method: 'POST',
                    headers: getHeaders(),
                    body: JSON.stringify(result.value)
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showSuccess('Provider assigned successfully');
                    } else {
                        showError(data.message || 'Failed to assign provider');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showError('An error occurred while assigning the provider');
                });
            }
        });
    }
    
    function viewProvider(providerId) {
        fetch(API.provider(providerId), { headers: getHeaders() })
            .then(response => response.json())
            .then(data => {
                const provider = data.data || data;
                Swal.fire({
                    title: 'Internet Service Provider Details',
                    html: `
                        <div class="text-start">
                            <div class="mb-3">
                                <strong class="text-primary">Provider Name:</strong><br>
                                <span>${provider.name}</span>
                            </div>
                            <div class="mb-3">
                                <strong class="text-primary">Code:</strong><br>
                                <span>${provider.code || 'N/A'}</span>
                            </div>
                            <div class="mb-3">
                                <strong class="text-primary">Contact Person:</strong><br>
                                <span>${provider.contact_person || 'N/A'}</span>
                            </div>
                            <div class="mb-3">
                                <strong class="text-primary">Contact Phone:</strong><br>
                                <span>${provider.contact_phone || 'N/A'}</span>
                            </div>
                            <div class="mb-3">
                                <strong class="text-primary">Contact Email:</strong><br>
                                <span>${provider.contact_email || 'N/A'}</span>
                            </div>
                            <div class="mb-3">
                                <strong class="text-primary">Website:</strong><br>
                                <span>${provider.website ? `<a href="${provider.website}" target="_blank">${provider.website}</a>` : 'N/A'}</span>
                            </div>
                            <div class="mb-3">
                                <strong class="text-primary">Status:</strong><br>
                                <span class="badge bg-${provider.status == 'active' ? 'success' : 'danger'}">${provider.status || 'Active'}</span>
                            </div>
                        </div>
                    `,
                    width: '600px'
                });
            })
            .catch(error => {
                console.error('Error:', error);
                showError('Failed to load provider details');
            });
    }
    
    function editProviderAssignment(stationId, providerId) {
        fetch(API.providerAssignment(providerId), { headers: getHeaders() })
            .then(response => response.json())
            .then(data => {
                const assignment = data.data;
                Swal.fire({
                    title: 'Edit Provider Assignment',
                    html: `
                        <form id="editProviderForm" class="text-start">
                            <div class="mb-3">
                                <label class="form-label fw-bold">Contract Number</label>
                                <input type="text" class="form-control" id="contract_number" value="${assignment.contract_number || ''}">
                            </div>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">Start Date</label>
                                    <input type="date" class="form-control" id="start_date" value="${assignment.start_date || ''}">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label fw-bold">End Date</label>
                                    <input type="date" class="form-control" id="end_date" value="${assignment.end_date || ''}">
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label fw-bold">Status</label>
                                <select class="form-select" id="status">
                                    <option value="active" ${assignment.status == 'active' ? 'selected' : ''}>Active</option>
                                    <option value="inactive" ${assignment.status == 'inactive' ? 'selected' : ''}>Inactive</option>
                                </select>
                            </div>
                        </form>
                    `,
                    showCancelButton: true,
                    confirmButtonText: 'Update',
                    preConfirm: () => ({
                        contract_number: document.getElementById('contract_number').value,
                        start_date: document.getElementById('start_date').value,
                        end_date: document.getElementById('end_date').value,
                        status: document.getElementById('status').value
                    })
                }).then((result) => {
                    if (result.isConfirmed) {
                        showLoading('Updating assignment...');
                        
                        fetch(API.updateProvider(providerId), {
                            method: 'PUT',
                            headers: getHeaders(),
                            body: JSON.stringify(result.value)
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                showSuccess('Provider assignment updated successfully');
                            } else {
                                showError(data.message);
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            showError('Failed to update assignment');
                        });
                    }
                });
            });
    }
    
    function removeProvider(stationId, providerId) {
        Swal.fire({
            title: 'Remove Provider?',
            text: "This will remove the service provider assignment from this station.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Yes, remove it!'
        }).then((result) => {
            if (result.isConfirmed) {
                showLoading('Removing provider...');
                
                fetch(API.removeProvider(providerId), {
                    method: 'DELETE',
                    headers: getHeaders()
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showSuccess('Provider has been removed');
                    } else {
                        showError(data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showError('Failed to remove provider');
                });
            }
        });
    }
    
    // ========== VENDOR FUNCTIONS ==========
    function assignVendor() {
        Swal.fire({
            title: 'Assign Vendor',
            html: `
                <form id="assignVendorForm" class="text-start">
                    <div class="mb-3">
                        <label class="form-label fw-bold">Select Vendor <span class="text-danger">*</span></label>
                        <select class="form-select" id="vendor_id" required>
                            <option value="">-- Choose vendor --</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold">Service Type</label>
                        <input type="text" class="form-control" id="service_type" placeholder="e.g., Cleaning, Security, Maintenance">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold">Contract Date</label>
                        <input type="date" class="form-control" id="contract_date">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold">Status</label>
                        <select class="form-select" id="status">
                            <option value="active">Active</option>
                            <option value="inactive">Inactive</option>
                        </select>
                    </div>
                </form>
            `,
            width: '600px',
            showCancelButton: true,
            confirmButtonText: 'Assign Vendor',
            cancelButtonText: 'Cancel',
            didOpen: () => {
                const select = document.getElementById('vendor_id');
                select.innerHTML = '<option value="">-- Loading vendors... --</option>';
                select.disabled = true;
                
                fetch(API.vendors, { headers: getHeaders() })
                    .then(response => response.json())
                    .then(data => {
                        select.disabled = false;
                        select.innerHTML = '<option value="">-- Choose vendor --</option>';
                        
                        const vendors = data.data || data;
                        if (Array.isArray(vendors) && vendors.length > 0) {
                            vendors.forEach(vendor => {
                                const option = document.createElement('option');
                                option.value = vendor.id;
                                option.textContent = `${vendor.name} ${vendor.category ? '(' + vendor.category + ')' : ''}`;
                                select.appendChild(option);
                            });
                        } else {
                            select.innerHTML = '<option value="">-- No vendors available --</option>';
                            Swal.showValidationMessage('No vendors available. Please add vendors first.');
                        }
                    })
                    .catch(error => {
                        console.error('Error loading vendors:', error);
                        select.disabled = false;
                        select.innerHTML = '<option value="">-- Error loading vendors --</option>';
                        Swal.showValidationMessage('Error loading vendors. Please refresh the page.');
                    });
            },
            preConfirm: () => {
                const vendorId = document.getElementById('vendor_id').value;
                if (!vendorId) {
                    Swal.showValidationMessage('Please select a vendor');
                    return false;
                }
                return {
                    vendor_id: vendorId,
                    service_type: document.getElementById('service_type').value,
                    contract_date: document.getElementById('contract_date').value,
                    status: document.getElementById('status').value
                };
            }
        }).then((result) => {
            if (result.isConfirmed) {
                showLoading('Assigning vendor...');
                
                fetch(API.assignVendor, {
                    method: 'POST',
                    headers: getHeaders(),
                    body: JSON.stringify(result.value)
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showSuccess('Vendor assigned successfully');
                    } else {
                        showError(data.message || 'Failed to assign vendor');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showError('An error occurred while assigning the vendor');
                });
            }
        });
    }
    
    function viewVendor(vendorId) {
        fetch(API.vendor(vendorId), { headers: getHeaders() })
            .then(response => response.json())
            .then(data => {
                const vendor = data.data || data;
                Swal.fire({
                    title: 'Vendor Details',
                    html: `
                        <div class="text-start">
                            <div class="mb-3">
                                <strong class="text-success">Vendor Name:</strong><br>
                                <span>${vendor.name}</span>
                            </div>
                            <div class="mb-3">
                                <strong class="text-success">Code:</strong><br>
                                <span>${vendor.code || 'N/A'}</span>
                            </div>
                            <div class="mb-3">
                                <strong class="text-success">Category:</strong><br>
                                <span>${vendor.category || 'N/A'}</span>
                            </div>
                            <div class="mb-3">
                                <strong class="text-success">Contact Person:</strong><br>
                                <span>${vendor.contact_person || 'N/A'}</span>
                            </div>
                            <div class="mb-3">
                                <strong class="text-success">Contact Phone:</strong><br>
                                <span>${vendor.contact_phone || 'N/A'}</span>
                            </div>
                            <div class="mb-3">
                                <strong class="text-success">Contact Email:</strong><br>
                                <span>${vendor.contact_email || 'N/A'}</span>
                            </div>
                            <div class="mb-3">
                                <strong class="text-success">Address:</strong><br>
                                <span>${vendor.address || 'N/A'}</span>
                            </div>
                            <div class="mb-3">
                                <strong class="text-success">Status:</strong><br>
                                <span class="badge bg-${vendor.status == 'active' ? 'success' : 'danger'}">${vendor.status || 'Active'}</span>
                            </div>
                        </div>
                    `,
                    width: '600px'
                });
            })
            .catch(error => {
                console.error('Error:', error);
                showError('Failed to load vendor details');
            });
    }
    
    function editVendorAssignment(stationId, vendorId) {
        fetch(API.vendorAssignment(vendorId), { headers: getHeaders() })
            .then(response => response.json())
            .then(data => {
                const assignment = data.data;
                Swal.fire({
                    title: 'Edit Vendor Assignment',
                    html: `
                        <form id="editVendorForm" class="text-start">
                            <div class="mb-3">
                                <label class="form-label fw-bold">Service Type</label>
                                <input type="text" class="form-control" id="service_type" value="${assignment.service_type || ''}">
                            </div>
                            <div class="mb-3">
                                <label class="form-label fw-bold">Contract Date</label>
                                <input type="date" class="form-control" id="contract_date" value="${assignment.contract_date || ''}">
                            </div>
                            <div class="mb-3">
                                <label class="form-label fw-bold">Status</label>
                                <select class="form-select" id="status">
                                    <option value="active" ${assignment.status == 'active' ? 'selected' : ''}>Active</option>
                                    <option value="inactive" ${assignment.status == 'inactive' ? 'selected' : ''}>Inactive</option>
                                </select>
                            </div>
                        </form>
                    `,
                    showCancelButton: true,
                    confirmButtonText: 'Update',
                    preConfirm: () => ({
                        service_type: document.getElementById('service_type').value,
                        contract_date: document.getElementById('contract_date').value,
                        status: document.getElementById('status').value
                    })
                }).then((result) => {
                    if (result.isConfirmed) {
                        showLoading('Updating assignment...');
                        
                        fetch(API.updateVendor(vendorId), {
                            method: 'PUT',
                            headers: getHeaders(),
                            body: JSON.stringify(result.value)
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                showSuccess('Vendor assignment updated successfully');
                            } else {
                                showError(data.message);
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            showError('Failed to update assignment');
                        });
                    }
                });
            });
    }
    
    function removeVendor(stationId, vendorId) {
        Swal.fire({
            title: 'Remove Vendor?',
            text: "This will remove the vendor assignment from this station.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Yes, remove it!'
        }).then((result) => {
            if (result.isConfirmed) {
                showLoading('Removing vendor...');
                
                fetch(API.removeVendor(vendorId), {
                    method: 'DELETE',
                    headers: getHeaders()
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showSuccess('Vendor has been removed');
                    } else {
                        showError(data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showError('Failed to remove vendor');
                });
            }
        });
    }
    
    // Initialize DataTable when DOM is ready
    $(document).ready(function() {
        if ($.fn.DataTable && $('#employeesTable').length) {
            $('#employeesTable').DataTable({
                pageLength: 10,
                language: {
                    search: "Search employees:",
                    lengthMenu: "Show _MENU_ employees per page",
                    info: "Showing _START_ to _END_ of _TOTAL_ employees"
                }
            });
        }
    });
    
    // Export functions to global scope (using a namespace to avoid conflicts)
    window.stationDetails = {
        viewEmployee,
        viewSchedule,
        assignProvider,
        assignVendor,
        viewProvider,
        viewVendor,
        editProviderAssignment,
        editVendorAssignment,
        removeProvider,
        removeVendor
    };
    
})();