<?php
require_once '../config/config.php';
requireLogin('candidate');

$database = new Database();
$db = $database->getConnection();
$candidate_id = $_SESSION['user_id'];

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

// Get candidate info
$stmt = $db->prepare("SELECT * FROM candidates WHERE id = ?");
$stmt->execute([$candidate_id]);
$candidate = $stmt->fetch();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $current_password = $_POST['current_password'];
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];
    
    // Validate current password
    if (!password_verify($current_password, $candidate['password'])) {
        $error = 'Current password is incorrect.';
    }
    // Check if new passwords match
    elseif ($new_password !== $confirm_password) {
        $error = 'New passwords do not match.';
    }
    // Check password complexity
    else {
        $complexity_errors = validatePasswordComplexity($new_password);
        if (!empty($complexity_errors)) {
            $error = implode('<br>', $complexity_errors);
        }
        // Check if new password is different from current
        elseif (password_verify($new_password, $candidate['password'])) {
            $error = 'New password must be different from your current password.';
        }
        // Update password
        else {
            $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
            $stmt = $db->prepare("UPDATE candidates SET password = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
            
            if ($stmt->execute([$hashed_password, $candidate_id])) {
                $success = 'Password changed successfully!';
            } else {
                $error = 'Failed to update password. Please try again.';
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Change Password - RecruitPro</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-briefcase me-2"></i>RecruitPro
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="dashboard.php">
                            <i class="fas fa-tachometer-alt me-1"></i>Dashboard
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="../jobs.php">
                            <i class="fas fa-search me-1"></i>Find Jobs
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="applications.php">
                            <i class="fas fa-file-alt me-1"></i>Applications
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="profile.php">
                            <i class="fas fa-user me-1"></i>Profile
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="cv-builder.php">
                            <i class="fas fa-file-text me-1"></i>CV Builder
                        </a>
                    </li>
                </ul>
                <ul class="navbar-nav">
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown">
                            <i class="fas fa-user me-1"></i><?php echo htmlspecialchars($candidate['first_name']); ?>
                        </a>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="profile.php">Profile</a></li>
                            <li><a class="dropdown-item" href="change-password.php">Change Password</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="../auth/logout.php">Logout</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <div class="row justify-content-center">
            <div class="col-md-8 col-lg-6">
                <div class="card">
                    <div class="card-header">
                        <h4 class="mb-0">
                            <i class="fas fa-lock me-2"></i>Change Password
                        </h4>
                    </div>
                    <div class="card-body">
                        <?php if ($error): ?>
                            <div class="alert alert-danger">
                                <?php echo $error; ?>
                            </div>
                        <?php endif; ?>

                        <?php if ($success): ?>
                            <div class="alert alert-success">
                                <?php echo $success; ?>
                            </div>
                        <?php endif; ?>

                        <div class="alert alert-info">
                            <h6><i class="fas fa-info-circle me-1"></i>Password Requirements:</h6>
                            <ul class="mb-0 small">
                                <li>At least 8 characters long</li>
                                <li>Contains at least one uppercase letter (A-Z)</li>
                                <li>Contains at least one lowercase letter (a-z)</li>
                                <li>Contains at least one number (0-9)</li>
                                <li>Contains at least one special character (!@#$%^&*)</li>
                            </ul>
                        </div>

                        <form method="POST" id="passwordForm">
                            <div class="mb-3">
                                <label for="current_password" class="form-label">Current Password *</label>
                                <div class="input-group">
                                    <input type="password" class="form-control" id="current_password" name="current_password" required>
                                    <button class="btn btn-outline-secondary" type="button" onclick="togglePassword('current_password')">
                                        <i class="fas fa-eye" id="current_password_icon"></i>
                                    </button>
                                </div>
                            </div>

                            <div class="mb-3">
                                <label for="new_password" class="form-label">New Password *</label>
                                <div class="input-group">
                                    <input type="password" class="form-control" id="new_password" name="new_password" required>
                                    <button class="btn btn-outline-secondary" type="button" onclick="togglePassword('new_password')">
                                        <i class="fas fa-eye" id="new_password_icon"></i>
                                    </button>
                                </div>
                                <div class="form-text" id="passwordHelp">
                                    <div id="passwordStrength" class="mt-2"></div>
                                </div>
                            </div>

                            <div class="mb-3">
                                <label for="confirm_password" class="form-label">Confirm New Password *</label>
                                <div class="input-group">
                                    <input type="password" class="form-control" id="confirm_password" name="confirm_password" required>
                                    <button class="btn btn-outline-secondary" type="button" onclick="togglePassword('confirm_password')">
                                        <i class="fas fa-eye" id="confirm_password_icon"></i>
                                    </button>
                                </div>
                                <div id="passwordMatch" class="form-text"></div>
                            </div>

                            <div class="d-grid gap-2">
                                <button type="submit" class="btn btn-primary" id="submitBtn" disabled>
                                    <i class="fas fa-save me-1"></i>Change Password
                                </button>
                                <a href="profile.php" class="btn btn-outline-secondary">
                                    <i class="fas fa-arrow-left me-1"></i>Back to Profile
                                </a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function togglePassword(fieldId) {
            const field = document.getElementById(fieldId);
            const icon = document.getElementById(fieldId + '_icon');
            
            if (field.type === 'password') {
                field.type = 'text';
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
            } else {
                field.type = 'password';
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
            }
        }

        function checkPasswordStrength(password) {
            const requirements = [
                { regex: /.{8,}/, text: 'At least 8 characters', met: false },
                { regex: /[A-Z]/, text: 'Uppercase letter', met: false },
                { regex: /[a-z]/, text: 'Lowercase letter', met: false },
                { regex: /[0-9]/, text: 'Number', met: false },
                { regex: /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/, text: 'Special character', met: false }
            ];

            let score = 0;
            let html = '<div class="row">';

            requirements.forEach((req, index) => {
                req.met = req.regex.test(password);
                if (req.met) score++;
                
                const color = req.met ? 'text-success' : 'text-danger';
                const icon = req.met ? 'fa-check' : 'fa-times';
                
                html += `<div class="col-6 small ${color}">
                    <i class="fas ${icon} me-1"></i>${req.text}
                </div>`;
            });

            html += '</div>';

            let strength = '';
            let strengthClass = '';
            if (score === 0) {
                strength = '';
            } else if (score < 3) {
                strength = 'Weak';
                strengthClass = 'text-danger';
            } else if (score < 5) {
                strength = 'Medium';
                strengthClass = 'text-warning';
            } else {
                strength = 'Strong';
                strengthClass = 'text-success';
            }

            if (strength) {
                html += `<div class="mt-2 ${strengthClass}"><strong>Password Strength: ${strength}</strong></div>`;
            }

            return { html, score, isStrong: score === 5 };
        }

        function validateForm() {
            const currentPassword = document.getElementById('current_password').value;
            const newPassword = document.getElementById('new_password').value;
            const confirmPassword = document.getElementById('confirm_password').value;
            const submitBtn = document.getElementById('submitBtn');

            const strength = checkPasswordStrength(newPassword);
            const passwordsMatch = newPassword === confirmPassword && newPassword.length > 0;

            // Update password match indicator
            const matchDiv = document.getElementById('passwordMatch');
            if (confirmPassword.length > 0) {
                if (passwordsMatch) {
                    matchDiv.innerHTML = '<span class="text-success"><i class="fas fa-check me-1"></i>Passwords match</span>';
                } else {
                    matchDiv.innerHTML = '<span class="text-danger"><i class="fas fa-times me-1"></i>Passwords do not match</span>';
                }
            } else {
                matchDiv.innerHTML = '';
            }

            // Enable submit button only if all conditions are met
            const isValid = currentPassword.length > 0 && strength.isStrong && passwordsMatch;
            submitBtn.disabled = !isValid;
        }

        // Real-time validation
        document.getElementById('new_password').addEventListener('input', function() {
            const strength = checkPasswordStrength(this.value);
            document.getElementById('passwordStrength').innerHTML = strength.html;
            validateForm();
        });

        document.getElementById('confirm_password').addEventListener('input', validateForm);
        document.getElementById('current_password').addEventListener('input', validateForm);

        // Form submission confirmation
        document.getElementById('passwordForm').addEventListener('submit', function(e) {
            if (!confirm('Are you sure you want to change your password?')) {
                e.preventDefault();
            }
        });
    </script>
</body>
</html>