<?= $this->extend('layouts/dashboard') ?>

<?= $this->section('content') ?>
<div class="d-flex justify-content-between align-items-center mb-4">
    <h1 class="h3">Companies Management</h1>
    <?php if (in_array(session()->get('role'), ['admin', 'superadmin'])): ?>
    <a href="<?= base_url('/companies/create') ?>" class="btn btn-primary">
        <i class="fas fa-plus me-2"></i> Add New Company
    </a>
    <?php endif; ?>
</div>

<!-- Success/Error Messages -->
<div id="message-container">
    <?php if (session()->getFlashdata('success')): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <strong>Success!</strong> <?= session()->getFlashdata('success') ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <?php if (session()->getFlashdata('error')): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <strong>Error!</strong> <?= session()->getFlashdata('error') ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>
</div>

<!-- Statistics Cards -->
<?php if (!empty($stats)): ?>
<div class="row g-4 mb-4">
    <div class="col-md-3">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="p-3 rounded-circle bg-primary bg-opacity-10 me-3">
                        <i class="fas fa-building text-primary fs-4"></i>
                    </div>
                    <div>
                        <p class="text-muted mb-1">Total Companies</p>
                        <p class="h4 mb-0"><?= $stats['total_companies'] ?></p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="p-3 rounded-circle bg-success bg-opacity-10 me-3">
                        <i class="fas fa-check-circle text-success fs-4"></i>
                    </div>
                    <div>
                        <p class="text-muted mb-1">Active Companies</p>
                        <p class="h4 mb-0"><?= $stats['active_companies'] ?></p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="p-3 rounded-circle bg-warning bg-opacity-10 me-3">
                        <i class="fas fa-users text-warning fs-4"></i>
                    </div>
                    <div>
                        <p class="text-muted mb-1">Total Workers</p>
                        <p class="h4 mb-0"><?= $stats['total_workers'] ?></p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-3">
        <div class="card border-0 shadow-sm h-100">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="p-3 rounded-circle bg-info bg-opacity-10 me-3">
                        <i class="fas fa-user-clock text-info fs-4"></i>
                    </div>
                    <div>
                        <p class="text-muted mb-1">Contractual Workers</p>
                        <p class="h4 mb-0"><?= $stats['contractual_workers'] ?></p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- Search and Filter Form -->
<div class="card border-0 shadow-sm mb-4">
    <div class="card-body">
        <form method="GET" action="<?= base_url('/companies') ?>" class="row g-3">
            <div class="col-md-3">
                <label for="search" class="form-label">Search</label>
                <input type="text" name="search" id="search" value="<?= esc($search) ?>" placeholder="Company, Email" class="form-control">
            </div>
            
            <div class="col-md-3">
                <label for="area" class="form-label">Area</label>
                <select name="area" id="area" class="form-select">
                    <option value="">All Areas</option>
                    <?php foreach ($areas as $areaOption): ?>
                        <option value="<?= $areaOption ?>" <?= ($area === $areaOption) ? 'selected' : '' ?>><?= $areaOption ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="col-md-3">
                <label for="status" class="form-label">Status</label>
                <select name="status" id="status" class="form-select">
                    <option value="">All Status</option>
                    <option value="Active" <?= ($status === 'Active') ? 'selected' : '' ?>>Active</option>
                    <option value="Inactive" <?= ($status === 'Inactive') ? 'selected' : '' ?>>Inactive</option>
                </select>
            </div>
            
            <div class="col-md-3 d-flex align-items-end">
                <div class="d-flex w-100 gap-2">
                    <button type="submit" class="btn btn-primary w-50">
                        <i class="fas fa-filter me-2"></i> Filter
                    </button>
                    <button type="button" id="reset-filters" class="btn btn-secondary w-50">
                        <i class="fas fa-undo me-2"></i> Reset
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Export Buttons -->
<div class="d-flex justify-content-end mb-4 gap-2">
    <?php if (in_array(session()->get('role'), ['admin', 'superadmin'])): ?>
    <a href="<?= base_url('/companies/export/csv') ?>?search=<?= esc($search) ?>&area=<?= esc($area) ?>&status=<?= esc($status) ?>" class="btn btn-success">
        <i class="fas fa-file-csv me-2"></i> Export CSV
    </a>
    <a href="<?= base_url('/companies/export/pdf') ?>?search=<?= esc($search) ?>&area=<?= esc($area) ?>&status=<?= esc($status) ?>" class="btn btn-danger">
        <i class="fas fa-file-pdf me-2"></i> Export PDF
    </a>
    <?php endif; ?>
</div>

<!-- Companies Table -->
<div class="card border-0 shadow-sm">
    <div class="table-responsive">
        <table class="table table-hover align-middle mb-0">
            <thead class="table-light">
                <tr>
                    <th scope="col">#</th>
                    <th scope="col">Company Name</th>
                    <th scope="col">Area</th>
                    <th scope="col">Total Workers</th>
                    <th scope="col">Contractual</th>
                    <th scope="col">Payroll</th>
                    <th scope="col">Email</th>
                    <th scope="col">Status</th>
                    <th scope="col">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!empty($companies)): ?>
                    <?php foreach ($companies as $company): ?>
                        <tr id="company-row-<?= $company['id'] ?>">
                            <td><?= $company['id'] ?></td>
                            <td class="fw-medium"><?= esc($company['company_name']) ?></td>
                            <td><?= $company['area'] ?></td>
                            <td><?= $company['total_workers'] ?></td>
                            <td><?= $company['contractual_workers'] ?></td>
                            <td><?= $company['payroll'] ?? '0' ?></td>
                            <td><?= esc($company['company_email']) ?></td>
                            <td>
                                <?php if ($company['status'] === 'Active'): ?>
                                    <span class="badge bg-success">Active</span>
                                <?php else: ?>
                                    <span class="badge bg-danger">Inactive</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <a href="<?= base_url('/companies/view/' . $company['id']) ?>" class="btn btn-sm btn-outline-primary me-1">
                                    <i class="fas fa-eye"></i> View
                                </a>
                                
                                <?php if (in_array(session()->get('role'), ['admin', 'superadmin'])): ?>
                                <a href="<?= base_url('/companies/edit/' . $company['id']) ?>" class="btn btn-sm btn-outline-secondary me-1">
                                    <i class="fas fa-edit"></i> Edit
                                </a>
                                <?php if ($company['status'] === 'Active'): ?>
                                <a href="#" 
                                   class="delete-company btn btn-sm btn-outline-danger"
                                   data-id="<?= $company['id'] ?>"
                                   data-name="<?= esc($company['company_name']) ?>">
                                    <i class="fas fa-trash"></i> Delete
                                </a>
                                <?php endif; ?>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="9" class="text-center py-4 text-muted">
                            No companies found.
                        </td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <!-- Pagination -->
    <?php if (!empty($companies)): ?>
    <div class="card-footer border-0">
        <?= $pager->links() ?>
    </div>
    <?php endif; ?>
</div>

<script>
    // Reset filters
    document.getElementById('reset-filters').addEventListener('click', function() {
        window.location.href = '<?= base_url('/companies') ?>';
    });

    // AJAX delete functionality
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('delete-company') || e.target.closest('.delete-company')) {
            e.preventDefault();
            
            const deleteLink = e.target.classList.contains('delete-company') ? e.target : e.target.closest('.delete-company');
            const companyId = deleteLink.getAttribute('data-id');
            const companyName = deleteLink.getAttribute('data-name');
            
            // Confirm deletion
            if (confirm(`Are you sure you want to delete "${companyName}"?`)) {
                // Send AJAX request
                fetch(`<?= base_url('/companies/delete') ?>/${companyId}`, {
                    method: 'POST',
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        'X-CSRF-TOKEN': '<?= csrf_hash() ?>'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        // Remove the company row from the table
                        const companyRow = document.getElementById(`company-row-${companyId}`);
                        if (companyRow) {
                            companyRow.remove();
                        }
                        
                        // Show success message
                        showMessage('success', data.message);
                    } else {
                        // Show error message
                        showMessage('error', data.message);
                    }
                })
                .catch(error => {
                    // Show error message
                    showMessage('error', 'An unexpected error occurred. Please try again.');
                    console.error('Error:', error);
                });
            }
        }
    });
    
    // Show message
    function showMessage(type, message) {
        const messageContainer = document.getElementById('message-container');
        const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
        const alertTitle = type === 'success' ? 'Success!' : 'Error!';
        
        messageContainer.innerHTML = `
            <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
                <strong>${alertTitle}</strong> ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        `;
        
        // Auto-hide message after 5 seconds
        setTimeout(() => {
            const alert = messageContainer.querySelector('.alert');
            if (alert) {
                const bsAlert = new bootstrap.Alert(alert);
                bsAlert.close();
            }
        }, 5000);
    }
</script>
<?= $this->endSection() ?>