<?php
require_once './includes/session_init.php';
require_once './includes/config.php';
require_once './includes/functions.php';

// Security headers
header("X-Frame-Options: DENY");
header("X-Content-Type-Options: nosniff");
header("X-XSS-Protection: 1; mode=block");

// Check if member is logged in
if (!isset($_SESSION['member_id'])) {
    header("Location: login.php");
    exit;
}

// Check if KYC is already verified
$stmt = $pdo->prepare("SELECT * FROM members WHERE id = ?");
$stmt->execute([$_SESSION['member_id']]);
$member = $stmt->fetch();

if ($member && $member['kyc_verified']) {
    header("Location: dashboard.php");
    exit;
}

$errors = [];
$success = "";
$attempts = $_SESSION['kyc_attempts'] ?? 0;
$locked = false;

// Check if too many attempts
if ($attempts >= 10) {
    $locked = true;
    $errors[] = "Too many failed attempts. Please contact support.";
}

if ($_SERVER["REQUEST_METHOD"] === "POST" && !$locked) {
    // CSRF protection
    if (!isset($_POST['csrf_token'])) {
        $errors[] = "Invalid request";
    } else {
        $input = [
            'phone_number'    => trim($_POST['phone_number']),
            'email_address'   => trim($_POST['email_address']),
            'personal_number' => trim($_POST['personal_number']),
            'id_number'       => trim($_POST['id_number']),
        ];

        // Validate inputs
        if (empty($input['phone_number'])) $errors[] = "Phone number is required";
        if (empty($input['email_address'])) $errors[] = "Email is required";
        if (empty($input['personal_number'])) $errors[] = "Personal number is required";
        if (empty($input['id_number'])) $errors[] = "ID number is required";

        if (empty($errors)) {
            // Prepare comparison log
            $comparisonLog = "KYC Verification Attempt:\n";
            $comparisonLog .= "System Values:\n";
            $comparisonLog .= "- Phone: " . $member['phone_number'] . "\n";
            $comparisonLog .= "- Email: " . $member['email_address'] . "\n";
            $comparisonLog .= "- Personal Number: " . $member['personal_number'] . "\n";
            $comparisonLog .= "- ID Number: " . $member['id_number'] . "\n\n";
            $comparisonLog .= "User Provided:\n";
            $comparisonLog .= "- Phone: " . $input['phone_number'] . "\n";
            $comparisonLog .= "- Email: " . $input['email_address'] . "\n";
            $comparisonLog .= "- Personal Number: " . $input['personal_number'] . "\n";
            $comparisonLog .= "- ID Number: " . $input['id_number'] . "\n";

            // Compare submitted values
            $matchCount = 0;
            $fieldMatches = [
                'phone' => false,
                'email_address' => false,
                'personal_number' => false,
                'id_number' => false
            ];

            if ($input['phone_number'] === $member['phone_number']) {
                $matchCount++;
                $fieldMatches['phone'] = true;
            }
            if ($input['email_address'] === $member['email_address']) {
                $matchCount++;
                $fieldMatches['email'] = true;
            }
            if ($input['personal_number'] === $member['personal_number']) {
                $matchCount++;
                $fieldMatches['personal_number'] = true;
            }
            if ($input['id_number'] === $member['id_number']) {
                $matchCount++;
                $fieldMatches['id_number'] = true;
            }

            $comparisonLog .= "\nMatch Results:\n";
            foreach ($fieldMatches as $field => $matched) {
                $comparisonLog .= "- $field: " . ($matched ? "MATCH" : "NO MATCH") . "\n";
            }

            if ($matchCount === 4) {
                // All match — update KYC flag
                $update = $pdo->prepare("UPDATE members SET kyc_verified = 1, kyc_verified_at = NOW() WHERE id = ?");
                $update->execute([$member['id']]);
                
                // Log successful verification
                logActivity($pdo, $_SESSION['member_id'], 'kyc_verification', 'KYC verification successful');
                
                header("Location: dashboard.php");
                exit;
            } else {
                $attempts++;
                $_SESSION['kyc_attempts'] = $attempts;
                
                // Log failed attempt with detailed comparison
                logActivity($pdo, $_SESSION['member_id'], 'kyc_attempt', $comparisonLog);
                
                $errors[] = "Verification failed. Attempts remaining: ".(3 - $attempts);
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>KYC Verification | Member Portal</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        :root {
            --primary: #4361ee;
            --primary-dark: #3a56d4;
            --danger: #f72585;
            --success: #4cc9f0;
            --light: #f8f9fa;
            --dark: #212529;
            --gray: #6c757d;
            --gray-light: #e9ecef;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Inter', sans-serif;
            background-color: #f5f7fb;
            color: var(--dark);
            line-height: 1.6;
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 1rem;
        }
        
        .kyc-container {
            max-width: 500px;
            width: 100%;
            animation: fadeIn 0.5s ease;
        }
        
        .kyc-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
            padding: 2.5rem;
            position: relative;
            overflow: hidden;
        }
        
        .kyc-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 4px;
            background: linear-gradient(90deg, var(--primary), var(--success));
        }
        
        .kyc-header {
            text-align: center;
            margin-bottom: 2rem;
        }
        
        .kyc-header img {
            height: 60px;
            margin-bottom: 1.5rem;
        }
        
        .kyc-header h2 {
            font-size: 1.8rem;
            font-weight: 700;
            color: var(--dark);
            margin-bottom: 0.5rem;
        }
        
        .kyc-header p {
            color: var(--gray);
            font-size: 0.95rem;
        }
        
        .form-group {
            margin-bottom: 1.5rem;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 500;
            color: var(--dark);
            font-size: 0.95rem;
        }
        
        .form-control {
            width: 100%;
            padding: 0.8rem 1rem;
            border: 1px solid var(--gray-light);
            border-radius: 8px;
            font-size: 1rem;
            transition: all 0.3s ease;
            background-color: #f8f9fa;
        }
        
        .form-control:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.2);
            background-color: white;
        }
        
        .btn {
            display: inline-block;
            background: var(--primary);
            color: white;
            border: none;
            padding: 0.9rem 1.5rem;
            font-size: 1rem;
            font-weight: 600;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            width: 100%;
            text-align: center;
        }
        
        .btn:hover {
            background: var(--primary-dark);
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        
        .btn:disabled {
            background: var(--gray-light);
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
        
        .alert {
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1.5rem;
            font-size: 0.95rem;
            display: flex;
            align-items: center;
        }
        
        .alert i {
            margin-right: 10px;
            font-size: 1.2rem;
        }
        
        .alert-danger {
            background-color: rgba(247, 37, 133, 0.1);
            color: var(--danger);
            border: 1px solid rgba(247, 37, 133, 0.2);
        }
        
        .alert-success {
            background-color: rgba(76, 201, 240, 0.1);
            color: #0d6efd;
            border: 1px solid rgba(76, 201, 240, 0.2);
        }
        
        .kyc-footer {
            text-align: center;
            margin-top: 1.5rem;
            font-size: 0.9rem;
            color: var(--gray);
        }
        
        .kyc-footer a {
            color: var(--primary);
            text-decoration: none;
            font-weight: 500;
        }
        
        .kyc-footer a:hover {
            text-decoration: underline;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        /* Dark mode support */
        @media (prefers-color-scheme: dark) {
            body {
                background-color: #121212;
            }
            
            .kyc-card {
                background: #1e1e1e;
                color: #f1f1f1;
                box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            }
            
            .kyc-header h2 {
                color: #f1f1f1;
            }
            
            .form-control {
                background-color: #2d2d2d;
                border-color: #444;
                color: #f1f1f1;
            }
            
            .form-control:focus {
                background-color: #2d2d2d;
                border-color: var(--primary);
            }
            
            .kyc-header p {
                color: #aaa;
            }
            
            .form-group label {
                color: #f1f1f1;
            }
        }
        
        /* Loading spinner */
        .spinner {
            display: none;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255,255,255,0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s ease-in-out infinite;
            margin-left: 10px;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        .btn-loading .spinner {
            display: inline-block;
        }
    </style>
</head>
<body>
    <div class="kyc-container">
        <div class="kyc-card">
            <div class="kyc-header">
                <img src="https://via.placeholder.com/150x60?text=Logo" alt="Logo">
                <h2>Identity Verification</h2>
                <p>Please confirm your details to complete your account setup</p>
            </div>
            
            <?php if (!empty($errors)): ?>
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle"></i> <?php echo implode("<br>", $errors); ?>
                </div>
            <?php endif; ?>
            
            <form method="POST" id="kycForm">
                <input type="hidden" name="csrf_token" value="<?php echo bin2hex(random_bytes(32)); ?>">
                
                <div class="form-group">
                    <label for="phone_number">Phone Number</label>
                    <input type="text" id="phone_number" name="phone_number" class="form-control" required <?php echo $locked ? 'disabled' : ''; ?>>
                </div>
                
                <div class="form-group">
                    <label for="email_address">Email Address</label>
                    <input type="email" id="email_address" name="email_address" class="form-control" required <?php echo $locked ? 'disabled' : ''; ?>>
                </div>
                
                <div class="form-group">
                    <label for="personal_number">Personal Number</label>
                    <input type="text" id="personal_number" name="personal_number" class="form-control" required <?php echo $locked ? 'disabled' : ''; ?>>
                </div>
                
                <div class="form-group">
                    <label for="id_number">ID Number</label>
                    <input type="text" id="id_number" name="id_number" class="form-control" required <?php echo $locked ? 'disabled' : ''; ?>>
                </div>
                
                <button type="submit" class="btn" id="verifyButton" <?php echo $locked ? 'disabled' : ''; ?>>
                    <span>Verify Identity</span>
                    <div class="spinner"></div>
                </button>
            </form>
            
            <div class="kyc-footer">
                <?php if ($locked): ?>
                    <p>Account verification locked. <a href="contact.php">Contact support</a> for assistance.</p>
                <?php else: ?>
                    <p>Having trouble? <a href="contact.php">Contact support</a></p>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const form = document.getElementById('kycForm');
            const verifyButton = document.getElementById('verifyButton');
            
            if (form) {
                form.addEventListener('submit', function() {
                    verifyButton.classList.add('btn-loading');
                    verifyButton.disabled = true;
                });
            }
            
            // Auto-focus first input
            const firstInput = document.querySelector('input:not([type="hidden"])');
            if (firstInput) {
                firstInput.focus();
            }
        });
    </script>
</body>
</html>