<?php
// Set flag to hide footer
$hideFooter = false;
?>
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2>
                    <i class="fas fa-times-circle me-2" style="color: var(--nis-primary);"></i>
                    Rejected Applications
                </h2>
                <div>
                    <a href="<?= APP_URL ?>/migrants/search" class="btn btn-outline-secondary me-2">
                        <i class="fas fa-search"></i> Search
                    </a>
                    <a href="<?= APP_URL ?>/pending" class="btn btn-outline-warning">
                        <i class="fas fa-clock"></i> Pending
                    </a>
                    <a href="<?= APP_URL ?>/approved" class="btn btn-outline-success">
                        <i class="fas fa-check-circle"></i> Approved
                    </a>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Statistics Cards -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="stat-card" style="background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <div class="stat-value"><?= count($applications) ?></div>
                        <div class="stat-label">Total Rejected</div>
                    </div>
                    <div class="stat-icon">
                        <i class="fas fa-times-circle"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Filters -->
    <div class="card mb-4">
        <div class="card-header">
            <i class="fas fa-filter"></i> Filter Rejected Applications
        </div>
        <div class="card-body">
            <div class="row">
                <div class="col-md-3 mb-3">
                    <label class="form-label">Date From</label>
                    <input type="date" id="date-from" class="form-control">
                </div>
                <div class="col-md-3 mb-3">
                    <label class="form-label">Date To</label>
                    <input type="date" id="date-to" class="form-control">
                </div>
                <div class="col-md-3 mb-3">
                    <label class="form-label">Nationality</label>
                    <input type="text" id="filter-nationality" class="form-control" placeholder="Filter by nationality">
                </div>
                <div class="col-md-3 mb-3 d-flex align-items-end">
                    <button class="btn btn-nis me-2" onclick="applyFilters()">
                        <i class="fas fa-search"></i> Apply
                    </button>
                    <button class="btn btn-outline-secondary" onclick="resetFilters()">
                        <i class="fas fa-undo"></i> Reset
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Rejected Applications List -->
    <div class="card">
        <div class="card-header">
            <i class="fas fa-list"></i> Rejected Applications List
        </div>
        <div class="card-body">
            <?php if (empty($applications)): ?>
                <div class="text-center py-5">
                    <i class="fas fa-check-circle fa-4x text-success mb-3"></i>
                    <h4>No Rejected Applications</h4>
                    <p class="text-muted">There are no rejected applications to display.</p>
                    <a href="<?= APP_URL ?>/pending" class="btn btn-nis mt-2">
                        <i class="fas fa-clock me-2"></i> View Pending Applications
                    </a>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover" id="rejected-table">
                        <thead>
                            <tr>
                                <th>Person ID</th>
                                <th>Name</th>
                                <th>Document No</th>
                                <th>Nationality</th>
                                <th>Rejected Date</th>
                                <th>Rejected By</th>
                                <th>Rejection Reason</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($applications as $app): ?>
                            <tr class="rejected-row" 
                                data-date="<?= date('Y-m-d', strtotime($app['updated_at'] ?? $app['created_at'])) ?>"
                                data-nationality="<?= htmlspecialchars($app['nationality'] ?? '') ?>">
                                <td><code><?= htmlspecialchars($app['person_id']) ?></code></td>
                                <td>
                                    <strong><?= htmlspecialchars($app['surname'] ?? '') ?></strong>, 
                                    <?= htmlspecialchars($app['given_name'] ?? '') ?>
                                </td>
                                <td><?= htmlspecialchars($app['document_no'] ?? '') ?></td>
                                <td><?= htmlspecialchars($app['nationality'] ?? '') ?></td>
                                <td>
                                    <span class="badge bg-danger">
                                        <i class="fas fa-calendar-alt me-1"></i>
                                        <?= date('d/m/Y H:i', strtotime($app['updated_at'] ?? $app['created_at'])) ?>
                                    </span>
                                </td>
                                <td>
                                    <?php
                                    $reviewerName = 'System';
                                    if (!empty($app['reviewer_name'])) {
                                        $reviewerName = $app['reviewer_name'];
                                    } elseif (!empty($app['reviewed_by'])) {
                                        $reviewerName = 'User ID: ' . $app['reviewed_by'];
                                    }
                                    ?>
                                    <span class="badge bg-secondary">
                                        <i class="fas fa-user me-1"></i>
                                        <?= htmlspecialchars($reviewerName) ?>
                                    </span>
                                </td>
                                <td>
                                    <?php if (!empty($app['remarks'])): ?>
                                        <button type="button" class="btn btn-sm btn-outline-danger" 
                                                onclick="showRejectionReason('<?= htmlspecialchars(addslashes($app['remarks'])) ?>')">
                                            <i class="fas fa-comment"></i> View Reason
                                        </button>
                                    <?php else: ?>
                                        <span class="text-muted">No reason provided</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <div class="btn-group">
                                        <a href="<?= APP_URL ?>/migrants/<?= urlencode($app['person_id']) ?>" 
                                           class="btn btn-sm btn-outline-primary" title="View Details">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        <?php if (in_array($_SESSION['role'] ?? '', ['Admin', 'SuperAdmin'])): ?>
                                        <button type="button" class="btn btn-sm btn-outline-warning" 
                                                onclick="reinstateApplication('<?= $app['person_id'] ?>')"
                                                title="Reinstate as Draft">
                                            <i class="fas fa-undo-alt"></i>
                                        </button>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                
                <!-- Summary -->
                <div class="row mt-4">
                    <div class="col-md-6">
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>
                            <strong>Total Rejected:</strong> <?= count($applications) ?>
                        </div>
                    </div>
                    <div class="col-md-6 text-end">
                        <button class="btn btn-outline-secondary" onclick="exportTableToCSV()">
                            <i class="fas fa-download"></i> Export to CSV
                        </button>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Rejection Reason Modal -->
<div class="modal fade" id="reasonModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">
                    <i class="fas fa-comment me-2"></i> Rejection Reason
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p id="reason-text" class="lead"></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<!-- Reinstate Confirmation Modal -->
<div class="modal fade" id="reinstateModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-warning">
                <h5 class="modal-title">
                    <i class="fas fa-undo-alt me-2"></i> Reinstate Application
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to reinstate this application as DRAFT?</p>
                <p class="text-muted small">The applicant will be able to edit and resubmit.</p>
                
                <form id="reinstate-form" method="POST">
                    <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?? '' ?>">
                    <div class="mb-3">
                        <label class="form-label">Additional Notes (Optional)</label>
                        <textarea name="remarks" class="form-control" rows="2"></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-warning" onclick="confirmReinstate()">
                    <i class="fas fa-undo-alt me-2"></i> Reinstate as Draft
                </button>
            </div>
        </div>
    </div>
</div>

<style>
.stat-card {
    color: white;
    border-radius: 15px;
    padding: 20px;
    height: 100%;
}

.stat-card .stat-value {
    font-size: 2rem;
    font-weight: 700;
    line-height: 1.2;
}

.stat-card .stat-icon {
    font-size: 2.5rem;
    opacity: 0.3;
}

.rejected-row td {
    vertical-align: middle;
}

.btn-group .btn {
    margin-right: 2px;
}

.table th {
    background: #f8f9fa;
    border-bottom: 2px solid #dee2e6;
}
</style>

<script>
let currentPersonId = null;

function showRejectionReason(reason) {
    document.getElementById('reason-text').textContent = reason;
    new bootstrap.Modal(document.getElementById('reasonModal')).show();
}

function reinstateApplication(personId) {
    currentPersonId = personId;
    new bootstrap.Modal(document.getElementById('reinstateModal')).show();
}

function confirmReinstate() {
    if (!currentPersonId) return;
    
    const form = document.getElementById('reinstate-form');
    const remarks = form.querySelector('[name="remarks"]').value;
    
    $.ajax({
        url: '<?= APP_URL ?>/migrants/' + currentPersonId + '/review',
        type: 'POST',
        data: {
            action: 'reinstate',
            remarks: remarks,
            csrf_token: form.querySelector('[name="csrf_token"]').value
        },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                alert('Application reinstated successfully');
                location.reload();
            } else {
                alert('Error: ' + response.error);
            }
        },
        error: function(xhr) {
            alert('Error reinstating application');
        },
        complete: function() {
            bootstrap.Modal.getInstance(document.getElementById('reinstateModal')).hide();
        }
    });
}

function applyFilters() {
    const dateFrom = document.getElementById('date-from').value;
    const dateTo = document.getElementById('date-to').value;
    const nationality = document.getElementById('filter-nationality').value.toLowerCase();
    
    const rows = document.querySelectorAll('.rejected-row');
    
    rows.forEach(row => {
        const rowDate = row.dataset.date;
        const rowNationality = row.dataset.nationality.toLowerCase();
        let show = true;
        
        if (dateFrom && rowDate < dateFrom) show = false;
        if (dateTo && rowDate > dateTo) show = false;
        if (nationality && !rowNationality.includes(nationality)) show = false;
        
        row.style.display = show ? '' : 'none';
    });
}

function resetFilters() {
    document.getElementById('date-from').value = '';
    document.getElementById('date-to').value = '';
    document.getElementById('filter-nationality').value = '';
    
    document.querySelectorAll('.rejected-row').forEach(row => {
        row.style.display = '';
    });
}

function exportTableToCSV() {
    const rows = document.querySelectorAll('#rejected-table tr');
    const csv = [];
    
    for (const row of rows) {
        const cells = row.querySelectorAll('td, th');
        const rowData = [];
        for (const cell of cells) {
            // Skip action buttons column
            if (cell.classList.contains('btn-group')) continue;
            
            let text = cell.innerText.trim();
            // Remove extra whitespace and normalize
            text = text.replace(/\s+/g, ' ').replace(/[^\x20-\x7E]/g, '');
            rowData.push('"' + text.replace(/"/g, '""') + '"');
        }
        csv.push(rowData.join(','));
    }
    
    const csvContent = csv.join('\n');
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    
    link.href = url;
    link.download = 'rejected_applications_' + new Date().toISOString().split('T')[0] + '.csv';
    link.click();
    
    URL.revokeObjectURL(url);
}
</script>