<?php
define('SECURE_ACCESS', true);

$pageTitle = "KYC & Bank Account Verification";
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

requireLogin();

$currentUser = getCurrentUser();

$error = '';
$success = '';

// Create uploads directory if it doesn't exist
$upload_dir = __DIR__ . '/uploads/kyc_documents';
if (!is_dir($upload_dir)) {
    mkdir($upload_dir, 0777, true);
}

// Fetch existing KYC details
$kyc = null;
try {
    $stmt = $pdo->prepare("SELECT * FROM kyc_records WHERE user_id = ?");
    $stmt->execute([$currentUser['id']]);
    $kyc = $stmt->fetch();
} catch (PDOException $e) {
    $error = "Failed to load KYC record: " . $e->getMessage();
}

// Fetch bank micro-deposit settings for display/verification
try {
    $stmt_min = $pdo->query("SELECT value FROM system_settings WHERE key = 'bank_verification_min_deposit'");
    $min_dep = (float)($stmt_min ? $stmt_min->fetchColumn() : 1.01);

    $stmt_max = $pdo->query("SELECT value FROM system_settings WHERE key = 'bank_verification_max_deposit'");
    $max_dep = (float)($stmt_max ? $stmt_max->fetchColumn() : 1.99);
} catch (PDOException $e) {
    $min_dep = 1.01;
    $max_dep = 1.99;
}

// 1. Handle Document & Bank Account Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_kyc'])) {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $_SESSION['flash_error'] = "Security check failed (CSRF). Please try again.";
        header("Location: kyc");
        exit();
    }
    $doc1_type = 'Aadhaar Card';
    $doc1_number = trim($_POST['doc1_number'] ?? '');
    $doc2_type = 'PAN Card';
    $doc2_number = trim($_POST['doc2_number'] ?? '');
    $bank_name = trim($_POST['bank_name'] ?? '');
    $account_holder = trim($_POST['account_holder'] ?? '');
    $account_number = trim($_POST['account_number'] ?? '');
    $routing_number = strtoupper(trim($_POST['routing_number'] ?? '')); // IFSC Code

    $doc1_file = $kyc['doc1_file'] ?? '';
    $doc2_file = $kyc['doc2_file'] ?? '';

    // Secure File Upload Helper
    function processKycUpload($fileInputName, $upload_dir) {
        if (isset($_FILES[$fileInputName]) && $_FILES[$fileInputName]['error'] === UPLOAD_ERR_OK) {
            $tmp_name = $_FILES[$fileInputName]['tmp_name'];
            $original_name = $_FILES[$fileInputName]['name'];
            $ext = strtolower(pathinfo($original_name, PATHINFO_EXTENSION));
            
            // 1. Strict Extension Whitelist
            $allowed_exts = ['jpg', 'jpeg', 'png', 'pdf'];
            if (!in_array($ext, $allowed_exts)) return false;
            
            // 2. Strict MIME Type Validation
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $mime = finfo_file($finfo, $tmp_name);
            finfo_close($finfo);
            
            $allowed_mimes = ['image/jpeg', 'image/png', 'application/pdf'];
            if (!in_array($mime, $allowed_mimes)) return false;
            
            // 3. Secure Random Filename Generation
            $filename = bin2hex(random_bytes(16)) . '.' . $ext;
            if (move_uploaded_file($tmp_name, $upload_dir . '/' . $filename)) {
                return 'uploads/kyc_documents/' . $filename;
            }
        }
        return false;
    }

    // Process Uploads (Only if they provide a new file)
    $uploaded_doc1 = processKycUpload('doc1_file', $upload_dir);
    if ($uploaded_doc1) $doc1_file = $uploaded_doc1;
    
    $uploaded_doc2 = processKycUpload('doc2_file', $upload_dir);
    if ($uploaded_doc2) $doc2_file = $uploaded_doc2;

    // Validation checks
    if (empty($doc1_file) || empty($doc2_file) || empty($doc1_number) || empty($doc2_number)) {
        $error = "Please upload both Aadhaar Card and PAN Card verification documents and enter their numbers.";
    } elseif (empty($bank_name) || empty($account_holder) || empty($account_number) || empty($routing_number)) {
        $error = "Please fill in all bank account details.";
    } elseif (!preg_match('/^[0-9]{12}$/', $doc1_number)) {
        $error = "Aadhaar Card number must be exactly 12 numeric digits.";
    } elseif (!preg_match('/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/i', $doc2_number)) {
        $error = "PAN Card ID must be a valid 10-character alphanumeric ID matching format (e.g. ABCDE1234F).";
    } elseif (!preg_match('/^[A-Z]{4}0[A-Z0-9]{6}$/i', $routing_number)) {
        $error = "Invalid Bank IFSC Code format. Must be 11 characters starting with 4 letters, then 0, and 6 digits/characters (e.g. SBIN0001234).";
    } else {

        $min_cents = (int)round($min_dep * 100);
        $max_cents = (int)round($max_dep * 100);

        $deposit_1 = rand($min_cents, $max_cents) / 100.0;
        $deposit_2 = rand($min_cents, $max_cents) / 100.0;
        $bank_status = 'initiated';
        $deposit_expiry = date('Y-m-d H:i:s', strtotime('+48 hours'));

        try {
            if ($kyc) {
                // Update existing record
                $stmt = $pdo->prepare("
                    UPDATE kyc_records 
                    SET doc1_type = ?, doc1_number = ?, doc1_file = ?, doc1_status = 'pending',
                        doc2_type = ?, doc2_number = ?, doc2_file = ?, doc2_status = 'pending',
                        bank_name = ?, account_holder = ?, account_number = ?, routing_number = ?,
                        deposit_1 = ?, deposit_2 = ?, bank_status = ?, deposit_expires_at = ?, updated_at = CURRENT_TIMESTAMP
                    WHERE user_id = ?
                ");
                $stmt->execute([
                    $doc1_type, $doc1_number, $doc1_file,
                    $doc2_type, $doc2_number, $doc2_file,
                    $bank_name, $account_holder, $account_number, $routing_number,
                    $deposit_1, $deposit_2, $bank_status, $deposit_expiry, $currentUser['id']
                ]);
            } else {
                // Insert new record
                $stmt = $pdo->prepare("
                    INSERT INTO kyc_records (user_id, doc1_type, doc1_number, doc1_file, doc2_type, doc2_number, doc2_file, bank_name, account_holder, account_number, routing_number, deposit_1, deposit_2, bank_status, deposit_expires_at)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ");
                $stmt->execute([
                    $currentUser['id'], $doc1_type, $doc1_number, $doc1_file, $doc2_type, $doc2_number, $doc2_file,
                    $bank_name, $account_holder, $account_number, $routing_number,
                    $deposit_1, $deposit_2, $bank_status, $deposit_expiry
                ]);
            }
            
            $_SESSION['flash_success'] = "Indian KYC details saved and micro-deposit bank account verification initiated! Check transaction logs below.";
            header("Location: kyc");
            exit();
        } catch (PDOException $e) {
            $error = "Database failed to save KYC: " . $e->getMessage();
        }
    }
}

// 2. Handle PayPal Micro-Deposit Verification
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['verify_deposits'])) {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $_SESSION['flash_error'] = "Security check failed (CSRF). Please try again.";
        header("Location: kyc");
        exit();
    }
    $entered_1 = (float)($_POST['deposit_1'] ?? 0.00);
    $entered_2 = (float)($_POST['deposit_2'] ?? 0.00);

    if ($kyc && $kyc['bank_status'] === 'initiated') {
        if (!empty($kyc['deposit_expires_at']) && strtotime($kyc['deposit_expires_at']) < time()) {
            $error = "The verification session has expired. Please re-submit your bank details to get new verification amounts.";
        } else {
            $real_1 = (float)$kyc['deposit_1'];
            $real_2 = (float)$kyc['deposit_2'];

            if (($entered_1 === $real_1 && $entered_2 === $real_2) || ($entered_1 === $real_2 && $entered_2 === $real_1)) {
                try {
                    $stmt = $pdo->prepare("UPDATE kyc_records SET bank_status = 'verified', updated_at = CURRENT_TIMESTAMP WHERE user_id = ?");
                    $stmt->execute([$currentUser['id']]);
                    $_SESSION['flash_success'] = "Bank account verified successfully! Micro-deposits matched.";
                    header("Location: kyc");
                    exit();
                } catch (PDOException $e) {
                    $error = "Failed to update bank verification status: " . $e->getMessage();
                }
            } else {
                $error = "Verification failed. The micro-deposit amounts entered do not match our records.";
            }
        }
    }
}

// Reload KYC details for display
try {
    $stmt = $pdo->prepare("SELECT * FROM kyc_records WHERE user_id = ?");
    $stmt->execute([$currentUser['id']]);
    $kyc = $stmt->fetch();
} catch (PDOException $e) {
    // Ignore
}

include __DIR__ . '/../includes/header.php';
?>

<div class="d-flex flex-column flex-md-row justify-content-between align-items-md-center gap-3 mb-4">
    <div>
        <h1 class="h2 fw-bold text-dark mb-1">Indian KYC & Bank Verification</h1>
        <p class="text-muted mb-0">Provide Aadhaar, PAN card documentation and verify your Indian bank account using IFSC codes.</p>
    </div>
</div>

<?php if (!empty($error)): ?>
    <div class="alert alert-danger alert-dismissible fade show shadow-sm border-0 mb-4" role="alert">
        <i class="bi bi-x-circle-fill me-2"></i>
        <?php echo htmlspecialchars($error); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<div class="row g-4">
    <!-- Left Column: Verification Forms -->
    <div class="col-12 col-lg-8">
        <?php if (!$kyc || $kyc['bank_status'] === 'unverified'): ?>
            <!-- Form Card: Upload Docs & Bank Details -->
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-white border-bottom py-3">
                    <h5 class="mb-0 fw-bold text-dark"><i class="bi bi-shield-lock me-2 text-primary"></i>1. Indian Compliance Verification Forms</h5>
                </div>
                <div class="card-body p-4">
                    <form method="POST" action="kyc" enctype="multipart/form-data">
                        <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                        
                        <!-- Documents Upload -->
                        <h6 class="fw-bold mb-3 text-secondary uppercase font-monospace" style="font-size: 0.8rem;">Required KYC Identification</h6>
                        <div class="row g-3 mb-4">
                            <!-- Document 1: Aadhaar Card -->
                            <div class="col-12 col-md-6">
                                <label for="doc1_number" class="form-label fw-bold small">Aadhaar Card Number (12 Digits) <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="doc1_number" name="doc1_number" placeholder="e.g. 543210987654" required value="<?php echo htmlspecialchars($kyc['doc1_number'] ?? ''); ?>">
                                <label class="form-label mt-2 small">Upload Aadhaar Card Scan <span class="text-danger">*</span></label>
                                
                                <div class="drop-zone border rounded p-3 text-center position-relative mb-1" id="drop-zone-doc1" style="border: 2px dashed #dee2e6 !important; cursor: pointer; transition: all 0.2s; background: #f8f9fa;">
                                    <i class="bi bi-cloud-arrow-up fs-3 text-secondary" id="icon-doc1"></i>
                                    <p class="small text-secondary mb-1 mt-2" id="text-doc1">
                                        <?php if(isset($kyc['doc1_file'])): ?>
                                            <span class="text-success"><i class="bi bi-check-circle-fill"></i> File uploaded</span>
                                            (<a href="download/<?php echo urlencode(basename($kyc['doc1_file'])); ?>" target="_blank" class="text-primary text-decoration-none fw-bold" onclick="event.stopPropagation();">View File</a>)<br>Click to replace
                                        <?php else: ?>
                                            Drag & drop image/pdf here<br>or click to browse
                                        <?php endif; ?>
                                    </p>
                                    <input type="file" class="form-control" id="doc1_file" name="doc1_file" accept=".jpg,.jpeg,.png,.pdf" <?php echo isset($kyc['doc1_file']) ? '' : 'required'; ?> style="opacity: 0; position: absolute; top: 0; left: 0; width: 100%; height: 100%; cursor: pointer;">
                                </div>
                                <span class="small text-muted font-monospace d-block mt-1">Upload front and back scan.</span>
                                
                                <?php if(isset($kyc['doc1_status'])): ?>
                                    <div class="mt-2">
                                        <span class="badge <?php echo $kyc['doc1_status'] === 'approved' ? 'bg-success' : ($kyc['doc1_status'] === 'rejected' ? 'bg-danger' : 'bg-warning text-dark'); ?>">
                                            Status: <?php echo ucfirst($kyc['doc1_status']); ?>
                                        </span>
                                    </div>
                                <?php endif; ?>
                            </div>
                            
                            <!-- Document 2: PAN Card -->
                            <div class="col-12 col-md-6">
                                <label for="doc2_number" class="form-label fw-bold small">PAN Card ID (10 Characters) <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="doc2_number" name="doc2_number" placeholder="e.g. ABCDE1234F" style="text-transform: uppercase;" required value="<?php echo htmlspecialchars($kyc['doc2_number'] ?? ''); ?>">
                                <label class="form-label mt-2 small">Upload PAN Card Scan <span class="text-danger">*</span></label>
                                
                                <div class="drop-zone border rounded p-3 text-center position-relative mb-1" id="drop-zone-doc2" style="border: 2px dashed #dee2e6 !important; cursor: pointer; transition: all 0.2s; background: #f8f9fa;">
                                    <i class="bi bi-cloud-arrow-up fs-3 text-secondary" id="icon-doc2"></i>
                                    <p class="small text-secondary mb-1 mt-2" id="text-doc2">
                                        <?php if(isset($kyc['doc2_file'])): ?>
                                            <span class="text-success"><i class="bi bi-check-circle-fill"></i> File uploaded</span>
                                            (<a href="download/<?php echo urlencode(basename($kyc['doc2_file'])); ?>" target="_blank" class="text-primary text-decoration-none fw-bold" onclick="event.stopPropagation();">View File</a>)<br>Click to replace
                                        <?php else: ?>
                                            Drag & drop image/pdf here<br>or click to browse
                                        <?php endif; ?>
                                    </p>
                                    <input type="file" class="form-control" id="doc2_file" name="doc2_file" accept=".jpg,.jpeg,.png,.pdf" <?php echo isset($kyc['doc2_file']) ? '' : 'required'; ?> style="opacity: 0; position: absolute; top: 0; left: 0; width: 100%; height: 100%; cursor: pointer;">
                                </div>
                                <span class="small text-muted font-monospace d-block mt-1">Must show name, birth date and signature.</span>
                                
                                <?php if(isset($kyc['doc2_status'])): ?>
                                    <div class="mt-2">
                                        <span class="badge <?php echo $kyc['doc2_status'] === 'approved' ? 'bg-success' : ($kyc['doc2_status'] === 'rejected' ? 'bg-danger' : 'bg-warning text-dark'); ?>">
                                            Status: <?php echo ucfirst($kyc['doc2_status']); ?>
                                        </span>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Bank Details -->
                        <h6 class="fw-bold mb-3 text-secondary uppercase font-monospace" style="font-size: 0.8rem;">Indian Bank Account Details</h6>
                        <div class="row g-3 mb-4">
                            <div class="col-12 col-md-6">
                                <label for="bank_name" class="form-label">Bank Name <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="bank_name" name="bank_name" placeholder="e.g. State Bank of India" required value="<?php echo htmlspecialchars($kyc['bank_name'] ?? ''); ?>">
                            </div>
                            <div class="col-12 col-md-6">
                                <label for="account_holder" class="form-label">Account Holder Name <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="account_holder" name="account_holder" placeholder="e.g. Rahul Sharma" required value="<?php echo htmlspecialchars($kyc['account_holder'] ?? ''); ?>">
                            </div>
                            <div class="col-12 col-md-6">
                                <label for="account_number" class="form-label">Account Number <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="account_number" name="account_number" placeholder="e.g. 5010020304050" required value="<?php echo htmlspecialchars($kyc['account_number'] ?? ''); ?>">
                            </div>
                            <div class="col-12 col-md-6">
                                <label for="routing_number" class="form-label">Indian IFSC Bank Code <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="routing_number" name="routing_number" placeholder="e.g. SBIN0001234" style="text-transform: uppercase;" required value="<?php echo htmlspecialchars($kyc['routing_number'] ?? ''); ?>">
                            </div>
                        </div>

                        <div class="d-grid">
                            <button type="submit" name="submit_kyc" class="btn btn-primary btn-lg fw-bold py-2.5">
                                <i class="bi bi-cloud-upload me-1"></i> Submit Details & Initiate Verification
                            </button>
                        </div>
                        
                        <script>
                            function setupDropZone(inputId, zoneId, textId, iconId) {
                                const dropZone = document.getElementById(zoneId);
                                const input = document.getElementById(inputId);
                                const text = document.getElementById(textId);
                                const icon = document.getElementById(iconId);

                                if(!dropZone) return;

                                ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
                                    dropZone.addEventListener(eventName, preventDefaults, false);
                                });

                                function preventDefaults(e) {
                                    e.preventDefault();
                                    e.stopPropagation();
                                }

                                ['dragenter', 'dragover'].forEach(eventName => {
                                    dropZone.addEventListener(eventName, highlight, false);
                                });

                                ['dragleave', 'drop'].forEach(eventName => {
                                    dropZone.addEventListener(eventName, unhighlight, false);
                                });

                                function highlight(e) {
                                    dropZone.style.backgroundColor = '#e9ecef';
                                    dropZone.style.borderColor = '#0d6efd';
                                }

                                function unhighlight(e) {
                                    dropZone.style.backgroundColor = '#f8f9fa';
                                    dropZone.style.borderColor = '#dee2e6';
                                }

                                dropZone.addEventListener('drop', handleDrop, false);

                                function handleDrop(e) {
                                    let dt = e.dataTransfer;
                                    let files = dt.files;
                                    input.files = files;
                                    updateUI();
                                }
                                
                                input.addEventListener('change', updateUI);
                                
                                function updateUI() {
                                    if(input.files && input.files[0]) {
                                        icon.className = 'bi bi-check-circle-fill fs-3 text-success';
                                        text.innerHTML = `<span class='text-success fw-bold'>${input.files[0].name}</span>`;
                                        dropZone.style.borderColor = '#198754';
                                    }
                                }
                            }
                            
                            document.addEventListener('DOMContentLoaded', () => {
                                setupDropZone('doc1_file', 'drop-zone-doc1', 'text-doc1', 'icon-doc1');
                                setupDropZone('doc2_file', 'drop-zone-doc2', 'text-doc2', 'icon-doc2');
                            });
                        </script>
                    </form>
                </div>
            </div>
        <?php elseif ($kyc['bank_status'] === 'initiated'): ?>
            <!-- Form Card: Verify Deposits -->
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-white border-bottom py-3">
                    <h5 class="mb-0 fw-bold text-dark"><i class="bi bi-wallet2 me-2 text-warning"></i>2. Bank Account Micro-Deposit Validation</h5>
                </div>
                <div class="card-body p-4">
                    <p class="text-muted">We have sent two micro-deposits (amounts between ₹<?php echo number_format($min_dep, 2); ?> and ₹<?php echo number_format($max_dep, 2); ?>) to your bank account <strong><?php echo htmlspecialchars($kyc['bank_name']); ?></strong> (ending in *<?php echo substr($kyc['account_number'], -4); ?>). Please check your transaction alert history log and input the exact deposit amounts below.</p>
                    
                    <form method="POST" action="kyc" class="row g-3 align-items-end mb-4">
                        <input type="hidden" name="csrf_token" value="<?php echo getCSRFToken(); ?>">
                        <div class="col-12 col-sm-4">
                            <label for="deposit_1" class="form-label small font-monospace">Deposit Amount 1 (₹)</label>
                            <input type="number" step="0.01" min="<?php echo number_format($min_dep, 2); ?>" max="<?php echo number_format($max_dep, 2); ?>" class="form-control" id="deposit_1" name="deposit_1" required placeholder="<?php echo number_format($min_dep + 0.14, 2); ?>">
                        </div>
                        <div class="col-12 col-sm-4">
                            <label for="deposit_2" class="form-label small font-monospace">Deposit Amount 2 (₹)</label>
                            <input type="number" step="0.01" min="<?php echo number_format($min_dep, 2); ?>" max="<?php echo number_format($max_dep, 2); ?>" class="form-control" id="deposit_2" name="deposit_2" required placeholder="<?php echo number_format($min_dep + 0.26, 2); ?>">
                        </div>
                        <div class="col-12 col-sm-4 d-grid">
                            <button type="submit" name="verify_deposits" class="btn btn-warning fw-bold text-dark py-2">
                                <i class="bi bi-check2-circle me-1"></i> Match & Verify
                            </button>
                        </div>
                    </form>

                    <!-- SANDBOX TEST ALERTS BOX -->
                    <div class="alert alert-info border-0 shadow-sm p-3 mb-0" role="alert" style="background-color: #e3f2fd; border-radius: 8px;">
                        <div class="d-flex">
                            <div class="me-3 fs-3 text-primary">
                                <i class="bi bi-phone-vibrate"></i>
                            </div>
                            <div>
                                <h6 class="alert-heading fw-bold mb-1 font-monospace text-primary" style="font-size: 0.85rem;">Developer Sandbox Simulation Alert: Bank SMS Feed</h6>
                                <p class="mb-0 small text-secondary"><strong>[SMS Notification Log]</strong>: State Bank Alert: Your account *<?php echo substr($kyc['account_number'], -4); ?> received credit transactions of <strong>₹<?php echo number_format($kyc['deposit_1'], 2); ?></strong> and <strong>₹<?php echo number_format($kyc['deposit_2'], 2); ?></strong> from EVENT CONFERENCES CORP.</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        <?php elseif ($kyc['bank_status'] === 'verified'): ?>
            <!-- Verified Success Card -->
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-body p-5 text-center">
                    <div class="d-inline-flex p-4 bg-success bg-opacity-10 text-success rounded-circle mb-3 fs-1">
                        <i class="bi bi-patch-check-fill"></i>
                    </div>
                    <h3 class="fw-bold text-dark">Bank Account Verified</h3>
                    <p class="text-secondary mb-0">Your Indian bank account is successfully linked and approved for payouts.</p>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <!-- Right Column: Verification Status Info -->
    <div class="col-12 col-lg-4">
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-white border-bottom py-3">
                <h5 class="mb-0 fw-bold text-dark"><i class="bi bi-patch-check me-2 text-success"></i>Verification Status</h5>
            </div>
            <div class="card-body p-4">
                <!-- Status List -->
                <div class="mb-4">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span class="small fw-semibold text-secondary">Aadhaar Document:</span>
                        <?php if (empty($kyc)): ?>
                            <span class="badge bg-secondary font-monospace">Unsubmitted</span>
                        <?php elseif ($kyc['doc1_status'] === 'pending'): ?>
                            <span class="badge bg-warning text-dark font-monospace">Pending Review</span>
                        <?php elseif ($kyc['doc1_status'] === 'approved'): ?>
                            <span class="badge bg-success font-monospace">Approved</span>
                        <?php else: ?>
                            <span class="badge bg-danger font-monospace">Rejected</span>
                        <?php endif; ?>
                    </div>
                    
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <span class="small fw-semibold text-secondary">PAN Document:</span>
                        <?php if (empty($kyc)): ?>
                            <span class="badge bg-secondary font-monospace">Unsubmitted</span>
                        <?php elseif ($kyc['doc2_status'] === 'pending'): ?>
                            <span class="badge bg-warning text-dark font-monospace">Pending Review</span>
                        <?php elseif ($kyc['doc2_status'] === 'approved'): ?>
                            <span class="badge bg-success font-monospace">Approved</span>
                        <?php else: ?>
                            <span class="badge bg-danger font-monospace">Rejected</span>
                        <?php endif; ?>
                    </div>
                    
                    <div class="d-flex justify-content-between align-items-center mb-0">
                        <span class="small fw-semibold text-secondary">Bank Verification:</span>
                        <?php if (empty($kyc)): ?>
                            <span class="badge bg-secondary font-monospace">Unlinked</span>
                        <?php elseif ($kyc['bank_status'] === 'initiated'): ?>
                            <span class="badge bg-info text-dark font-monospace">Initiated</span>
                        <?php elseif ($kyc['bank_status'] === 'verified'): ?>
                            <span class="badge bg-success font-monospace">Verified</span>
                        <?php else: ?>
                            <span class="badge bg-secondary font-monospace">Unverified</span>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Status Progress bar -->
                <?php
                $pct = 0;
                if ($kyc) {
                    if ($kyc['doc1_status'] === 'approved') $pct += 33;
                    if ($kyc['doc2_status'] === 'approved') $pct += 33;
                    if ($kyc['bank_status'] === 'verified') $pct += 34;
                }
                ?>
                <div class="progress mb-2" style="height: 6px;">
                    <div class="progress-bar bg-success" role="progressbar" style="width: <?php echo $pct; ?>%;" aria-valuenow="<?php echo $pct; ?>" aria-valuemin="0" aria-valuemax="100"></div>
                </div>
                <div class="d-flex justify-content-between text-muted small uppercase font-monospace" style="font-size: 0.65rem;">
                    <span>Linked</span>
                    <span>Verified: <?php echo $pct; ?>%</span>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
include __DIR__ . '/../includes/footer.php';
?>
