<?php
require_once 'config.php';
require_once 'classes/Security.php';
require_once 'classes/User.php';

Security::requireAuth();

$pageTitle = 'Security Settings - CryptoExchange Pro | Account Security';
$pageDescription = 'Manage your account security settings including password, two-factor authentication, and login activity monitoring.';

$user = new User();
$userInfo = $user->getUserById($_SESSION['user_id']);

$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!Security::validateCSRFToken($_POST['csrf_token'])) {
        $message = 'Invalid security token. Please try again.';
        $messageType = 'danger';
    } else {
        if (isset($_POST['change_password'])) {
            // Handle password change
            $currentPassword = $_POST['current_password'];
            $newPassword = $_POST['new_password'];
            $confirmPassword = $_POST['confirm_password'];
            
            if (!Security::verifyPassword($currentPassword, $userInfo['password_hash'])) {
                $message = 'Current password is incorrect.';
                $messageType = 'danger';
            } elseif ($newPassword !== $confirmPassword) {
                $message = 'New passwords do not match.';
                $messageType = 'danger';
            } elseif (strlen($newPassword) < 8) {
                $message = 'New password must be at least 8 characters long.';
                $messageType = 'danger';
            } else {
                // Update password
                $db = new Database();
                $newPasswordHash = Security::hashPassword($newPassword);
                $db->query("UPDATE users SET password_hash = :password WHERE id = :user_id");
                $db->bind(':password', $newPasswordHash);
                $db->bind(':user_id', $_SESSION['user_id']);
                
                if ($db->execute()) {
                    $message = 'Password changed successfully.';
                    $messageType = 'success';
                    Security::logSecurityEvent('PASSWORD_CHANGED', 'User changed password', $_SESSION['user_id']);
                } else {
                    $message = 'Failed to change password. Please try again.';
                    $messageType = 'danger';
                }
            }
        }
    }
}

// Get recent login activity
$db = new Database();
$db->query("SELECT * FROM activity_logs WHERE user_id = :user_id AND action IN ('LOGIN_SUCCESS', 'LOGIN_FAILED') ORDER BY created_at DESC LIMIT 10");
$db->bind(':user_id', $_SESSION['user_id']);
$loginActivity = $db->resultSet();

include 'includes/header.php';
?>

<main style="min-height: 100vh; background-color: var(--bg-secondary); padding: 40px 0;">
    <div class="container">
        <!-- Header -->
        <div class="mb-4">
            <h1 style="font-size: 2.5rem; font-weight: 700; color: var(--text-primary); margin-bottom: 8px;">
                <i class="fas fa-shield-alt" style="color: var(--primary-color); margin-right: 16px;"></i>Security Settings
            </h1>
            <p style="color: var(--text-secondary); font-size: 16px;">Manage your account security and privacy settings</p>
        </div>

        <!-- Alert Messages -->
        <?php if ($message): ?>
        <div class="alert alert-<?php echo $messageType; ?> fade-in mb-4">
            <div class="d-flex align-items-center">
                <div style="margin-right: 12px;">
                    <i class="fas <?php echo $messageType === 'success' ? 'fa-check-circle' : 'fa-exclamation-triangle'; ?>"></i>
                </div>
                <div>
                    <p style="margin: 0; font-weight: 500;"><?php echo $message; ?></p>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <div class="row">
            <!-- Security Settings -->
            <div class="col-8">
                <!-- Password Change -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h2 style="margin: 0; font-size: 1.25rem; font-weight: 600;">
                            <i class="fas fa-key" style="color: var(--primary-color); margin-right: 8px;"></i>
                            Change Password
                        </h2>
                    </div>
                    <div class="card-body">
                        <form method="POST" action="">
                            <input type="hidden" name="csrf_token" value="<?php echo Security::generateCSRFToken(); ?>">
                            
                            <div class="form-group">
                                <label class="form-label">Current Password *</label>
                                <input type="password" name="current_password" class="form-control" required>
                            </div>

                            <div class="row">
                                <div class="col-6">
                                    <div class="form-group">
                                        <label class="form-label">New Password *</label>
                                        <input type="password" name="new_password" class="form-control" required 
                                               minlength="8" id="newPassword">
                                        <small style="color: var(--text-secondary); font-size: 12px;">
                                            Must be at least 8 characters with uppercase, lowercase, number, and special character
                                        </small>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="form-group">
                                        <label class="form-label">Confirm New Password *</label>
                                        <input type="password" name="confirm_password" class="form-control" required 
                                               id="confirmPassword">
                                    </div>
                                </div>
                            </div>

                            <button type="submit" name="change_password" class="btn btn-primary">
                                <i class="fas fa-save"></i> Change Password
                            </button>
                        </form>
                    </div>
                </div>

                <!-- Two-Factor Authentication -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h2 style="margin: 0; font-size: 1.25rem; font-weight: 600;">
                            <i class="fas fa-mobile-alt" style="color: var(--secondary-color); margin-right: 8px;"></i>
                            Two-Factor Authentication (2FA)
                        </h2>
                    </div>
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <div>
                                <h4 style="margin: 0; font-size: 16px; font-weight: 600;">Authenticator App</h4>
                                <p style="margin: 0; color: var(--text-secondary); font-size: 14px;">
                                    Use Google Authenticator or similar apps for enhanced security
                                </p>
                            </div>
                            <div>
                                <?php if ($userInfo['two_factor_enabled']): ?>
                                <span class="badge badge-success">Enabled</span>
                                <?php else: ?>
                                <span class="badge badge-warning">Disabled</span>
                                <?php endif; ?>
                            </div>
                        </div>

                        <?php if (!$userInfo['two_factor_enabled']): ?>
                        <div class="alert alert-info">
                            <div class="d-flex align-items-center">
                                <div style="margin-right: 12px;">
                                    <i class="fas fa-info-circle"></i>
                                </div>
                                <div>
                                    <p style="margin: 0; font-weight: 500;">
                                        Two-factor authentication adds an extra layer of security to your account.
                                        We strongly recommend enabling it.
                                    </p>
                                </div>
                            </div>
                        </div>
                        <button class="btn btn-primary" onclick="alert('2FA setup will be available in the next update!')">
                            <i class="fas fa-plus"></i> Enable 2FA
                        </button>
                        <?php else: ?>
                        <button class="btn btn-danger" onclick="alert('2FA management will be available in the next update!')">
                            <i class="fas fa-times"></i> Disable 2FA
                        </button>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Login Activity -->
                <div class="card">
                    <div class="card-header">
                        <h2 style="margin: 0; font-size: 1.25rem; font-weight: 600;">
                            <i class="fas fa-history" style="color: var(--warning-color); margin-right: 8px;"></i>
                            Recent Login Activity
                        </h2>
                    </div>
                    <div class="card-body">
                        <?php if (!empty($loginActivity)): ?>
                        <div style="overflow-x: auto;">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>Date & Time</th>
                                        <th>Status</th>
                                        <th>IP Address</th>
                                        <th>User Agent</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($loginActivity as $activity): ?>
                                    <tr>
                                        <td style="font-size: 14px;">
                                            <?php echo date('M j, Y H:i:s', strtotime($activity['created_at'])); ?>
                                        </td>
                                        <td>
                                            <?php if ($activity['action'] === 'LOGIN_SUCCESS'): ?>
                                            <span class="badge badge-success">Success</span>
                                            <?php else: ?>
                                            <span class="badge badge-danger">Failed</span>
                                            <?php endif; ?>
                                        </td>
                                        <td style="font-family: monospace; font-size: 13px;">
                                            <?php echo $activity['ip_address']; ?>
                                        </td>
                                        <td style="font-size: 12px; max-width: 200px; overflow: hidden; text-overflow: ellipsis;">
                                            <?php echo substr($activity['user_agent'], 0, 50) . (strlen($activity['user_agent']) > 50 ? '...' : ''); ?>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        <?php else: ?>
                        <div style="text-align: center; padding: 40px 0;">
                            <i class="fas fa-history" style="font-size: 3rem; color: var(--text-secondary); margin-bottom: 16px;"></i>
                            <h4 style="color: var(--text-secondary); margin-bottom: 8px;">No login activity found</h4>
                            <p style="color: var(--text-secondary); margin: 0;">Your login history will appear here</p>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Security Status -->
            <div class="col-4">
                <div class="card mb-4">
                    <div class="card-header">
                        <h3 style="margin: 0; font-size: 1.25rem; font-weight: 600;">
                            <i class="fas fa-shield-check" style="color: var(--secondary-color); margin-right: 8px;"></i>
                            Security Score
                        </h3>
                    </div>
                    <div class="card-body text-center">
                        <?php
                        $securityScore = 0;
                        $maxScore = 100;
                        
                        // Calculate security score
                        if ($userInfo['email_verified']) $securityScore += 20;
                        if ($userInfo['kyc_status'] === 'verified') $securityScore += 30;
                        if ($userInfo['two_factor_enabled']) $securityScore += 30;
                        if (!empty($userInfo['phone'])) $securityScore += 10;
                        if (strlen($userInfo['password_hash']) > 0) $securityScore += 10; // Has password
                        
                        $scoreColor = $securityScore >= 80 ? 'var(--secondary-color)' : 
                                     ($securityScore >= 60 ? 'var(--warning-color)' : 'var(--danger-color)');
                        ?>
                        
                        <div style="position: relative; width: 120px; height: 120px; margin: 0 auto 20px;">
                            <svg width="120" height="120" style="transform: rotate(-90deg);">
                                <circle cx="60" cy="60" r="50" fill="none" stroke="var(--border-color)" stroke-width="8"/>
                                <circle cx="60" cy="60" r="50" fill="none" stroke="<?php echo $scoreColor; ?>" stroke-width="8"
                                        stroke-dasharray="<?php echo ($securityScore / 100) * 314; ?> 314" stroke-linecap="round"/>
                            </svg>
                            <div style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);">
                                <div style="font-size: 2rem; font-weight: 700; color: <?php echo $scoreColor; ?>;">
                                    <?php echo $securityScore; ?>%
                                </div>
                            </div>
                        </div>
                        
                        <h4 style="margin-bottom: 8px; color: var(--text-primary);">
                            <?php 
                            if ($securityScore >= 80) echo 'Excellent';
                            elseif ($securityScore >= 60) echo 'Good';
                            elseif ($securityScore >= 40) echo 'Fair';
                            else echo 'Poor';
                            ?>
                        </h4>
                        <p style="color: var(--text-secondary); margin: 0; font-size: 14px;">
                            Your account security level
                        </p>
                    </div>
                </div>

                <div class="card mb-4">
                    <div class="card-header">
                        <h3 style="margin: 0; font-size: 1.25rem; font-weight: 600;">
                            <i class="fas fa-tasks" style="color: var(--primary-color); margin-right: 8px;"></i>
                            Security Checklist
                        </h3>
                    </div>
                    <div class="card-body">
                        <div style="display: flex; flex-direction: column; gap: 12px;">
                            <div class="d-flex align-items-center gap-3">
                                <i class="fas <?php echo $userInfo['email_verified'] ? 'fa-check-circle' : 'fa-times-circle'; ?>" 
                                   style="color: <?php echo $userInfo['email_verified'] ? 'var(--secondary-color)' : 'var(--danger-color)'; ?>;"></i>
                                <span style="font-size: 14px;">Email Verified</span>
                            </div>
                            
                            <div class="d-flex align-items-center gap-3">
                                <i class="fas <?php echo $userInfo['kyc_status'] === 'verified' ? 'fa-check-circle' : 'fa-times-circle'; ?>" 
                                   style="color: <?php echo $userInfo['kyc_status'] === 'verified' ? 'var(--secondary-color)' : 'var(--danger-color)'; ?>;"></i>
                                <span style="font-size: 14px;">KYC Verified</span>
                            </div>
                            
                            <div class="d-flex align-items-center gap-3">
                                <i class="fas <?php echo $userInfo['two_factor_enabled'] ? 'fa-check-circle' : 'fa-times-circle'; ?>" 
                                   style="color: <?php echo $userInfo['two_factor_enabled'] ? 'var(--secondary-color)' : 'var(--danger-color)'; ?>;"></i>
                                <span style="font-size: 14px;">2FA Enabled</span>
                            </div>
                            
                            <div class="d-flex align-items-center gap-3">
                                <i class="fas <?php echo !empty($userInfo['phone']) ? 'fa-check-circle' : 'fa-times-circle'; ?>" 
                                   style="color: <?php echo !empty($userInfo['phone']) ? 'var(--secondary-color)' : 'var(--danger-color)'; ?>;"></i>
                                <span style="font-size: 14px;">Phone Number Added</span>
                            </div>
                            
                            <div class="d-flex align-items-center gap-3">
                                <i class="fas fa-check-circle" style="color: var(--secondary-color);"></i>
                                <span style="font-size: 14px;">Strong Password</span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <h3 style="margin: 0; font-size: 1.25rem; font-weight: 600;">
                            <i class="fas fa-exclamation-triangle" style="color: var(--warning-color); margin-right: 8px;"></i>
                            Security Tips
                        </h3>
                    </div>
                    <div class="card-body">
                        <div style="display: flex; flex-direction: column; gap: 16px;">
                            <div style="padding: 12px; background: rgba(52, 168, 83, 0.1); border-radius: var(--border-radius); border-left: 4px solid var(--secondary-color);">
                                <h4 style="font-size: 14px; font-weight: 600; margin-bottom: 4px; color: var(--secondary-color);">
                                    <i class="fas fa-shield-alt"></i> Enable 2FA
                                </h4>
                                <p style="margin: 0; font-size: 12px; color: var(--text-secondary);">
                                    Add an extra layer of security to your account
                                </p>
                            </div>
                            
                            <div style="padding: 12px; background: rgba(251, 188, 4, 0.1); border-radius: var(--border-radius); border-left: 4px solid var(--warning-color);">
                                <h4 style="font-size: 14px; font-weight: 600; margin-bottom: 4px; color: var(--warning-color);">
                                    <i class="fas fa-key"></i> Strong Password
                                </h4>
                                <p style="margin: 0; font-size: 12px; color: var(--text-secondary);">
                                    Use a unique, complex password for your account
                                </p>
                            </div>
                            
                            <div style="padding: 12px; background: rgba(26, 115, 232, 0.1); border-radius: var(--border-radius); border-left: 4px solid var(--primary-color);">
                                <h4 style="font-size: 14px; font-weight: 600; margin-bottom: 4px; color: var(--primary-color);">
                                    <i class="fas fa-eye"></i> Monitor Activity
                                </h4>
                                <p style="margin: 0; font-size: 12px; color: var(--text-secondary);">
                                    Regularly check your login activity for suspicious access
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

<script>
// Password confirmation validation
document.getElementById('confirmPassword')?.addEventListener('input', function() {
    const newPassword = document.getElementById('newPassword').value;
    const confirmPassword = this.value;
    
    if (newPassword !== confirmPassword) {
        this.setCustomValidity('Passwords do not match');
    } else {
        this.setCustomValidity('');
    }
});

document.getElementById('newPassword')?.addEventListener('input', function() {
    const confirmPassword = document.getElementById('confirmPassword');
    if (confirmPassword.value && this.value !== confirmPassword.value) {
        confirmPassword.setCustomValidity('Passwords do not match');
    } else {
        confirmPassword.setCustomValidity('');
    }
});
</script>

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