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

$database = new Database();
$db = $database->getConnection();

// For admin, we'll create a simple admin table or use a hardcoded admin
// Let's first check if there's an admins table
$admin_email = $_SESSION['email'] ?? 'admin@admin.com';
$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $current_password = $_POST['current_password'];
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];
    
    // For demo purposes, let's assume admin password is stored in a simple way
    // In production, this should be in a proper admins table
    $current_hash = '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi'; // "password"
    
    // Try to get admin from database if table exists
    try {
        $stmt = $db->query("SELECT password FROM admins WHERE email = 'admin@admin.com' LIMIT 1");
        $admin = $stmt->fetch();
        if ($admin) {
            $current_hash = $admin['password'];
        }
    } catch (PDOException $e) {
        // Admins table doesn't exist, use default
    }
    
    // Validate current password
    if (!password_verify($current_password, $current_hash)) {
        $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, $current_hash)) {
            $error = 'New password must be different from your current password.';
        }
        // Update password
        else {
            $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
            
            try {
                // Try to update in admins table
                $stmt = $db->prepare("UPDATE admins SET password = ? WHERE email = ?");
                $stmt->execute([$hashed_password, $admin_email]);
                $success = 'Password changed successfully!';
            } catch (PDOException $e) {
                // If admins table doesn't exist, create it and insert admin
                try {
                    $db->exec("
                        CREATE TABLE IF NOT EXISTS admins (
                            id INT PRIMARY KEY AUTO_INCREMENT,
                            email VARCHAR(255) UNIQUE NOT NULL,
                            password VARCHAR(255) NOT NULL,
                            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
                        )
                    ");
                    
                    $stmt = $db->prepare("
                        INSERT INTO admins (email, password) VALUES (?, ?)
                        ON DUPLICATE KEY UPDATE password = VALUES(password), updated_at = CURRENT_TIMESTAMP
                    ");
                    $stmt->execute([$admin_email, $hashed_password]);
                    $success = 'Password changed successfully!';
                } catch (PDOException $e) {
                    $error = 'Failed to update password. Please contact system administrator.';
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Change Password - Admin Panel</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-dark">
        <div class="container">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-briefcase me-2"></i>RecruitPro Admin
            </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="companies.php">
                            <i class="fas fa-building me-1"></i>Companies
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="candidates.php">
                            <i class="fas fa-users me-1"></i>Candidates
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="jobs.php">
                            <i class="fas fa-briefcase me-1"></i>Jobs
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="categories.php">
                            <i class="fas fa-tags me-1"></i>Categories
                        </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>
                </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>Admin
                        </a>
                        <ul class="dropdown-menu">
                            <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 Admin Password
                        </h4>
                        <small class="text-muted">Administrator Account</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-warning">
                            <h6><i class="fas fa-exclamation-triangle me-1"></i>Security Notice:</h6>
                            <p class="mb-0 small">As an administrator, it's crucial to use a strong password to protect the system. Make sure to store your new password securely.</p>
                        </div>

                        <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 class="form-text">Default admin password is "password" (if not changed)</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-danger" id="submitBtn" disabled>
                                    <i class="fas fa-save me-1"></i>Change Password
                                </button>
                                <a href="dashboard.php" class="btn btn-outline-secondary">
                                    <i class="fas fa-arrow-left me-1"></i>Back to Dashboard
                                </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 admin password? Make sure to remember the new password.')) {
                e.preventDefault();
            }
        });
    </script>
</body>
</html>