@extends('layouts.masterbeta')

@section('title', 'Click ERP - Client Management')

@push('styles')
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<style>
    /* Custom styling to make Select2 match Bootstrap 5 form controls */
    .select2-container .select2-selection--multiple {
        min-height: 38px;
        border: 1px solid #dee2e6;
        border-radius: 0.375rem;
    }
    .select2-container--default .select2-selection--multiple .select2-selection__choice {
        background-color: #5c4df0;
        border: none;
        color: white;
        border-radius: 4px;
        padding: 2px 8px;
        margin-top: 5px;
    }
    .select2-container--default .select2-selection--multiple .select2-selection__choice__remove {
        color: white;
        margin-right: 5px;
    }
    .select2-container--default .select2-selection--multiple .select2-selection__choice__remove:hover {
        color: #ffcccc;
        background: transparent;
    }
    /* Fix for validation red border */
    .is-invalid + .select2-container .select2-selection {
        border-color: #dc3545;
    }
    .avatar-circle { width: 36px; height: 36px; display: flex; align-items: center; justify-content: center; border-radius: 50%; font-weight: bold; font-size: 0.85rem; }
    </style>
@endpush

@section('breadcrumbs')
    <a href="{{ url('/') }}" class="text-secondary text-decoration-none"><i class="bi bi-house me-2"></i></a>
    <i class="bi bi-chevron-right text-secondary me-2" style="font-size: 0.8rem;"></i>
    <span class="fw-bold" style="font-size: 0.95rem;">Clients</span>
@endsection

@section('content')
    <!-- Page Header -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h4 class="fw-bold mb-1">Client Management</h4>
            <p class="text-secondary mb-0" style="font-size: 0.9rem;">Manage clients, payment modes, services etc.</p>
        </div>
        <div class="dropdown">
            <button class="btn btn-outline-secondary d-flex align-items-center dropdown-toggle" type="button" data-bs-toggle="dropdown" style="border-radius: 8px;">
                <i class="bi bi-download me-2"></i> Export
            </button>
            <ul class="dropdown-menu shadow-sm border-0">
                <li>
                    <a class="dropdown-item btn-export d-flex align-items-center" href="#" data-format="csv">
                        <i class="bi bi-filetype-csv me-2 text-success"></i> Export as CSV (Excel)
                    </a>
                </li>
                <li>
                    <a class="dropdown-item btn-export d-flex align-items-center" href="#" data-format="pdf">
                        <i class="bi bi-filetype-pdf me-2 text-danger"></i> Export as PDF
                    </a>
                </li>
            </ul>
        </div>
        <button class="btn text-white fw-bold d-flex align-items-center" style="background-color: #5c4df0; border-radius: 8px;" id="btnOpenClientModal">
            <i class="bi bi-plus-lg me-2"></i> Add New Client
        </button>

    </div>

    <!-- Data Table Card -->
    <div class="content-card">
        <!-- Filters -->
        <div class="p-3 border-bottom bg-light bg-opacity-50">
            <div class="row g-3">
                <div class="col-md-4">
                    <div class="input-group">
                        <span class="input-group-text bg-white border-end-0 text-secondary"><i class="bi bi-search"></i></span>
                        <input type="text" class="form-control bg-white border-start-0 ps-0" id="searchClient" placeholder="Search clients, email, or contact...">
                    </div>
                </div>
                <div class="col-md-2">
                    <select class="form-select bg-white" id="filterService">
                        <option value="">All Service Types</option>
                        <option value="a2p">A2P</option>
                        <option value="ussd">USSD</option>
                        <option value="airtime">Airtime</option>
                        <option value="voice">Voice</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <select class="form-select bg-white" id="filterBilling">
                        <option value="">Payment Mode: All</option>
                        <option value="postpaid">Postpaid (Invoice)</option>
                        <option value="prepaid">Prepaid (Balance)</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <select class="form-select bg-white" id="filterStatus">
                        <option value="">Status: All</option>
                        <option value="Live">Live</option>
                        <option value="Prospective">Prospective</option>
                        <option value="Cancelled">Cancelled</option>
                        <option value="Inactive">Inactive</option>
                        <option value="Prospective">Prospective</option>
                    </select>
                </div>
            </div>
        </div>

        <!-- Table -->
        <div class="table-responsive">
            <table class="table table-custom table-hover mb-0">
                <thead>
                    <tr>
                        <th>Client Details</th>
                        <th>Primary Contact</th>
                        <th>Services</th>
                        <th>Billing</th>
                        <th>Date Added</th>
                        <th>Status</th>
                        <th class="text-end">Actions</th>
                    </tr>
                </thead>
                <tbody id="clientTableBody">
                    <!-- Data will be injected here via AJAX -->
                </tbody>
            </table>
        </div>
        
        <!-- Pagination Container -->
        <div class="p-3 d-flex justify-content-between align-items-center" id="paginationContainer">
            <span class="text-secondary" style="font-size: 0.85rem;" id="paginationInfo">Showing 0 to 0 of 0 entries</span>
            <nav>
                <ul class="pagination pagination-sm mb-0" id="paginationLinks">
                    <!-- Pagination links injected here -->
                </ul>
            </nav>
        </div>
    </div>
@endsection

@push('modals')
    @include('clients.partials.create')
@endpush

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#clientService').select2({
                placeholder: "-- Select Services --",
                allowClear: true,
                dropdownParent: $('#createClientModal')
            });
            let searchTimer;

            // Initialize the table on page load
            fetchClients();

            // Event Listeners for Search and Filters
            $('#searchClient').on('keyup', function() {
                clearTimeout(searchTimer);
                // Debounce the search so we don't spam the server on every keystroke
                searchTimer = setTimeout(() => fetchClients(1), 400); 
            });

            $('#filterService, #filterBilling').on('change', function() {
                fetchClients(1);
            });
            $('#filterService, #filterStatus').on('change', function() {
                fetchClients(1);
            });
            // Handle Pagination Clicks dynamically
            $(document).on('click', '.page-link-ajax', function(e) {
                e.preventDefault();
                let page = $(this).data('page');
                if (page) fetchClients(page);
            });

            $('#btnOpenClientModal').on('click', function(e) {
                e.preventDefault();
                // Replace '#createClientModal' with the actual ID of the modal in your clients.partials.create file
                $('#createClientModal').modal('show'); 
            });

            $(document).on('click', '.btn-view-client', function(e) {
                e.preventDefault();
                let clientId = $(this).data('id');
                
                // OPTION A: Redirect to a view page
                window.location.href = base_url + "/clients/" + clientId;
                
                // OPTION B: If you are using a View Modal instead, uncomment this:
                // fetchClientDetailsForView(clientId);
                // $('#viewClientModal').modal('show');
            });


            $(document).on('click', '.btn-edit-client', function(e) {
                e.preventDefault();
                let clientId = $(this).data('id');
                
                // OPTION A: Redirect to an edit page
                window.location.href = base_url + "/clients/" + clientId + "/edit";
                
                // OPTION B: If you are using an Edit Modal instead, uncomment this:
                // fetchClientDetailsForEdit(clientId); 
                // $('#editClientModal').modal('show');
            });

            // ---------------------------------------------------------
            // AJAX FORM SUBMISSION (Create Client)
            // ---------------------------------------------------------
            $('#createClientForm').on('submit', function(e) {
                e.preventDefault();
                
                let $form = $(this);
                let $submitBtn = $('#btnSubmitClient');
                let originalText = $submitBtn.html();
                let $alertBox = $('#clientModalAlert');
                
                // 1. Show loading state & reset previous alerts/errors
                $submitBtn.html('<span class="spinner-border spinner-border-sm me-2"></span>Saving...').prop('disabled', true);
                $alertBox.html(''); 
                $form.find('.is-invalid').removeClass('is-invalid');
                $form.find('.invalid-feedback').remove();

                $.ajax({
                    url: $form.attr('action'), 
                    method: 'POST',
                    data: $form.serialize(),
                    success: function(response) {
                        if(response.success) {
                            // Show success message inside the modal
                            $alertBox.html(`
                                <div class="alert alert-success d-flex align-items-center" role="alert">
                                    <i class="bi bi-check-circle-fill me-2"></i>
                                    <div>${response.message || 'Client added successfully!'}</div>
                                </div>
                            `);
                            
                            // Refresh the background datatable
                            fetchClients(1);
                            
                            // Optional: Automatically close the modal after 2 seconds
                            setTimeout(() => {
                                $('#createClientModal').modal('hide');
                                $form[0].reset();
                                $alertBox.html('');
                            }, 2000);
                        }
                    },
                    error: function(xhr) {
                        if (xhr.status === 401) {
                            window.location.href = base_url + '/login';
                        }
                        // Handle Laravel Validation Errors (Status 422)
                        if (xhr.status === 422) {
                            let errors = xhr.responseJSON.errors;
                            
                            // Show general warning alert at the top
                            $alertBox.html(`
                                <div class="alert alert-danger d-flex align-items-center" role="alert">
                                    <i class="bi bi-exclamation-triangle-fill me-2"></i>
                                    <div>Please fix the errors highlighted below.</div>
                                </div>
                            `);

                            // Highlight specific fields
                            $.each(errors, function(key, value) {
                                // Account for array names like services[]
                                let fieldName = key;
                                if(key === 'services') fieldName = 'services[]';
                                
                                let $input = $form.find('[name="' + fieldName + '"]');
                                
                                if ($input.length) {
                                    $input.addClass('is-invalid');
                                    // Append the specific error message right below the field
                                    $input.parent().append('<div class="invalid-feedback d-block fw-medium">' + value[0] + '</div>');
                                }
                            });
                        } else {
                            // Handle standard 500 server errors
                            $alertBox.html(`
                                <div class="alert alert-danger d-flex align-items-center" role="alert">
                                    <i class="bi bi-x-circle-fill me-2"></i>
                                    <div>An unexpected server error occurred. Please try again.</div>
                                </div>
                            `);
                        }
                    },
                    complete: function() {
                        // Restore the button to its original state
                        $submitBtn.html(originalText).prop('disabled', false);
                    }
                });
            });
            
            // Clear alerts and errors when the modal is closed manually
            $('#createClientModal').on('hidden.bs.modal', function () {
                $('#createClientForm')[0].reset();
                $('#clientService').val(null).trigger('change');
                $('#clientModalAlert').html('');
                $('#createClientForm').find('.is-invalid').removeClass('is-invalid');
                $('#createClientForm').find('.invalid-feedback').remove();
            });
            // AJAX Fetch Function
            function fetchClients(page = 1) {
                const search = $('#searchClient').val();
                const service = $('#filterService').val();
                const billing = $('#filterBilling').val();
                const status = $('#filterStatus').val();

                // Show loading state
                $('#clientTableBody').html(`
                    <tr>
                        <td colspan="7" class="text-center py-5">
                            <div class="spinner-border text-primary" role="status" style="color: #5c4df0 !important;"></div>
                            <div class="mt-2 text-secondary" style="font-size: 0.85rem;">Loading clients...</div>
                        </td>
                    </tr>
                `);

                $.ajax({
                    url:  base_url + "/clients/data",
                    type: "GET",
                    data: { page: page, search: search, service: service, billing: billing, status:status },
                    success: function(response) {
                        renderTable(response.data);
                        renderPagination(response);
                    },
                    error: function() {
                        $('#clientTableBody').html('<tr><td colspan="6" class="text-center text-danger py-4">Failed to load data. Please try again.</td></tr>');
                    }
                });
            }
            // Handle Export Actions
            $('.btn-export').on('click', function(e) {
                e.preventDefault();
                
                // Get current filter values
                const search = $('#searchClient').val();
                const service = $('#filterService').val();
                const billing = $('#filterBilling').val();
                const status = $('#filterStatus').val();
                const format = $(this).data('format'); // 'csv' or 'pdf'
                
                // Build the query string
                const queryParams = $.param({
                    search: search,
                    service: service,
                    billing: billing,
                    status : billing,
                    format: format
                });

                window.location.href = "{{ route('clients.export') }}?" + queryParams;
            });
            // Render Table Rows
            function renderTableOld(clients) {
                let html = '';

                if (clients.length === 0) {
                    $('#clientTableBody').html('<tr><td colspan="6" class="text-center text-secondary py-4">No clients found matching your criteria.</td></tr>');
                    return;
                }

                clients.forEach(client => {
                    // Extract initials for the avatar
                    let initials = client.name.substring(0, 2).toUpperCase();
                    
                    let servicesHtml = '<span class="text-secondary" style="font-size: 0.8rem;">N/A</span>';
                    if (client.services) {
                        try {
                            let servicesArray = JSON.parse(client.services);
                            
                            // 2. Map each service into a Bootstrap badge
                            if (Array.isArray(servicesArray) && servicesArray.length > 0) {
                                servicesHtml = servicesArray.map(service => 
                                    `<span class="badge bg-secondary bg-opacity-10 text-secondary border me-1 mb-1" style="font-size: 0.7rem;">${service}</span>`
                                ).join('');
                            }
                        } catch (e) {
                            console.error("Could not parse services for client: " + client.name);
                        }
                    }
                    // Status Badge Logic
                    let statusBadge = client.status === 'active' 
                        ? '<span class="badge bg-success bg-opacity-10 text-success px-2 py-1"><i class="bi bi-check-circle me-1"></i>Active</span>'
                        : '<span class="badge bg-warning bg-opacity-10 text-warning px-2 py-1"><i class="bi bi-clock me-1"></i>' + client.status + '</span>';

                    html += `
                        <tr>
                            <td>
                                <div class="d-flex align-items-center">
                                    <div class="avatar-circle bg-primary bg-opacity-10 text-primary me-3">${initials}</div>
                                    <div>
                                        <div class="fw-bold text-dark">${client.name}</div>
                                        <div class="text-secondary" style="font-size: 0.8rem;"><i class="bi bi-geo-alt me-1"></i>${client.country || 'N/A'}</div>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <div class="fw-semibold">${client.contact_person || 'N/A'}</div>
                                <div class="text-secondary" style="font-size: 0.8rem;">${client.email || 'N/A'}</div>
                            </td>
                            <td style="max-width: 200px; white-space: normal;">
                                ${servicesHtml}
                            </td>
                            <td><span class="badge bg-info bg-opacity-10 text-info text-uppercase">${client.pay_mode || 'N/A'}</span></td>
                            <td><span class="fw-medium text-primary">${client.created_at}</span></td>
                            <td>${statusBadge}</td>
                            <td class="text-end">
                                <button class="btn btn-sm btn-light text-primary me-1 btn-view-client" 
                                    data-id="${client.id}">
                                    <i class="bi bi-eye"></i>
                                </button>
                                <button class="btn btn-sm btn-light text-primary me-1 btn-edit-client" 
                                    data-id="${client.id}">
                                    <i class="bi bi-pencil"></i>
                                </button>
                            </td>
                        </tr>
                    `;
                });

                $('#clientTableBody').html(html);
            }
            function renderTable(clients) {
                let html = '';

                if (clients.length === 0) {
                    $('#clientTableBody').html('<tr><td colspan="7" class="text-center text-secondary py-4">No clients found matching your criteria.</td></tr>');
                    return;
                }

                clients.forEach(client => {
                    // 1. Extract initials for the avatar
                    let initials = client.name.substring(0, 2).toUpperCase();
                    
                    // 2. Handle Services
                    let servicesHtml = '<span class="text-secondary" style="font-size: 0.8rem;">N/A</span>';
                    if (client.services) {
                        try {
                            let servicesArray = JSON.parse(client.services);
                            if (Array.isArray(servicesArray) && servicesArray.length > 0) {
                                servicesHtml = servicesArray.map(service => 
                                    `<span class="badge bg-secondary bg-opacity-10 text-secondary border me-1 mb-1" style="font-size: 0.7rem;">${service}</span>`
                                ).join('');
                            }
                        } catch (e) {
                            console.error("Could not parse services for client: " + client.name);
                        }
                    }

                    // 3. Status Badge Logic
                    let statusBadge = client.status === 'Live' || client.status === 'active' 
                        ? '<span class="badge bg-success bg-opacity-10 text-success px-2 py-1"><i class="bi bi-check-circle me-1"></i>Active</span>'
                        : '<span class="badge bg-warning bg-opacity-10 text-warning px-2 py-1"><i class="bi bi-clock me-1"></i>' + client.status + '</span>';

                    // 4. Format the Date (Human Friendly)
                    let formattedDate = 'N/A';
                    if (client.created_at) {
                        const dateObj = new Date(client.created_at);
                        // Formats to: "23 Jul 2026"
                        formattedDate = dateObj.toLocaleDateString('en-GB', {
                            day: 'numeric',
                            month: 'short',
                            year: 'numeric'
                        });
                    }

                    html += `
                        <tr>
                            <td>
                                <div class="d-flex align-items-center">
                                    <div class="avatar-circle bg-primary bg-opacity-10 text-primary me-3">${initials}</div>
                                    <div>
                                        <div class="fw-bold text-dark">${client.name}</div>
                                        <div class="text-secondary" style="font-size: 0.8rem;"><i class="bi bi-geo-alt me-1"></i>${client.country || 'N/A'}</div>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <div class="fw-semibold">${client.contact_person || 'N/A'}</div>
                                <div class="text-secondary" style="font-size: 0.8rem;">${client.email || 'N/A'}</div>
                            </td>
                            <td style="max-width: 200px; white-space: normal;">
                                ${servicesHtml}
                            </td>
                            <td><span class="badge bg-info bg-opacity-10 text-info text-uppercase">${client.pay_mode || 'N/A'}</span></td>
                            
                            <!-- Updated Date Column -->
                            <td><span class="fw-medium text-primary">${formattedDate}</span></td>
                            
                            <td>${statusBadge}</td>
                            <td class="text-end">
                                <button class="btn btn-sm btn-light text-primary me-1 btn-view-client" 
                                    data-id="${client.id}">
                                    <i class="bi bi-eye"></i>
                                </button>
                                <button class="btn btn-sm btn-light text-primary me-1 btn-edit-client" 
                                    data-id="${client.id}">
                                    <i class="bi bi-pencil"></i>
                                </button>
                            </td>
                        </tr>
                    `;
                });

                $('#clientTableBody').html(html);
            }

            // Render Pagination Links
            function renderPagination(response) {
                // Update "Showing X to Y of Z entries"
                $('#paginationInfo').text(`Showing ${response.from || 0} to ${response.to || 0} of ${response.total} entries`);

                let paginationHtml = '';
                
                // Only show pagination if there is more than 1 page
                if (response.last_page > 1) {
                    // Previous Button
                    let prevDisabled = response.current_page === 1 ? 'disabled' : '';
                    paginationHtml += `<li class="page-item ${prevDisabled}"><a class="page-link page-link-ajax" href="#" data-page="${response.current_page - 1}">Previous</a></li>`;

                    // Page Numbers
                    for (let i = 1; i <= response.last_page; i++) {
                        let activeClass = response.current_page === i ? 'active' : '';
                        let style = response.current_page === i ? 'style="background-color: #5c4df0; border-color: #5c4df0;"' : 'class="page-link text-dark"';
                        
                        paginationHtml += `<li class="page-item ${activeClass}"><a class="page-link page-link-ajax" href="#" ${style} data-page="${i}">${i}</a></li>`;
                    }

                    // Next Button
                    let nextDisabled = response.current_page === response.last_page ? 'disabled' : '';
                    paginationHtml += `<li class="page-item ${nextDisabled}"><a class="page-link page-link-ajax" href="#" data-page="${response.current_page + 1}">Next</a></li>`;
                }

                $('#paginationLinks').html(paginationHtml);
            }
        });
    </script>
@endpush