<?php
require_once 'functions.php';
requireAuth();

$user = getCurrentUser();
$db = getDB();

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

// Handle KYC document upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload_kyc'])) {
    $docType = $_POST['document_type'] ?? '';
    
    if (empty($docType)) {
        $error = 'Please select a document type.';
    } elseif (!isset($_FILES['document']) || $_FILES['document']['error'] !== UPLOAD_ERR_OK) {
        $error = 'Please upload a valid document file.';
    } else {
        $uploadDir = 'uploads/kyc/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }
        
        $fileName = uniqid() . '_' . basename($_FILES['document']['name']);
        $filePath = $uploadDir . $fileName;
        
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf'];
        if (!in_array($_FILES['document']['type'], $allowedTypes)) {
            $error = 'Only JPG, PNG, GIF, and PDF files are allowed.';
        } elseif (move_uploaded_file($_FILES['document']['tmp_name'], $filePath)) {
            // Fix 1: Removed 'file_name' since it doesn't exist in kyc_documents
            $stmt = $db->prepare("INSERT INTO kyc_documents (user_id, document_type, document_path, status) VALUES (?, ?, ?, 'pending')");
            $stmt->bind_param('iss', $user['id'], $docType, $filePath);
            
            if ($stmt->execute()) {
                // FIXED: Removed 'kyc_requested' since it doesn't exist in the users table schema
                $stmt = $db->prepare("UPDATE users SET kyc_status = 'pending' WHERE id = ?");
                $stmt->bind_param('i', $user['id']);
                $stmt->execute();
                
                $success = 'Document uploaded successfully! Your KYC verification is now pending review.';
                createNotification($user['id'], 'KYC Document Submitted', 'Your KYC document has been submitted for review.', 'info');
                
                // Refresh user data
                $user = getCurrentUser();
            } else {
                $error = 'Failed to save document record.';
            }
        } else {
            $error = 'Failed to upload file. Please try again.';
        }
    }
}

// Fix 2: Changed uploaded_at to created_at to resolve unknown column mysqli error
$stmt = $db->prepare("SELECT * FROM kyc_documents WHERE user_id = ? ORDER BY created_at DESC");
$stmt->bind_param('i', $user['id']);
$stmt->execute();
$documents = $stmt->get_result();

$flash = getFlash();

$statusLabels = [
    'pending' => ['label' => 'Pending Review', 'class' => 'pending'],
    'verified' => ['label' => 'Verified', 'class' => 'verified'],
    'rejected' => ['label' => 'Rejected', 'class' => 'rejected']
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>KYC Verification - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
    <?php include 'includes/client-sidebar.php'; ?>
    
    <div class="main-content">
        <?php include 'includes/client-header.php'; ?>
        
        <div class="page-content">
            <div class="page-header">
                <h2>KYC Verification</h2>
                <p>Verify your identity to unlock all banking features</p>
            </div>
            
            <?php if ($flash): ?>
                <div class="alert alert-<?php echo $flash['type']; ?> fade-in">
                    <span><?php echo $flash['type'] === 'success' ? '✓' : '⚠'; ?></span> <?php echo e($flash['message']); ?>
                </div>
            <?php endif; ?>
            
            <div style="background: <?php echo $user['kyc_status'] === 'verified' ? 'var(--success-light)' : ($user['kyc_status'] === 'rejected' ? 'var(--danger-light)' : 'var(--warning-light)'); ?>; border: 1px solid <?php echo $user['kyc_status'] === 'verified' ? '#A7F3D0' : ($user['kyc_status'] === 'rejected' ? '#FECACA' : '#FDE68A'); ?>; border-radius: var(--border-radius-lg); padding: 24px; margin-bottom: 28px; display: flex; align-items: center; gap: 20px;">
                <div style="width: 56px; height: 56px; border-radius: 50%; background: <?php echo $user['kyc_status'] === 'verified' ? 'var(--success)' : ($user['kyc_status'] === 'rejected' ? 'var(--danger)' : 'var(--warning)'); ?>; color: white; display: flex; align-items: center; justify-content: center; font-size: 24px; flex-shrink: 0;">
                    <?php echo $user['kyc_status'] === 'verified' ? '✓' : ($user['kyc_status'] === 'rejected' ? '✕' : '⏳'); ?>
                </div>
                <div>
                    <h3 style="font-size: 18px; font-weight: 700; margin-bottom: 4px;">
                        KYC Status: <?php echo ucfirst(e($user['kyc_status'])); ?>
                    </h3>
                    <p style="margin: 0; font-size: 14px; color: var(--gray);">
                        <?php if ($user['kyc_status'] === 'verified'): ?>
                            Your identity has been verified. You have full access to all banking features.
                        <?php elseif ($user['kyc_status'] === 'rejected'): ?>
                            Your verification was rejected. Please check the admin notes and resubmit.
                        <?php else: ?>
                            Your verification is pending review. Please upload the required documents below.
                        <?php endif; ?>
                    </p>
                </div>
            </div>
            
            <?php if (!empty($user['kyc_admin_notes'])): ?>
            <div class="alert alert-info" style="margin-bottom: 24px;">
                <span>ℹ</span> <strong>Admin Note:</strong> <?php echo e($user['kyc_admin_notes']); ?>
            </div>
            <?php elseif (!empty($user['kyc_notes'])): ?>
            <div class="alert alert-info" style="margin-bottom: 24px;">
                <span>ℹ</span> <strong>Admin Note:</strong> <?php echo e($user['kyc_notes']); ?>
            </div>
            <?php endif; ?>
            
            <?php if ($user['kyc_status'] !== 'verified'): ?>
            <div class="card" style="margin-bottom: 24px;">
                <div class="card-header">
                    <span class="card-title">Upload Verification Document</span>
                </div>
                <div class="card-body">
                    <?php if ($error): ?>
                        <div class="alert alert-danger" style="margin-bottom: 20px;"><span>⚠</span> <?php echo e($error); ?></div>
                    <?php endif; ?>
                    <?php if ($success): ?>
                        <div class="alert alert-success" style="margin-bottom: 20px;"><span>✓</span> <?php echo e($success); ?></div>
                    <?php endif; ?>
                    
                    <form method="POST" action="" enctype="multipart/form-data">
                        <input type="hidden" name="upload_kyc" value="1">
                        
                        <div class="form-group">
                            <label class="form-label">Document Type *</label>
                            <select name="document_type" class="form-control" required>
                                <option value="">Select Document Type</option>
                                <option value="passport">Passport</option>
                                <option value="drivers_license">Driver's License</option>
                                <option value="national_id">National ID Card</option>
                                <option value="utility_bill">Utility Bill</option>
                                <option value="bank_statement">Bank Statement</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Upload Document *</label>
                            <div class="file-upload">
                                <input type="file" name="document" accept=".jpg,.jpeg,.png,.gif,.pdf" required>
                                <div class="file-upload-icon">📁</div>
                                <div class="file-upload-text">Drag & drop or <span>click to browse</span></div>
                                <div style="font-size: 12px; color: var(--gray); margin-top: 8px;">Accepted: JPG, PNG, GIF, PDF (max 5MB)</div>
                            </div>
                        </div>
                        
                        <button type="submit" class="btn btn-primary">Upload Document</button>
                    </form>
                </div>
            </div>
            <?php endif; ?>
            
            <?php if ($documents->num_rows > 0): ?>
            <div class="card">
                <div class="card-header">
                    <span class="card-title">Submitted Documents</span>
                </div>
                <div class="card-body" style="padding: 0;">
                    <div class="table-container">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Document</th>
                                    <th>Type</th>
                                    <th>Status</th>
                                    <th>Admin Notes</th>
                                    <th>Uploaded</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while ($doc = $documents->fetch_assoc()): 
                                    $statusInfo = $statusLabels[$doc['status']] ?? ['label' => 'Unknown', 'class' => 'secondary'];
                                    // Extracted file name safely from the saved path variable since file_name is not in the DB schema
                                    $displayFileName = !empty($doc['document_path']) ? basename($doc['document_path']) : 'Document';
                                ?>
                                    <tr>
                                        <td><?php echo e($displayFileName); ?></td>
                                        <td><span style="text-transform: capitalize;"><?php echo str_replace('_', ' ', e($doc['document_type'])); ?></span></td>
                                        <td><span class="kyc-status <?php echo $statusInfo['class']; ?>"><?php echo $statusInfo['label']; ?></span></td>
                                        <td><?php echo e($doc['rejection_reason'] ?? $doc['admin_notes'] ?? '-'); ?></td>
                                        <td style="font-size: 12px;"><?php echo formatDateShort($doc['created_at']); ?></td>
                                    </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
    
    <script src="assets/js/main.js"></script>
</body>
</html>