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

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

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

// Get company user info
$stmt = $db->prepare("
    SELECT cu.*, c.name as company_name 
    FROM company_users cu 
    JOIN companies c ON cu.company_id = c.id 
    WHERE cu.id = ?
");
$stmt->execute([$user_id]);
$user = $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, $user['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, $user['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 company_users SET password = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
            
            if ($stmt->execute([$hashed_password, $user_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 - <?php echo SITE_NAME; ?></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>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-briefcase me-2"></i><?php echo SITE_NAME; ?>
            </a>
            
            <div class="navbar-nav ms-auto">
                <span class="navbar-text me-3">
                    Welcome, <?php echo htmlspecialchars($user['company_name']); ?>
                </span>
                <a class="nav-link" href="../auth/logout.php">
                    <i class="fas fa-sign-out-alt me-1"></i>Logout
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <nav class="col-md-3 col-lg-2 sidebar">
                <div class="position-sticky">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="dashboard.php">
                                <i class="fas fa-tachometer-alt me-2"></i>Dashboard
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="profile.php">
                                <i class="fas fa-building me-2"></i>Company Profile
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="jobs.php">
                                <i class="fas fa-briefcase me-2"></i>Manage Jobs
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="post-job.php">
                                <i class="fas fa-plus me-2"></i>Post New Job
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="applications.php">
                                <i class="fas fa-file-alt me-2"></i>Applications
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="interviews.php">
                                <i class="fas fa-calendar-alt me-2"></i>Interviews
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="change-password.php">
                                <i class="fas fa-lock me-2"></i>Change Password
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- Main content -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">Change Password</h1>
                </div>
                
                <div class="row justify-content-center">
                    <div class="col-lg-8">
                <div class="card">
                    <div class="card-header">
                        <h4 class="mb-0">
                            <i class="fas fa-lock me-2"></i>Change Password
                        </h4>
                        <small class="text-muted"><?php echo htmlspecialchars($user['company_name']); ?></small>
                    </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-success" 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>
            </main>
        </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>