<?php
$page_title = "Security Settings";
require_once '../config/config.php';

require_once '../includes/user_auth.php';
require_once '../includes/functions.php';


$db = Database::getInstance()->connect();
$user_id = $_SESSION['user_id'];

// Get user data
$user_stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
$user_stmt->execute([$user_id]);
$user = $user_stmt->fetch();

if (!$user) {
    $_SESSION['error'] = "User not found";
    header('Location: dashboard.php');
    exit();
}

// Handle password change
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_password'])) {
    $current_password = $_POST['current_password'];
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];

    $errors = [];

    // Validate current password
    if (empty($current_password)) {
        $errors[] = "Current password is required";
    } elseif (!password_verify($current_password, $user['password'])) {
        $errors[] = "Current password is incorrect";
    }

    // Validate new password
    if (empty($new_password)) {
        $errors[] = "New password is required";
    } elseif (strlen($new_password) < 6) {
        $errors[] = "New password must be at least 6 characters long";
    }

    // Validate password confirmation
    if (empty($confirm_password)) {
        $errors[] = "Password confirmation is required";
    } elseif ($new_password !== $confirm_password) {
        $errors[] = "New passwords do not match";
    }

    if (empty($errors)) {
        $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);

        $update_stmt = $db->prepare("UPDATE users SET password = ?, updated_at = NOW() WHERE id = ?");
        $result = $update_stmt->execute([$hashed_password, $user_id]);

        if ($result) {
            // Log the password change
            $log_stmt = $db->prepare("INSERT INTO activity_logs (user_id, action, description, ip_address, details, created_at) VALUES (?, 'password_change', 'Password changed successfully', ?, ?, NOW())");
            $log_stmt->execute([$user_id, $_SERVER['REMOTE_ADDR'] ?? '', json_encode(['details' => 'Password changed successfully'])]);

            $_SESSION['success'] = "Password changed successfully";
        } else {
            $_SESSION['error'] = "Failed to change password";
        }
    } else {
        $_SESSION['error'] = implode("<br>", $errors);
    }

    header('Location: security.php');
    exit();
}

// Handle 2FA toggle
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['toggle_2fa'])) {
    $enable_2fa = isset($_POST['enable_2fa']) ? 1 : 0;

    $update_stmt = $db->prepare("UPDATE users SET two_fa_enabled = ?, updated_at = NOW() WHERE id = ?");
    $result = $update_stmt->execute([$enable_2fa, $user_id]);

    if ($result) {
        $_SESSION['success'] = $enable_2fa ? "Two-factor authentication enabled" : "Two-factor authentication disabled";
        $user['two_fa_enabled'] = $enable_2fa;
    } else {
        $_SESSION['error'] = "Failed to update 2FA settings";
    }

    header('Location: security.php');
    exit();
}

// Handle login notifications toggle
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['toggle_notifications'])) {
    $login_notifications = isset($_POST['login_notifications']) ? 1 : 0;

    $update_stmt = $db->prepare("UPDATE users SET login_notifications = ?, updated_at = NOW() WHERE id = ?");
    $result = $update_stmt->execute([$login_notifications, $user_id]);

    if ($result) {
        $_SESSION['success'] = $login_notifications ? "Login notifications enabled" : "Login notifications disabled";
        $user['login_notifications'] = $login_notifications;
    } else {
        $_SESSION['error'] = "Failed to update notification settings";
    }

    header('Location: security.php');
    exit();
}

// Get recent login activity
$login_activity_stmt = $db->prepare("
    SELECT * FROM activity_logs
    WHERE user_id = ? AND action IN ('login', 'logout', 'password_change', 'failed_login')
    ORDER BY created_at DESC
    LIMIT 10
");
$login_activity_stmt->execute([$user_id]);
$login_activity = $login_activity_stmt->fetchAll();

// Get active sessions (simplified - in real app, you'd track sessions in database)
$current_session = [
    'ip_address' => $_SERVER['REMOTE_ADDR'],
    'user_agent' => $_SERVER['HTTP_USER_AGENT'],
    'login_time' => $_SESSION['login_time'] ?? time(),
    'current' => true
];
?>


<?php require_once '../includes/header_user.php'; ?>

<div class="max-w-4xl mx-auto">
    <div class="bg-white rounded-lg shadow-md p-6">
        <div class="flex items-center justify-between mb-6">
            <h1 class="text-2xl font-bold text-gray-800">Security Settings</h1>
            <a href="dashboard.php" class="text-purple-600 hover:text-purple-700">
                <i class="fas fa-arrow-left mr-2"></i>Back to Dashboard
            </a>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
            <!-- Password Change -->
            <div class="space-y-6">
                <div>
                    <h2 class="text-lg font-semibold text-gray-800 mb-4">Change Password</h2>
                    <form method="POST" class="space-y-4">
                        <div>
                            <label for="current_password" class="block text-sm font-medium text-gray-700 mb-2">Current Password</label>
                            <input type="password" id="current_password" name="current_password" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-purple-500 focus:border-purple-500" required>
                        </div>

                        <div>
                            <label for="new_password" class="block text-sm font-medium text-gray-700 mb-2">New Password</label>
                            <input type="password" id="new_password" name="new_password" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-purple-500 focus:border-purple-500" required minlength="6">
                            <p class="text-xs text-gray-500 mt-1">Minimum 6 characters</p>
                        </div>

                        <div>
                            <label for="confirm_password" class="block text-sm font-medium text-gray-700 mb-2">Confirm New Password</label>
                            <input type="password" id="confirm_password" name="confirm_password" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-purple-500 focus:border-purple-500" required>
                        </div>

                        <button type="submit" name="change_password" class="w-full bg-purple-600 hover:bg-purple-700 text-white py-2 px-4 rounded-md font-medium transition-colors">
                            <i class="fas fa-key mr-2"></i>Change Password
                        </button>
                    </form>
                </div>

                <!-- Two-Factor Authentication -->
                <div>
                    <h2 class="text-lg font-semibold text-gray-800 mb-4">Two-Factor Authentication</h2>
                    <form method="POST" class="space-y-4">
                        <div class="flex items-center justify-between">
                            <div>
                                <h3 class="text-sm font-medium text-gray-900">Enable 2FA</h3>
                                <p class="text-sm text-gray-500">Add an extra layer of security to your account</p>
                            </div>
                            <label class="relative inline-flex items-center cursor-pointer">
                                <input type="checkbox" name="enable_2fa" class="sr-only peer" <?php echo ($user['two_fa_enabled'] ?? 0) ? 'checked' : ''; ?> onchange="this.form.submit()">
                                <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-purple-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-purple-600"></div>
                            </label>
                        </div>
                        <input type="hidden" name="toggle_2fa" value="1">
                    </form>

                    <?php if (($user['two_fa_enabled'] ?? 0)): ?>
                        <div class="mt-4 p-4 bg-green-50 border border-green-200 rounded-md">
                            <div class="flex">
                                <div class="flex-shrink-0">
                                    <i class="fas fa-shield-alt text-green-400"></i>
                                </div>
                                <div class="ml-3">
                                    <p class="text-sm text-green-700">Two-factor authentication is enabled for your account.</p>
                                </div>
                            </div>
                        </div>
                    <?php else: ?>
                        <div class="mt-4 p-4 bg-yellow-50 border border-yellow-200 rounded-md">
                            <div class="flex">
                                <div class="flex-shrink-0">
                                    <i class="fas fa-exclamation-triangle text-yellow-400"></i>
                                </div>
                                <div class="ml-3">
                                    <p class="text-sm text-yellow-700">Two-factor authentication is not enabled. Enable it for better security.</p>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Login Notifications -->
                <div>
                    <h2 class="text-lg font-semibold text-gray-800 mb-4">Login Notifications</h2>
                    <form method="POST" class="space-y-4">
                        <div class="flex items-center justify-between">
                            <div>
                                <h3 class="text-sm font-medium text-gray-900">Email Notifications</h3>
                                <p class="text-sm text-gray-500">Get notified when someone logs into your account</p>
                            </div>
                            <label class="relative inline-flex items-center cursor-pointer">
                                <input type="checkbox" name="login_notifications" class="sr-only peer" <?php echo ($user['login_notifications'] ?? 1) ? 'checked' : ''; ?> onchange="this.form.submit()">
                                <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-purple-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-purple-600"></div>
                            </label>
                        </div>
                        <input type="hidden" name="toggle_notifications" value="1">
                    </form>
                </div>
            </div>

            <!-- Security Information -->
            <div class="space-y-6">
                <!-- Account Security Status -->
                <div>
                    <h2 class="text-lg font-semibold text-gray-800 mb-4">Security Status</h2>
                    <div class="space-y-3">
                        <div class="flex items-center justify-between p-3 bg-gray-50 rounded-md">
                            <div class="flex items-center">
                                <i class="fas fa-lock text-green-500 mr-3"></i>
                                <span class="text-sm font-medium text-gray-900">Password Strength</span>
                            </div>
                            <span class="text-sm text-green-600 font-medium">Strong</span>
                        </div>

                        <div class="flex items-center justify-between p-3 bg-gray-50 rounded-md">
                            <div class="flex items-center">
                                <i class="fas fa-shield-alt <?php echo ($user['two_fa_enabled'] ?? 0) ? 'text-green-500' : 'text-yellow-500'; ?> mr-3"></i>
                                <span class="text-sm font-medium text-gray-900">Two-Factor Authentication</span>
                            </div>
                            <span class="text-sm <?php echo ($user['two_fa_enabled'] ?? 0) ? 'text-green-600' : 'text-yellow-600'; ?> font-medium">
                                <?php echo ($user['two_fa_enabled'] ?? 0) ? 'Enabled' : 'Disabled'; ?>
                            </span>
                        </div>

                        <div class="flex items-center justify-between p-3 bg-gray-50 rounded-md">
                            <div class="flex items-center">
                                <i class="fas fa-envelope <?php echo ($user['login_notifications'] ?? 1) ? 'text-green-500' : 'text-yellow-500'; ?> mr-3"></i>
                                <span class="text-sm font-medium text-gray-900">Login Notifications</span>
                            </div>
                            <span class="text-sm <?php echo ($user['login_notifications'] ?? 1) ? 'text-green-600' : 'text-yellow-600'; ?> font-medium">
                                <?php echo ($user['login_notifications'] ?? 1) ? 'Enabled' : 'Disabled'; ?>
                            </span>
                        </div>

                        <div class="flex items-center justify-between p-3 bg-gray-50 rounded-md">
                            <div class="flex items-center">
                                <i class="fas fa-user-check <?php echo $user['kyc_status'] === 'verified' ? 'text-green-500' : 'text-yellow-500'; ?> mr-3"></i>
                                <span class="text-sm font-medium text-gray-900">KYC Verification</span>
                            </div>
                            <span class="text-sm <?php echo $user['kyc_status'] === 'verified' ? 'text-green-600' : 'text-yellow-600'; ?> font-medium">
                                <?php echo ucfirst($user['kyc_status']); ?>
                            </span>
                        </div>
                    </div>
                </div>

                <!-- Recent Activity -->
                <div>
                    <h2 class="text-lg font-semibold text-gray-800 mb-4">Recent Activity</h2>
                    <div class="space-y-3 max-h-64 overflow-y-auto">
                        <?php if (empty($login_activity)): ?>
                            <p class="text-gray-500 text-sm">No recent activity</p>
                        <?php else: ?>
                            <?php foreach ($login_activity as $activity): ?>
                                <div class="flex items-center justify-between p-3 bg-gray-50 rounded-md">
                                    <div class="flex items-center">
                                        <i class="fas <?php
                                            echo $activity['action'] === 'login' ? 'fa-sign-in-alt text-green-500' :
                                                 ($activity['action'] === 'logout' ? 'fa-sign-out-alt text-blue-500' :
                                                 ($activity['action'] === 'password_change' ? 'fa-key text-purple-500' :
                                                 'fa-exclamation-triangle text-red-500'));
                                        ?> mr-3"></i>
                                        <div>
                                            <p class="text-sm font-medium text-gray-900">
                                                <?php
                                                echo $activity['action'] === 'login' ? 'Logged in' :
                                                     ($activity['action'] === 'logout' ? 'Logged out' :
                                                     ($activity['action'] === 'password_change' ? 'Password changed' :
                                                     'Failed login attempt'));
                                                ?>
                                            </p>
                                            <p class="text-xs text-gray-500"><?php echo date('M j, Y g:i A', strtotime($activity['created_at'])); ?></p>
                                        </div>
                                    </div>
                                    <span class="text-xs text-gray-500"><?php echo htmlspecialchars($activity['ip_address']); ?></span>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Current Session -->
                <div>
                    <h2 class="text-lg font-semibold text-gray-800 mb-4">Current Session</h2>
                    <div class="p-4 bg-blue-50 border border-blue-200 rounded-md">
                        <div class="flex items-center mb-2">
                            <i class="fas fa-desktop text-blue-500 mr-2"></i>
                            <span class="text-sm font-medium text-blue-900">Active Session</span>
                        </div>
                        <div class="text-xs text-blue-700 space-y-1">
                            <p><strong>IP Address:</strong> <?php echo htmlspecialchars($current_session['ip_address']); ?></p>
                            <p><strong>Login Time:</strong> <?php echo date('M j, Y g:i A', $current_session['login_time']); ?></p>
                            <p><strong>Device:</strong> <?php echo htmlspecialchars(substr($current_session['user_agent'], 0, 50)) . '...'; ?></p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Password strength indicator
document.getElementById('new_password').addEventListener('input', function() {
    const password = this.value;
    const strength = calculatePasswordStrength(password);

    // Remove existing strength classes
    this.classList.remove('border-red-500', 'border-yellow-500', 'border-green-500');

    if (password.length > 0) {
        if (strength < 2) {
            this.classList.add('border-red-500');
        } else if (strength < 4) {
            this.classList.add('border-yellow-500');
        } else {
            this.classList.add('border-green-500');
        }
    }
});

function calculatePasswordStrength(password) {
    let strength = 0;
    if (password.length >= 6) strength++;
    if (password.match(/[a-z]/)) strength++;
    if (password.match(/[A-Z]/)) strength++;
    if (password.match(/[0-9]/)) strength++;
    if (password.match(/[^A-Za-z0-9]/)) strength++;
    return strength;
}

// Form validation
document.querySelector('form[name="change_password"]').addEventListener('submit', function(e) {
    const newPassword = document.getElementById('new_password').value;
    const confirmPassword = document.getElementById('confirm_password').value;

    if (newPassword !== confirmPassword) {
        e.preventDefault();
        showNotification('Passwords do not match', 'error');
        return false;
    }

    if (newPassword.length < 6) {
        e.preventDefault();
        showNotification('Password must be at least 6 characters long', 'error');
        return false;
    }
});

// Confirm 2FA changes
document.querySelectorAll('input[name="enable_2fa"]').forEach(function(checkbox) {
    checkbox.addEventListener('change', function() {
        if (!this.checked) {
            if (!confirm('Are you sure you want to disable two-factor authentication? This will make your account less secure.')) {
                this.checked = true;
                return false;
            }
        }
    });
});
</script>

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