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

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

<!-- Search and Filter Form -->
<div class="card border-0 shadow-sm mb-4">
    <div class="card-body">
        <form method="GET" action="<?= base_url('/units') ?>" 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="Unit, Manager" class="form-control">
            </div>
            
            <div class="col-md-3">
                <label for="company_id" class="form-label">Company</label>
                <select name="company_id" id="company_id" class="form-select">
                    <option value="">All Companies</option>
                    <?php foreach ($companies as $company): ?>
                        <option value="<?= $company['id'] ?>" <?= ($company_id == $company['id']) ? 'selected' : '' ?>><?= $company['company_name'] ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="col-md-2">
                <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-2 d-flex align-items-end">
                <button type="submit" class="btn btn-primary w-100">
                    <i class="fas fa-filter me-2"></i> Filter
                </button>
            </div>
            
            <div class="col-md-2 d-flex align-items-end">
                <button type="button" id="reset-filters" class="btn btn-secondary w-100">
                    <i class="fas fa-undo me-2"></i> Reset
                </button>
            </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('/units/export/csv') ?>?search=<?= esc($search) ?>&company_id=<?= esc($company_id) ?>&status=<?= esc($status) ?>" class="btn btn-success">
        <i class="fas fa-file-csv me-2"></i> Export CSV
    </a>
    <a href="<?= base_url('/units/export/pdf') ?>?search=<?= esc($search) ?>&company_id=<?= esc($company_id) ?>&status=<?= esc($status) ?>" class="btn btn-danger">
        <i class="fas fa-file-pdf me-2"></i> Export PDF
    </a>
    <?php endif; ?>
</div>

<!-- Units 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">Unit Name</th>
                    <th scope="col">Company</th>
                    <th scope="col">Manager</th>
                    <th scope="col">HR</th>
                    <th scope="col">Total Workers</th>
                    <th scope="col">Contractual</th>
                    <th scope="col">Status</th>
                    <th scope="col">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!empty($units)): ?>
                    <?php foreach ($units as $unit): ?>
                        <tr id="unit-row-<?= $unit['id'] ?>">
                            <td><?= $unit['id'] ?></td>
                            <td class="fw-medium"><?= esc($unit['unit_name']) ?></td>
                            <td><?= esc($unit['company_name']) ?></td>
                            <td><?= $unit['unit_manager_name'] ?? '-' ?></td>
                            <td><?= $unit['unit_hr_name'] ?? '-' ?></td>
                            <td><?= $unit['total_workers'] ?></td>
                            <td><?= $unit['contractual_workers'] ?></td>
                            <td>
                                <?php if ($unit['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('/units/view/' . $unit['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('/units/edit/' . $unit['id']) ?>" class="btn btn-sm btn-outline-secondary me-1">
                                    <i class="fas fa-edit"></i> Edit
                                </a>
                                <a href="#" 
                                   class="delete-unit btn btn-sm btn-outline-danger"
                                   data-id="<?= $unit['id'] ?>"
                                   data-name="<?= esc($unit['unit_name']) ?>">
                                    <i class="fas fa-trash"></i> Delete
                                </a>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="9" class="text-center py-4 text-muted">
                            No units found.
                        </td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <!-- Pagination -->
    <?php if (!empty($units)): ?>
    <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('/units') ?>';
    });

    // AJAX delete functionality
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('delete-unit') || e.target.closest('.delete-unit')) {
            e.preventDefault();
            
            const deleteLink = e.target.classList.contains('delete-unit') ? e.target : e.target.closest('.delete-unit');
            const unitId = deleteLink.getAttribute('data-id');
            const unitName = deleteLink.getAttribute('data-name');
            
            // Confirm deletion
            if (confirm(`Are you sure you want to delete "${unitName}"?`)) {
                // Send AJAX request
                fetch(`<?= base_url('/units/delete') ?>/${unitId}`, {
                    method: 'POST',
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        'X-CSRF-TOKEN': '<?= csrf_hash() ?>'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        // Remove the unit row from the table
                        const unitRow = document.getElementById(`unit-row-${unitId}`);
                        if (unitRow) {
                            unitRow.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() ?>