<?php $title=__('customers.title', 'Customers'); ob_start(); ?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1 class="h3 mb-0">
        <i class="fas fa-users"></i> <?= __('customers.title', 'Customers') ?>
    </h1>
    <div class="btn-group">
        <a href="/samanta_crm/customers/create" class="btn btn-primary">
            <i class="fas fa-plus"></i> <?= __('common.new', 'New') ?>
        </a>
    </div>
</div>

<!-- Filters -->
<div class="card mb-3">
    <div class="card-body">
        <form id="filterForm" class="row g-3">
            <div class="col-md-3">
                <label class="form-label"><?= __('customers.type', 'Type') ?></label>
                <select name="type" id="filterType" class="form-select">
                    <option value=""><?= __('common.all', 'All') ?></option>
                    <option value="inhouse" selected><?= __('customers.type_inhouse', 'In-House') ?></option>
                    <option value="customer"><?= __('customers.type_customer', 'Customer') ?></option>
                </select>
            </div>
            <div class="col-md-5">
                <label class="form-label"><?= __('common.search', 'Search') ?></label>
                <input type="text" name="search" id="filterSearch" class="form-control" placeholder="<?= __('customers.search_placeholder', 'Search by name, email or phone...') ?>">
            </div>
            <div class="col-md-2">
                <label class="form-label"><?= __('common.per_page', 'Per Page') ?></label>
                <select name="per_page" id="filterPerPage" class="form-select">
                    <option value="10">10</option>
                    <option value="25" selected>25</option>
                    <option value="50">50</option>
                    <option value="100">100</option>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">&nbsp;</label>
                <button type="submit" class="btn btn-primary w-100">
                    <i class="fas fa-search me-1"></i><?= __('common.filter', 'Filter') ?>
                </button>
            </div>
        </form>
    </div>
</div>

<div class="card">
    <div class="card-header py-2 d-flex justify-content-between align-items-center">
        <span class="small fw-bold"><i class="fas fa-table me-1"></i><?= __('customers.title', 'Customers') ?></span>
        <span id="totalCount" class="badge bg-secondary">0</span>
    </div>
    <div class="card-body pt-0 position-relative">
        <!-- Loading Overlay -->
        <div id="loadingOverlay" class="position-absolute top-0 start-0 w-100 h-100 d-none" style="background: rgba(255,255,255,0.8); z-index: 10;">
            <div class="d-flex justify-content-center align-items-center h-100">
                <div class="spinner-border text-primary" role="status">
                    <span class="visually-hidden"><?= __('common.loading', 'Loading...') ?></span>
                </div>
            </div>
        </div>
        
        <table class="table table-sm table-hover align-middle data-table mb-0">
            <thead>
                <tr>
                    <th><?= __('common.name', 'Name') ?></th>
                    <th><?= __('common.email', 'Email') ?></th>
                    <th><?= __('customers.phone', 'Phone') ?></th>
                    <th><?= __('customers.type', 'Type') ?></th>
                    <th><?= __('common.status', 'Status') ?></th>
                    <th class="text-end"><?= __('common.actions', 'Actions') ?></th>
                </tr>
            </thead>
            <tbody id="customersTableBody">
                <!-- Customers will be loaded via AJAX -->
            </tbody>
        </table>
    </div>
    <div class="card-footer py-2">
        <div class="d-flex justify-content-between align-items-center">
            <div id="paginationInfo" class="small text-muted"></div>
            <nav id="paginationNav">
                <ul class="pagination pagination-sm mb-0">
                    <!-- Pagination will be loaded via AJAX -->
                </ul>
            </nav>
        </div>
    </div>
</div>

<script>
// AJAX Customer Loading
let currentPage = 1;
let currentFilters = {
    type: 'inhouse',
    search: '',
    per_page: 25
};

// Fetch customers via AJAX
function fetchCustomers(page = 1) {
    const loadingOverlay = document.getElementById('loadingOverlay');
    const tbody = document.getElementById('customersTableBody');
    
    // Show loading
    loadingOverlay.classList.remove('d-none');
    
    // Build query params
    const params = new URLSearchParams({
        ajax: '1',
        type: currentFilters.type || '',
        search: currentFilters.search || '',
        page: page,
        per_page: currentFilters.per_page
    });
    
    const baseUrl = window.location.pathname.split('/customers')[0];
    const fetchUrl = `${baseUrl}/customers?${params.toString()}`;
    
    fetch(fetchUrl)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return response.json();
        })
        .then(data => {
            renderCustomers(data.customers);
            renderPagination(data.pagination);
            currentPage = page;
            loadingOverlay.classList.add('d-none');
        })
        .catch(error => {
            console.error('Error fetching customers:', error);
            tbody.innerHTML = '<tr><td colspan="6" class="text-center text-danger py-4"><?= __("common.error_loading", "Error loading data") ?></td></tr>';
            loadingOverlay.classList.add('d-none');
        });
}

// Render customers in table
function renderCustomers(customers) {
    const tbody = document.getElementById('customersTableBody');
    
    if (customers.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="6" class="text-center text-muted py-4">
                    <i class="fas fa-inbox fa-3x mb-3 d-block"></i>
                    <?= __('common.no_results', 'No results found') ?>
                </td>
            </tr>
        `;
        return;
    }
    
    const baseUrl = window.location.pathname.split('/customers')[0];
    
    tbody.innerHTML = customers.map(c => {
        const typeClass = c.type === 'inhouse' ? 'info' : 'primary';
        const typeLabel = c.type === 'inhouse' ? '<?= __("customers.type_inhouse", "In-House") ?>' : '<?= __("customers.type_customer", "Customer") ?>';
        const statusClass = c.status === 'active' ? 'success' : 'secondary';
        
        return `
            <tr>
                <td><strong>${escapeHtml(c.name)}</strong></td>
                <td>${escapeHtml(c.email || '')}</td>
                <td>${escapeHtml(c.phone || '')}</td>
                <td>
                    <span class="badge bg-${typeClass}">${typeLabel}</span>
                </td>
                <td>
                    <span class="badge bg-${statusClass}">${escapeHtml(c.status)}</span>
                </td>
                <td class="text-end">
                    <a class="btn btn-sm btn-outline-primary" href="${baseUrl}/customers/${c.id}/edit">
                        <i class="fas fa-edit"></i> <?= __('common.edit', 'Edit') ?>
                    </a>
                    <form action="${baseUrl}/customers/${c.id}/delete" method="POST" class="d-inline" onsubmit="return confirm('<?= __('customers.confirm_delete', 'Delete customer?') ?>')">
                        <button class="btn btn-sm btn-outline-danger">
                            <i class="fas fa-trash"></i> <?= __('common.delete', 'Del') ?>
                        </button>
                    </form>
                </td>
            </tr>
        `;
    }).join('');
}

// Update count displays
function updateCount(total) {
    document.getElementById('totalCount').textContent = total;
}

// Render pagination controls
function renderPagination(pagination) {
    const paginationInfo = document.getElementById('paginationInfo');
    const paginationNav = document.getElementById('paginationNav').querySelector('.pagination');
    const totalCount = document.getElementById('totalCount');
    
    // Update total count badge
    totalCount.textContent = pagination.total_count;
    
    // Update info text
    const start = ((pagination.current_page - 1) * pagination.per_page) + 1;
    const end = Math.min(pagination.current_page * pagination.per_page, pagination.total_count);
    paginationInfo.textContent = `<?= __('common.showing', 'Showing') ?> ${start}-${end} <?= __('common.of', 'of') ?> ${pagination.total_count}`;
    
    // Build pagination buttons
    let paginationHtml = '';
    
    // Previous button
    paginationHtml += `
        <li class="page-item ${!pagination.has_prev ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="changePage(${pagination.current_page - 1}); return false;">
                <i class="fas fa-chevron-left"></i>
            </a>
        </li>
    `;
    
    // Page numbers
    const maxButtons = 5;
    let startPage = Math.max(1, pagination.current_page - Math.floor(maxButtons / 2));
    let endPage = Math.min(pagination.total_pages, startPage + maxButtons - 1);
    
    if (endPage - startPage < maxButtons - 1) {
        startPage = Math.max(1, endPage - maxButtons + 1);
    }
    
    // First page
    if (startPage > 1) {
        paginationHtml += `
            <li class="page-item">
                <a class="page-link" href="#" onclick="changePage(1); return false;">1</a>
            </li>
        `;
        if (startPage > 2) {
            paginationHtml += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
        }
    }
    
    // Page buttons
    for (let i = startPage; i <= endPage; i++) {
        paginationHtml += `
            <li class="page-item ${i === pagination.current_page ? 'active' : ''}">
                <a class="page-link" href="#" onclick="changePage(${i}); return false;">${i}</a>
            </li>
        `;
    }
    
    // Last page
    if (endPage < pagination.total_pages) {
        if (endPage < pagination.total_pages - 1) {
            paginationHtml += `<li class="page-item disabled"><span class="page-link">...</span></li>`;
        }
        paginationHtml += `
            <li class="page-item">
                <a class="page-link" href="#" onclick="changePage(${pagination.total_pages}); return false;">${pagination.total_pages}</a>
            </li>
        `;
    }
    
    // Next button
    paginationHtml += `
        <li class="page-item ${!pagination.has_next ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="changePage(${pagination.current_page + 1}); return false;">
                <i class="fas fa-chevron-right"></i>
            </a>
        </li>
    `;
    
    paginationNav.innerHTML = paginationHtml;
}

// Change page handler
function changePage(page) {
    if (page < 1) return;
    fetchCustomers(page);
    window.scrollTo({ top: 0, behavior: 'smooth' });
}

// HTML escape helper
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// Filter form submit handler
document.getElementById('filterForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    currentFilters = {
        type: document.getElementById('filterType').value,
        search: document.getElementById('filterSearch').value,
        per_page: parseInt(document.getElementById('filterPerPage').value)
    };
    
    fetchCustomers(1);
});

// Real-time search with debounce
let searchTimeout;
document.getElementById('filterSearch').addEventListener('input', function() {
    clearTimeout(searchTimeout);
    searchTimeout = setTimeout(() => {
        currentFilters.search = this.value;
        fetchCustomers(1);
    }, 500);
});

// Type filter change
document.getElementById('filterType').addEventListener('change', function() {
    currentFilters.type = this.value;
    fetchCustomers(1);
});

// Per page change
document.getElementById('filterPerPage').addEventListener('change', function() {
    currentFilters.per_page = parseInt(this.value);
    fetchCustomers(1);
});

// Load customers on page load
document.addEventListener('DOMContentLoaded', function() {
    fetchCustomers(1);
});
</script>

<?php $content=ob_get_clean(); require_once __DIR__.'/../layout.php'; ?>


