<?php
$page_title = 'My Documents';
require_once __DIR__ . '/header.php';

// Ensure uploads directory exists
$upload_dir = __DIR__ . '/../uploads/documents/';
if (!is_dir($upload_dir)) { mkdir($upload_dir, 0777, true); }

// Fetch user's documents from DB
$stmt = $db->prepare("SELECT * FROM employee_documents WHERE employee_id = ?");
$stmt->execute([$emp_id]);
$db_docs = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Helper function to find a doc in DB results
function getDoc($db_docs, $type) {
    foreach ($db_docs as $d) {
        if ($d['document_type'] === $type) return $d;
    }
    return null;
}

// Define the exact categories requested
$doc_categories = [
    'Identity' => [
        ['type' => 'Aadhaar Card', 'icon' => 'fas fa-id-card'],
        ['type' => 'PAN Card', 'icon' => 'fas fa-credit-card'],
        ['type' => 'Passport Size Photo', 'icon' => 'fas fa-camera'],
        ['type' => 'Signature', 'icon' => 'fas fa-pen-fancy'],
    ],
    'Address' => [
        ['type' => 'Address Proof', 'icon' => 'fas fa-map-marker-alt'],
    ],
    'Banking' => [
        ['type' => 'Bank Passbook', 'icon' => 'fas fa-university'],
        ['type' => 'Cancelled Cheque', 'icon' => 'fas fa-money-check'],
    ],
    'Education' => [
        ['type' => '10th Certificate', 'icon' => 'fas fa-certificate'],
        ['type' => '12th Certificate', 'icon' => 'fas fa-certificate'],
        ['type' => 'Diploma / Degree', 'icon' => 'fas fa-graduation-cap'],
        ['type' => 'Skill Certificate', 'icon' => 'fas fa-star'],
    ],
    'Employment' => [
        ['type' => 'Resume', 'icon' => 'fas fa-file-alt'],
        ['type' => 'Experience Letter', 'icon' => 'fas fa-briefcase'],
        ['type' => 'Offer Letter', 'icon' => 'fas fa-envelope-open-text'],
        ['type' => 'Joining Letter', 'icon' => 'fas fa-file-signature'],
    ],
    'Compliance' => [
        ['type' => 'Police Verification', 'icon' => 'fas fa-shield-alt'],
        ['type' => 'Medical Fitness', 'icon' => 'fas fa-heartbeat'],
        ['type' => 'PF / UAN Form', 'icon' => 'fas fa-piggy-bank'],
        ['type' => 'ESIC Form', 'icon' => 'fas fa-hospital'],
    ],
];

// Combine definitions with DB data
$all_docs = [];
$verified_count = 0;
$total_required = 0;

foreach ($doc_categories as $cat => &$docs) {
    foreach ($docs as &$d) {
        $total_required++;
        $db_entry = getDoc($db_docs, $d['type']);
        if ($db_entry) {
            $d['status'] = $db_entry['status'];
            $d['file_url'] = $db_entry['file_url'];
            $d['uploaded_at'] = date('d M Y', strtotime($db_entry['uploaded_at']));
            $d['doc_id'] = $db_entry['doc_id'];
            if ($d['status'] === 'Verified') $verified_count++;
        } else {
            $d['status'] = 'Pending Upload';
            $d['file_url'] = '';
            $d['uploaded_at'] = '';
            $d['doc_id'] = '';
        }
        $all_docs[] = $d;
    }
}

$progress = $total_required > 0 ? round(($verified_count / $total_required) * 100) : 0;

$status_map = [
    'Verified' => ['#10b981', '#dcfce7', '#166534', 'fas fa-check-circle'],
    'Submitted' => ['#3b82f6', '#dbeafe', '#1e40af', 'fas fa-paper-plane'],
    'Under Review' => ['#f59e0b', '#fef3c7', '#b45309', 'fas fa-clock'],
    'Correction Needed' => ['#ef4444', '#fee2e2', '#991b1b', 'fas fa-exclamation-triangle'],
    'Rejected' => ['#ef4444', '#fee2e2', '#991b1b', 'fas fa-times-circle'],
    'Pending Upload' => ['#94a3b8', '#f1f5f9', '#475569', 'fas fa-upload'],
    'Expired' => ['#ef4444', '#fee2e2', '#991b1b', 'fas fa-calendar-times'],
];
?>

<!-- Profile Header & Progress -->
<div class="card" style="display:flex; align-items:center; gap:30px; margin-bottom:24px; background:linear-gradient(135deg,#0a1f4e,#1e3a7a); color:#fff; border:none;">
    <div style="width:80px; height:80px; border-radius:50%; background:#2563eb; display:flex; align-items:center; justify-content:center; font-size:2rem; font-weight:bold; border:3px solid #fff; flex-shrink:0;">
        <?= strtoupper(substr($emp['name'],0,1)) ?>
    </div>
    <div style="flex:1;">
        <h2 style="margin:0 0 5px; font-family:'Outfit',sans-serif; font-size:1.6rem;"><?= h($emp['name']) ?></h2>
        <div style="display:flex; gap:20px; font-size:0.9rem; color:#cbd5e1; margin-bottom:15px;">
            <span><i class="fas fa-id-badge"></i> <?= h($_SESSION['emp_code']) ?></span>
            <span><i class="fas fa-building"></i> <?= h($dept) ?></span>
            <span><i class="fas fa-calendar-alt"></i> Joined: <?= date('d M Y', strtotime($emp['joining_date'] ?? '2024-04-01')) ?></span>
            <span style="color:#10b981; font-weight:bold;"><i class="fas fa-check-circle"></i> Verification Status: <?= $emp['verification_status'] ?? 'Pending' ?></span>
        </div>
        <div style="display:flex; align-items:center; gap:15px;">
            <div style="flex:1; background:rgba(255,255,255,0.15); height:8px; border-radius:4px; overflow:hidden;">
                <div style="width:<?= $progress ?>%; height:100%; background:linear-gradient(90deg,#10b981,#34d399); border-radius:4px;"></div>
            </div>
            <span style="font-weight:bold; font-size:1.1rem; color:#34d399;"><?= $progress ?>% Verified</span>
        </div>
    </div>
</div>

<div class="grid-3" style="gap:24px; align-items:start;">
    
    <!-- Left Column: Document Categories -->
    <div style="grid-column: span 2; display:flex; flex-direction:column; gap:24px;">
        <?php foreach ($doc_categories as $cat_name => $docs): ?>
        <div class="card" style="margin-bottom:0;">
            <h3 style="margin:0 0 20px; font-size:1.15rem; color:#0f172a; border-bottom:1px solid #e2e8f0; padding-bottom:10px;">
                <i class="fas fa-folder-open" style="color:#3b82f6; margin-right:8px;"></i> <?= $cat_name ?>
            </h3>
            <div style="display:grid; grid-template-columns:1fr 1fr; gap:15px;">
                <?php foreach ($docs as $d):
                    $st = $status_map[$d['status']];
                    $has_file = !empty($d['file_url']);
                ?>
                <div style="border:1px solid #e2e8f0; border-radius:10px; padding:15px; border-left:4px solid <?= $st[0] ?>; position:relative;">
                    <span style="position:absolute; top:15px; right:15px; background:<?= $st[1] ?>; color:<?= $st[2] ?>; padding:3px 8px; border-radius:6px; font-size:0.65rem; font-weight:bold;">
                        <?= $d['status'] ?>
                    </span>
                    <div style="display:flex; align-items:center; gap:12px; margin-bottom:12px;">
                        <div style="width:40px; height:40px; border-radius:8px; background:<?= $st[0] ?>15; display:flex; align-items:center; justify-content:center; font-size:1.1rem; color:<?= $st[0] ?>;">
                            <i class="<?= $d['icon'] ?>"></i>
                        </div>
                        <div>
                            <div style="font-weight:600; font-size:0.9rem; color:#0f172a; padding-right:70px;"><?= $d['type'] ?></div>
                            <?php if ($has_file): ?>
                                <div style="font-size:0.75rem; color:#64748b; margin-top:2px;">
                                    <i class="fas fa-file" style="color:#ef4444;"></i> <?= basename($d['file_url']) ?>
                                </div>
                            <?php else: ?>
                                <div style="font-size:0.75rem; color:#94a3b8; margin-top:2px;">Missing Document</div>
                            <?php endif; ?>
                        </div>
                    </div>
                    
                    <div style="display:flex; gap:8px;">
                        <?php if ($d['status'] === 'Pending Upload' || $d['status'] === 'Correction Needed'): ?>
                            <button onclick="openUploadModal('<?= $cat_name ?>', '<?= $d['type'] ?>')" style="flex:1; padding:6px; background:#2563eb; color:#fff; border:none; border-radius:6px; font-size:0.75rem; cursor:pointer; font-weight:600;">
                                <i class="fas fa-upload"></i> Upload
                            </button>
                        <?php else: ?>
                            <a href="<?= SITE_URL ?>/uploads/documents/<?= $d['file_url'] ?>" target="_blank" style="flex:1; text-align:center; padding:6px; background:#f8fafc; color:#475569; border:1px solid #e2e8f0; border-radius:6px; font-size:0.75rem; cursor:pointer; text-decoration:none;">
                                <i class="fas fa-eye"></i> Preview
                            </a>
                            <button onclick="openUploadModal('<?= $cat_name ?>', '<?= $d['type'] ?>')" style="flex:1; padding:6px; background:#f8fafc; color:#475569; border:1px solid #e2e8f0; border-radius:6px; font-size:0.75rem; cursor:pointer;">
                                <i class="fas fa-sync"></i> Replace
                            </button>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

    <!-- Right Column: Upload Features & Status -->
    <div style="display:flex; flex-direction:column; gap:24px;">
        
        <!-- Auto Checks Status -->
        <div class="card">
            <h3 style="margin:0 0 15px; font-size:1.1rem; color:#0f172a;"><i class="fas fa-shield-check" style="color:#8b5cf6; margin-right:8px;"></i>System Validation</h3>
            <?php
            $checks = [
                ['Aadhaar Format Check', true, '#10b981'],
                ['PAN Format Check', true, '#10b981'],
                ['Bank IFSC Validation', false, '#ef4444'],
                ['Name Match Verification', true, '#10b981'],
                ['File Size Compliance (10MB)', true, '#10b981'],
                ['Malware / Virus Scan', true, '#10b981'],
            ];
            foreach ($checks as $c): ?>
            <div style="display:flex; align-items:center; gap:10px; padding:8px 0; border-bottom:1px solid #f1f5f9;">
                <i class="fas <?= $c[1] ? 'fa-check-circle' : 'fa-exclamation-circle' ?>" style="color:<?= $c[2] ?>;"></i>
                <span style="font-size:0.85rem; color:<?= $c[1] ? '#0f172a' : $c[2] ?>; font-weight:<?= $c[1] ? '400' : '600' ?>;"><?= $c[0] ?></span>
            </div>
            <?php endforeach; ?>
        </div>

        <button style="width:100%; padding:12px; background:#0f172a; color:#fff; border:none; border-radius:8px; font-size:0.95rem; cursor:pointer; font-weight:700;"><i class="fas fa-paper-plane"></i> Submit For Final HR Review</button>

    </div>
</div>

<!-- Upload Modal -->
<div id="uploadModal" style="display:none; position:fixed; inset:0; background:rgba(0,0,0,0.5); z-index:1000; align-items:center; justify-content:center;">
    <div style="background:#fff; width:100%; max-width:500px; border-radius:12px; padding:24px; box-shadow:0 10px 25px rgba(0,0,0,0.2);">
        <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px;">
            <h3 style="margin:0; font-size:1.2rem; color:#0f172a;">Upload Document</h3>
            <button onclick="closeUploadModal()" style="background:none; border:none; font-size:1.2rem; cursor:pointer; color:#64748b;"><i class="fas fa-times"></i></button>
        </div>
        
        <form id="uploadForm" onsubmit="handleUpload(event)">
            <input type="hidden" id="uploadCategory" name="category">
            <input type="hidden" id="uploadType" name="document_type">
            
            <div style="margin-bottom:15px;">
                <label style="display:block; font-size:0.85rem; font-weight:600; margin-bottom:5px;">Document Type</label>
                <input type="text" id="uploadTypeDisplay" readonly style="width:100%; padding:10px; background:#f1f5f9; border:1px solid #cbd5e1; border-radius:6px; color:#475569; font-weight:600; outline:none;">
            </div>
            
            <div style="margin-bottom:15px;">
                <label style="display:block; font-size:0.85rem; font-weight:600; margin-bottom:5px;">Document Number / ID (Optional)</label>
                <input type="text" name="document_number" placeholder="e.g. Aadhaar Number, PAN Number" style="width:100%; padding:10px; border:1px solid #cbd5e1; border-radius:6px; outline:none; font-size:0.9rem;">
            </div>
            
            <div style="border:2px dashed #3b82f6; border-radius:8px; padding:30px; text-align:center; background:#eff6ff; margin-bottom:20px; cursor:pointer;" onclick="document.getElementById('fileInput').click()">
                <i class="fas fa-cloud-upload-alt" style="font-size:3rem; color:#3b82f6; margin-bottom:10px;"></i>
                <div style="font-weight:600; color:#1e40af; margin-bottom:5px;">Click to Browse or Drag File Here</div>
                <div style="font-size:0.75rem; color:#64748b;">Supported: PDF, JPG, PNG (Max 10MB)</div>
                <input type="file" id="fileInput" name="document_file" style="display:none;" accept=".pdf,.jpg,.jpeg,.png" onchange="document.getElementById('fileName').innerText = this.files[0].name">
                <div id="fileName" style="margin-top:10px; font-weight:600; color:#10b981; font-size:0.85rem;"></div>
            </div>
            
            <div style="margin-bottom:20px;">
                <label style="display:flex; align-items:center; gap:8px; font-size:0.85rem; cursor:pointer;">
                    <input type="checkbox" required style="accent-color:#2563eb; width:16px; height:16px;">
                    I confirm this document is authentic and digitally sign this submission.
                </label>
            </div>
            
            <button type="submit" id="submitBtn" style="width:100%; padding:12px; background:#2563eb; color:#fff; border:none; border-radius:8px; font-weight:700; cursor:pointer; font-size:1rem;"><i class="fas fa-upload"></i> Secure Upload</button>
        </form>
    </div>
</div>

<script>
function openUploadModal(category, type) {
    document.getElementById('uploadCategory').value = category;
    document.getElementById('uploadType').value = type;
    document.getElementById('uploadTypeDisplay').value = type;
    document.getElementById('uploadModal').style.display = 'flex';
}

function closeUploadModal() {
    document.getElementById('uploadModal').style.display = 'none';
    document.getElementById('uploadForm').reset();
    document.getElementById('fileName').innerText = '';
}

async function handleUpload(e) {
    e.preventDefault();
    const btn = document.getElementById('submitBtn');
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Uploading...';
    btn.disabled = true;
    
    const formData = new FormData(e.target);
    
    try {
        const response = await fetch('../api/upload-document.php', {
            method: 'POST',
            body: formData
        });
        const result = await response.json();
        
        if (result.success) {
            alert('Document uploaded successfully!');
            location.reload();
        } else {
            alert('Error: ' + result.message);
            btn.innerHTML = '<i class="fas fa-upload"></i> Secure Upload';
            btn.disabled = false;
        }
    } catch (err) {
        alert('Network Error. Please try again.');
        btn.innerHTML = '<i class="fas fa-upload"></i> Secure Upload';
        btn.disabled = false;
    }
}
</script>

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