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

<?= $this->section('content') ?>
<div class="d-flex justify-content-between align-items-center mb-4">
    <h1 class="h3">
        <?= isset($company) ? 'Personnel for ' . esc($company['company_name']) : 'Personnel Management' ?>
    </h1>
    <?php if (in_array(session()->get('role'), ['admin', 'superadmin'])): ?>
        <?php if (isset($company)): ?>
            <a href="<?= base_url('/companies/' . $company['id'] . '/personnel/create') ?>" class="btn btn-primary">
                <i class="fas fa-plus me-2"></i> Add New Personnel
            </a>
        <?php else: ?>
            <a href="<?= base_url('/personnel/create') ?>" class="btn btn-primary">
                <i class="fas fa-plus me-2"></i> Add New Personnel
            </a>
        <?php endif; ?>
    <?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-users text-primary fs-4"></i>
                    </div>
                    <div>
                        <p class="text-muted mb-1">Total Personnel</p>
                        <p class="h4 mb-0"><?= $stats['total_personnel'] ?></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-user-check text-success fs-4"></i>
                    </div>
                    <div>
                        <p class="text-muted mb-1">Active Personnel</p>
                        <p class="h4 mb-0"><?= $stats['active_personnel'] ?></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-user-tie text-warning fs-4"></i>
                    </div>
                    <div>
                        <p class="text-muted mb-1">Managers</p>
                        <p class="h4 mb-0">
                            <?php 
                            $managers = 0;
                            foreach ($stats['by_role'] as $roleStat) {
                                if ($roleStat['role'] === 'Manager') {
                                    $managers = $roleStat['count'];
                                    break;
                                }
                            }
                            echo $managers;
                            ?>
                        </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-friends text-info fs-4"></i>
                    </div>
                    <div>
                        <p class="text-muted mb-1">HR Personnel</p>
                        <p class="h4 mb-0">
                            <?php 
                            $hrs = 0;
                            foreach ($stats['by_role'] as $roleStat) {
                                if ($roleStat['role'] === 'HR') {
                                    $hrs = $roleStat['count'];
                                    break;
                                }
                            }
                            echo $hrs;
                            ?>
                        </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(isset($company) ? '/companies/' . $company['id'] . '/personnel' : '/personnel') ?>" class="row g-3">
            <div class="col-md-2">
                <label for="search" class="form-label">Search</label>
                <input type="text" name="search" id="search" value="<?= esc($search) ?>" placeholder="Name, Role" class="form-control">
            </div>
            
            <?php if (!isset($company)): ?>
            <div class="col-md-2">
                <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 $companyItem): ?>
                        <option value="<?= $companyItem['id'] ?>" <?= ($company_id == $companyItem['id']) ? 'selected' : '' ?>><?= $companyItem['company_name'] ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <?php endif; ?>
            
            <div class="col-md-2">
                <label for="unit_id" class="form-label">Unit</label>
                <select name="unit_id" id="unit_id" class="form-select">
                    <option value="">All Units</option>
                    <?php foreach ($units as $unit): ?>
                        <option value="<?= $unit['id'] ?>" <?= ($unit_id == $unit['id']) ? 'selected' : '' ?>><?= $unit['unit_name'] ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            
            <div class="col-md-2">
                <label for="role" class="form-label">Role</label>
                <select name="role" id="role" class="form-select">
                    <option value="">All Roles</option>
                    <option value="Manager" <?= ($role === 'Manager') ? 'selected' : '' ?>>Manager</option>
                    <option value="HR" <?= ($role === 'HR') ? 'selected' : '' ?>>HR</option>
                    <option value="Owner" <?= ($role === 'Owner') ? 'selected' : '' ?>>Owner</option>
                    <option value="Other" <?= ($role === 'Other') ? 'selected' : '' ?>>Other</option>
                </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="Left" <?= ($status === 'Left') ? 'selected' : '' ?>>Left</option>
                </select>
            </div>
            
            <div class="col-md-2 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(isset($company) ? '/companies/' . $company['id'] . '/personnel/export/csv' : '/personnel/export/csv') ?>?search=<?= esc($search) ?><?= isset($company) ? '' : '&company_id=' . esc($company_id) ?>&unit_id=<?= esc($unit_id) ?>&role=<?= esc($role) ?>&status=<?= esc($status) ?>" class="btn btn-success">
            <i class="fas fa-file-csv me-2"></i> Export CSV
        </a>
        <a href="<?= base_url(isset($company) ? '/companies/' . $company['id'] . '/personnel/export/pdf' : '/personnel/export/pdf') ?>?search=<?= esc($search) ?><?= isset($company) ? '' : '&company_id=' . esc($company_id) ?>&unit_id=<?= esc($unit_id) ?>&role=<?= esc($role) ?>&status=<?= esc($status) ?>" class="btn btn-danger">
            <i class="fas fa-file-pdf me-2"></i> Export PDF
        </a>
    <?php endif; ?>
</div>

<!-- Personnel 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">Name</th>
                    <th scope="col">Role</th>
                    <?php if (!isset($company)): ?>
                    <th scope="col">Company</th>
                    <?php endif; ?>
                    <th scope="col">Unit</th>
                    <th scope="col">Email</th>
                    <th scope="col">Phone</th>
                    <th scope="col">Status</th>
                    <th scope="col">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!empty($personnel)): ?>
                    <?php foreach ($personnel as $p): ?>
                        <tr id="personnel-row-<?= $p['id'] ?>">
                            <td><?= $p['id'] ?></td>
                            <td class="fw-medium"><?= esc($p['name']) ?></td>
                            <td>
                                <?php if ($p['role'] === 'Manager'): ?>
                                    <span class="badge bg-primary">Manager</span>
                                <?php elseif ($p['role'] === 'HR'): ?>
                                    <span class="badge bg-success">HR</span>
                                <?php elseif ($p['role'] === 'Owner'): ?>
                                    <span class="badge bg-info">Owner</span>
                                <?php else: ?>
                                    <span class="badge bg-secondary"><?= $p['role'] ?></span>
                                <?php endif; ?>
                            </td>
                            <?php if (!isset($company)): ?>
                            <td><?= esc($p['company_name']) ?></td>
                            <?php endif; ?>
                            <td><?= esc($p['unit_name'] ?? '-') ?></td>
                            <td><?= $p['email'] ?? '-' ?></td>
                            <td><?= $p['phone'] ?? '-' ?></td>
                            <td>
                                <?php if ($p['status'] === 'Active'): ?>
                                    <span class="badge bg-success">Active</span>
                                <?php else: ?>
                                    <span class="badge bg-danger">Left</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <a href="<?= base_url('/personnel/view/' . $p['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('/personnel/edit/' . $p['id']) ?>" class="btn btn-sm btn-outline-secondary me-1">
                                    <i class="fas fa-edit"></i> Edit
                                </a>
                                <?php if ($p['status'] === 'Active'): ?>
                                <a href="#" 
                                   class="delete-personnel btn btn-sm btn-outline-danger"
                                   data-id="<?= $p['id'] ?>"
                                   data-name="<?= esc($p['name']) ?>">
                                    <i class="fas fa-trash"></i> Delete
                                </a>
                                <?php endif; ?>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="<?= isset($company) ? '8' : '9' ?>" class="text-center py-4 text-muted">
                            No personnel found.
                        </td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <!-- Pagination -->
    <?php if (!empty($personnel)): ?>
    <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(isset($company) ? '/companies/' . $company['id'] . '/personnel' : '/personnel') ?>';
    });

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