<?php
$page_title = 'HR Verification Dashboard';
require_once __DIR__ . '/../config.php';
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!isset($_SESSION['admin_id'])) { redirect(SITE_URL . '/admin/login.php'); }
require_once __DIR__ . '/header.php';

$db = getDB();

// Fetch Employees dynamically
$stmt = $db->query("
    SELECT e.id, e.name, e.department, e.verification_status, e.emp_code, b.branch_name,
    (SELECT COUNT(*) FROM employee_documents WHERE employee_id = e.id AND status != 'Verified') as missing_docs,
    (SELECT COUNT(*) FROM employee_documents WHERE employee_id = e.id AND status = 'Verified') as verified_docs
    FROM employees e
    LEFT JOIN branches b ON e.branch_id = b.id
    ORDER BY e.id DESC
");
$employees = $stmt->fetchAll(PDO::FETCH_ASSOC);

$status_colors = [
    'Verified' => '#10b981',
    'Under Review' => '#f59e0b',
    'Pending' => '#64748b',
    'Correction Needed' => '#ef4444'
];
?>

<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:24px;">
    <div>
        <h2 style="font-family:'Outfit',sans-serif; font-size:1.8rem; color:#0f172a; margin:0;"><i class="fas fa-user-shield" style="color:#2563eb; margin-right:10px;"></i>HR Verification Dashboard</h2>
        <p style="color:#64748b; font-size:0.95rem; margin-top:5px;">Dynamic module reading directly from employee_documents database via AJAX APIs.</p>
    </div>
    <div style="display:flex; gap:10px;">
        <button style="background:#f8fafc; color:#0f172a; border:1px solid #cbd5e1; padding:8px 16px; border-radius:6px; cursor:pointer;"><i class="fas fa-file-excel"></i> Export CSV</button>
    </div>
</div>

<div class="grid-2" style="grid-template-columns: 1fr 1.5fr; gap:24px;">
    
    <!-- Left Column: Employee List Table -->
    <div class="card" style="padding:0; overflow:hidden;">
        <div style="padding:15px; border-bottom:1px solid #e2e8f0; background:#f8fafc;">
            <h3 style="margin:0; font-size:1.15rem; color:#0f172a;">Employee Queue</h3>
            <input type="text" placeholder="Search by name or EMP ID..." style="width:100%; padding:8px; margin-top:10px; border:1px solid #cbd5e1; border-radius:6px; outline:none;">
        </div>
        <div style="max-height:600px; overflow-y:auto;">
            <table style="width:100%; border-collapse:collapse; font-size:0.85rem;">
                <tbody>
                    <?php foreach ($employees as $e): 
                        $emp_code = $e['emp_code'] ?? 'EMP-'.str_pad($e['id'],4,'0',STR_PAD_LEFT);
                        $v_status = $e['verification_status'] ?? 'Pending';
                        $color = $status_colors[$v_status] ?? '#64748b';
                    ?>
                    <tr onclick="loadEmployeeDocs(<?= $e['id'] ?>)" style="border-bottom:1px solid #f1f5f9; cursor:pointer; transition:background 0.2s;" onmouseover="this.style.background='#f8fafc'" onmouseout="this.style.background='transparent'">
                        <td style="padding:15px;">
                            <div style="display:flex; justify-content:space-between; align-items:flex-start;">
                                <div>
                                    <div style="font-weight:700; color:#0f172a; font-size:0.95rem;"><?= h($e['name']) ?></div>
                                    <div style="font-size:0.75rem; color:#64748b; margin-top:2px;"><?= $emp_code ?> · <?= h($e['department'] ?? 'Office') ?></div>
                                    <div style="font-size:0.7rem; color:#94a3b8; margin-top:2px;"><i class="fas fa-building"></i> <?= h($e['branch_name'] ?? 'Head Office') ?></div>
                                </div>
                                <div style="text-align:right;">
                                    <span style="background:<?= $color ?>15; color:<?= $color ?>; padding:3px 8px; border-radius:4px; font-size:0.7rem; font-weight:700;"><?= $v_status ?></span>
                                    <div style="font-size:0.75rem; color:#ef4444; font-weight:600; margin-top:5px;"><?= $e['missing_docs'] ?> Pending Action</div>
                                </div>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Right Column: Verification Panel (AJAX Target) -->
    <div class="card" id="verificationPanel" style="border-top:4px solid #3b82f6; display:flex; flex-direction:column; align-items:center; justify-content:center; min-height:400px; text-align:center;">
        <i class="fas fa-user-shield" style="font-size:4rem; color:#cbd5e1; margin-bottom:15px;"></i>
        <h3 style="color:#64748b; margin:0;">Select an employee to verify documents</h3>
    </div>
</div>

<script>
let currentDocId = null;

async function loadEmployeeDocs(empId) {
    const panel = document.getElementById('verificationPanel');
    panel.innerHTML = '<i class="fas fa-spinner fa-spin" style="font-size:2rem; color:#3b82f6;"></i><p style="margin-top:10px; color:#64748b;">Fetching records...</p>';
    
    try {
        const response = await fetch(`../api/get-employee-docs.php?id=${empId}`);
        const data = await response.json();
        
        if (!data.success) {
            panel.innerHTML = `<div style="color:#ef4444;"><i class="fas fa-exclamation-triangle"></i> ${data.message}</div>`;
            return;
        }

        renderPanel(data.employee, data.documents);
    } catch (err) {
        panel.innerHTML = `<div style="color:#ef4444;">Network error fetching employee data.</div>`;
    }
}

function renderPanel(emp, docs) {
    let statusColor = '#64748b';
    if(emp.verification_status === 'Verified') statusColor = '#10b981';
    if(emp.verification_status === 'Under Review') statusColor = '#f59e0b';
    if(emp.verification_status === 'Correction Needed') statusColor = '#ef4444';

    let docOptions = '<option value="">-- Select Document --</option>';
    let docsMap = {};
    docs.forEach(d => {
        docsMap[d.doc_id] = d;
        let badge = d.status === 'Verified' ? '✓' : (d.status === 'Submitted' ? '⏳' : '!');
        docOptions += `<option value="${d.doc_id}">${badge} ${d.document_type}</option>`;
    });

    // We store docsMap globally for the dropdown to use
    window.currentEmployeeDocs = docsMap;

    let html = `
        <div style="width:100%; text-align:left;">
            <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:15px; padding-bottom:15px; border-bottom:1px solid #e2e8f0;">
                <div>
                    <div style="font-size:1.2rem; font-weight:700;">${emp.name} <span style="font-size:0.7rem; background:${statusColor}15; color:${statusColor}; padding:2px 6px; border-radius:4px;">${emp.verification_status || 'Pending'}</span></div>
                    <div style="font-size:0.85rem; color:#64748b;">${emp.emp_code} · ${emp.department || 'Office'} · ${emp.branch_name}</div>
                </div>
                <select id="docSelect" onchange="previewDocument(this.value)" style="padding:8px 12px; border:1px solid #cbd5e1; border-radius:6px; outline:none; font-weight:600; min-width:200px; background:#f8fafc;">
                    ${docOptions}
                </select>
            </div>

            <div id="docPreviewContainer" style="display:none;">
                <div style="display:grid; grid-template-columns: 1.5fr 1fr; gap:20px; margin-bottom:20px;">
                    <!-- Document Preview -->
                    <div>
                        <div id="pdfViewer" style="background:#f1f5f9; height:350px; border-radius:8px; border:1px solid #cbd5e1; display:flex; align-items:center; justify-content:center; flex-direction:column; position:relative; overflow:hidden;">
                            <!-- Will be injected by JS -->
                        </div>
                        <a id="downloadBtn" href="#" target="_blank" style="display:block; text-align:center; margin-top:10px; background:#f8fafc; color:#2563eb; border:1px solid #bfdbfe; padding:8px; border-radius:6px; text-decoration:none; font-size:0.85rem; font-weight:600;"><i class="fas fa-external-link-alt"></i> Open Full File</a>
                    </div>

                    <!-- OCR & Actions -->
                    <div style="display:flex; flex-direction:column; gap:15px;">
                        <div style="background:#f8fafc; padding:12px; border-radius:8px; border:1px solid #e2e8f0;">
                            <div style="font-size:0.75rem; font-weight:700; color:#64748b; margin-bottom:8px; text-transform:uppercase;"><i class="fas fa-info-circle"></i> Document Details</div>
                            <div style="font-size:0.85rem; margin-bottom:5px;">Type: <strong id="detType"></strong></div>
                            <div style="font-size:0.85rem; margin-bottom:5px;">ID/Number: <strong id="detNum"></strong></div>
                            <div style="font-size:0.85rem; margin-bottom:5px;">Status: <strong id="detStatus"></strong></div>
                            <div style="font-size:0.85rem; color:#64748b;">Uploaded: <span id="detDate"></span></div>
                        </div>

                        <div style="margin-bottom:5px;">
                            <label style="display:block; font-size:0.8rem; font-weight:600; margin-bottom:5px; color:#475569;">HR Remarks (Visible to Employee)</label>
                            <textarea id="hrRemarks" style="width:100%; padding:10px; border:1px solid #cbd5e1; border-radius:6px; outline:none; resize:none; font-family:inherit; font-size:0.85rem;" rows="3" placeholder="Add rejection reasons or approval notes here..."></textarea>
                        </div>

                        <div style="display:grid; grid-template-columns: 1fr 1fr; gap:10px;">
                            <button onclick="verifyDoc('Approve')" style="background:#10b981; color:#fff; border:none; padding:10px; border-radius:6px; cursor:pointer; font-weight:600; font-size:0.85rem;"><i class="fas fa-check"></i> Approve</button>
                            <button onclick="verifyDoc('Reject')" style="background:#ef4444; color:#fff; border:none; padding:10px; border-radius:6px; cursor:pointer; font-weight:600; font-size:0.85rem;"><i class="fas fa-times"></i> Reject</button>
                            <button onclick="verifyDoc('Correction')" style="background:#f59e0b; color:#fff; border:none; padding:10px; border-radius:6px; cursor:pointer; font-weight:600; font-size:0.85rem; grid-column:span 2;"><i class="fas fa-redo"></i> Request Correction</button>
                        </div>
                    </div>
                </div>
            </div>

            <div id="noDocSelected" style="text-align:center; padding:40px; color:#94a3b8;">
                <i class="fas fa-file-alt" style="font-size:3rem; margin-bottom:10px;"></i>
                <p>Select a document from the dropdown to review.</p>
            </div>
        </div>
    `;

    const panel = document.getElementById('verificationPanel');
    panel.innerHTML = html;
    
    // Auto-select first document if available
    if(docs.length > 0) {
        document.getElementById('docSelect').value = docs[0].doc_id;
        previewDocument(docs[0].doc_id);
    }
}

function previewDocument(docId) {
    if (!docId) {
        document.getElementById('docPreviewContainer').style.display = 'none';
        document.getElementById('noDocSelected').style.display = 'block';
        currentDocId = null;
        return;
    }

    const doc = window.currentEmployeeDocs[docId];
    currentDocId = docId;

    document.getElementById('noDocSelected').style.display = 'none';
    document.getElementById('docPreviewContainer').style.display = 'block';

    // Populate Details
    document.getElementById('detType').innerText = doc.document_type;
    document.getElementById('detNum').innerText = doc.document_number || 'N/A';
    document.getElementById('detStatus').innerText = doc.status;
    
    let statusColor = '#64748b';
    if(doc.status === 'Verified') statusColor = '#10b981';
    if(doc.status === 'Submitted') statusColor = '#3b82f6';
    if(doc.status === 'Rejected' || doc.status === 'Correction Needed') statusColor = '#ef4444';
    document.getElementById('detStatus').style.color = statusColor;

    document.getElementById('detDate').innerText = doc.uploaded_at;
    document.getElementById('hrRemarks').value = doc.remarks || '';

    // File Preview Logic
    const viewer = document.getElementById('pdfViewer');
    const fileUrl = `../uploads/documents/${doc.file_url}`;
    document.getElementById('downloadBtn').href = fileUrl;

    if (doc.file_url.toLowerCase().endsWith('.pdf')) {
        viewer.innerHTML = `<iframe src="${fileUrl}" style="width:100%; height:100%; border:none;"></iframe>`;
    } else {
        viewer.innerHTML = `<img src="${fileUrl}" style="max-width:100%; max-height:100%; object-fit:contain;">`;
    }
}

async function verifyDoc(action) {
    if (!currentDocId) return;
    
    const remarks = document.getElementById('hrRemarks').value;
    
    try {
        const response = await fetch('../api/verify-document.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                doc_id: currentDocId,
                action: action,
                remarks: remarks
            })
        });
        
        const result = await response.json();
        if (result.success) {
            // Update local state
            window.currentEmployeeDocs[currentDocId].status = result.new_status;
            window.currentEmployeeDocs[currentDocId].remarks = remarks;
            
            // Re-render preview to show new status
            previewDocument(currentDocId);
            
            // Show toast/alert
            alert(result.message);
        } else {
            alert('Error: ' + result.message);
        }
    } catch (err) {
        alert('Network error occurred.');
    }
}
</script>

<?php require_once __DIR__ . '/footer.php'; ?>
