<?php
declare(strict_types=1);
require_once __DIR__ . '/includes/middleware.php';
if (!isset($pdo)) {
    $pdo = require_once __DIR__ . '/config/database.php';
}

// Handle password reset
if (is_post() && isset($_POST['password'], $_POST['confirm_password'])) {
    ensure_csrf();
    
    $token = $_GET['token'] ?? '';
    $password = $_POST['password'];
    $confirmPassword = $_POST['confirm_password'];
    
    // Validate inputs
    $errors = [];
    
    if (empty($token)) {
        $errors[] = 'Invalid reset token';
    }
    
    if (strlen($password) < 8) {
        $errors[] = 'Password must be at least 8 characters long';
    }
    
    if (!preg_match('/[A-Z]/', $password)) {
        $errors[] = 'Password must contain at least one uppercase letter';
    }
    
    if (!preg_match('/[a-z]/', $password)) {
        $errors[] = 'Password must contain at least one lowercase letter';
    }
    
    if (!preg_match('/[0-9]/', $password)) {
        $errors[] = 'Password must contain at least one number';
    }
    
    if ($password !== $confirmPassword) {
        $errors[] = 'Passwords do not match';
    }
    
    // Check if token is valid
    $stmt = $pdo->prepare("SELECT email FROM password_resets WHERE token=? AND expires_at > ? AND used=0");
    $stmt->execute([$token, date('c')]);
    $reset = $stmt->fetch();
    
    if (!$reset) {
        $errors[] = 'Invalid or expired reset token';
    }
    
    if (empty($errors)) {
        // Update user password
        $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
        $stmt = $pdo->prepare("UPDATE users SET password=?, updated_at=? WHERE email=?");
        $stmt->execute([$hashedPassword, date('c'), $reset['email']]);
        
        // Mark token as used
        $stmt = $pdo->prepare("UPDATE password_resets SET used=1, used_at=? WHERE token=?");
        $stmt->execute([date('c'), $token]);
        
        set_flash('success', 'Your password has been reset successfully. You can now login with your new password.');
        redirect('/login.php');
    } else {
        set_flash('error', implode('<br>', $errors));
    }
}

// Verify token on page load
$token = $_GET['token'] ?? '';
$validToken = false;

if ($token) {
    $stmt = $pdo->prepare("SELECT email, expires_at FROM password_resets WHERE token=? AND expires_at > ? AND used=0");
    $stmt->execute([$token, date('c')]);
    $reset = $stmt->fetch();
    $validToken = !empty($reset);
}

include __DIR__ . '/includes/header.php';
?>

<style>
.reset-password-container {
    max-width: 480px;
    margin: 60px auto;
    padding: 0 20px;
}

.reset-password-card {
    background: #fff;
    border: 1px solid var(--border);
    border-radius: 20px;
    overflow: hidden;
    box-shadow: 0 20px 25px -5px rgba(0,0,0,0.1);
}

.reset-password-header {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    padding: 40px 30px;
    text-align: center;
    color: white;
}

.reset-password-header h1 {
    margin: 0 0 10px;
    font-size: 28px;
    font-weight: 800;
}

.reset-password-header p {
    margin: 0;
    opacity: 0.9;
    font-size: 16px;
}

.reset-password-body {
    padding: 40px 30px;
}

.reset-password-form {
    display: flex;
    flex-direction: column;
    gap: 20px;
}

.form-group {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.form-label {
    font-weight: 600;
    color: var(--text);
    font-size: 14px;
}

.form-input {
    padding: 14px 16px;
    border: 1px solid var(--border);
    border-radius: 10px;
    font-size: 15px;
    transition: all 0.2s;
}

.form-input:focus {
    outline: none;
    border-color: var(--primary);
    box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1);
}

.password-strength {
    margin-top: 8px;
    padding: 8px 12px;
    border-radius: 6px;
    font-size: 12px;
    font-weight: 500;
}

.strength-weak {
    background: #fee2e2;
    color: #dc2626;
    border: 1px solid #fecaca;
}

.strength-medium {
    background: #fef3c7;
    color: #d97706;
    border: 1px solid #fde68a;
}

.strength-strong {
    background: #dcfce7;
    color: #16a34a;
    border: 1px solid #bbf7d0;
}

.btn-reset {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: white;
    border: none;
    padding: 16px 24px;
    border-radius: 10px;
    font-size:16px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
}

.btn-reset:hover {
    transform: translateY(-2px);
    box-shadow: 0 10px 20px -5px rgba(16, 185, 129, 0.3);
}

.btn-reset:active {
    transform: translateY(0);
}

.password-requirements {
    background: #f8fafc;
    border: 1px solid #e2e8f0;
    border-radius: 10px;
    padding: 16px;
    margin-top: 20px;
}

.password-requirements h3 {
    color: #374151;
    margin: 0 0 12px;
    font-size: 14px;
    font-weight: 600;
}

.requirement-list {
    list-style: none;
    padding: 0;
    margin: 0;
}

.requirement-item {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 6px;
    font-size: 13px;
    color: #6b7280;
}

.requirement-item.met {
    color: #16a34a;
}

.requirement-icon {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 10px;
    font-weight: bold;
}

.requirement-item.met .requirement-icon {
    background: #dcfce7;
    color: #16a34a;
}

.requirement-item:not(.met) .requirement-icon {
    background: #f3f4f6;
    color: #9ca3af;
}

.invalid-token {
    background: #fee2e2;
    border: 1px solid #fecaca;
    border-radius: 10px;
    padding: 20px;
    text-align: center;
    color: #dc2626;
}

.invalid-token h2 {
    margin: 0 0 10px;
    font-size: 18px;
}

.invalid-token p {
    margin: 0 0 15px;
    font-size: 14px;
}

@media (max-width: 640px) {
    .reset-password-container {
        margin: 40px auto;
        padding: 0 16px;
    }
    
    .reset-password-header {
        padding: 30px 20px;
    }
    
    .reset-password-body {
        padding: 30px 20px;
    }
}
</style>

<div class="reset-password-container">
    <div class="reset-password-card">
        <?php if ($validToken): ?>
            <div class="reset-password-header">
                <h1>Reset Password</h1>
                <p>Enter your new password below</p>
            </div>
            
            <div class="reset-password-body">
                <?php if (has_flash()): ?>
                    <div class="alert alert-<?=get_flash_type()?>">
                        <?=get_flash_message()?>
                    </div>
                <?php endif; ?>
                
                <form method="post" class="reset-password-form" id="resetForm">
                    <?=csrf_field()?>
                    
                    <div class="form-group">
                        <label for="password" class="form-label">New Password</label>
                        <input 
                            type="password" 
                            id="password" 
                            name="password" 
                            class="form-input" 
                            placeholder="Enter new password"
                            required
                            minlength="8"
                            autocomplete="new-password"
                        >
                        <div id="passwordStrength" class="password-strength" style="display: none;"></div>
                    </div>
                    
                    <div class="form-group">
                        <label for="confirm_password" class="form-label">Confirm Password</label>
                        <input 
                            type="password" 
                            id="confirm_password" 
                            name="confirm_password" 
                            class="form-input" 
                            placeholder="Confirm new password"
                            required
                            minlength="8"
                            autocomplete="new-password"
                        >
                    </div>
                    
                    <div class="password-requirements">
                        <h3>Password Requirements:</h3>
                        <ul class="requirement-list">
                            <li class="requirement-item" id="req-length">
                                <span class="requirement-icon">○</span>
                                At least 8 characters
                            </li>
                            <li class="requirement-item" id="req-uppercase">
                                <span class="requirement-icon">○</span>
                                One uppercase letter
                            </li>
                            <li class="requirement-item" id="req-lowercase">
                                <span class="requirement-icon">○</span>
                                One lowercase letter
                            </li>
                            <li class="requirement-item" id="req-number">
                                <span class="requirement-icon">○</span>
                                One number
                            </li>
                            <li class="requirement-item" id="req-match">
                                <span class="requirement-icon">○</span>
                                Passwords match
                            </li>
                        </ul>
                    </div>
                    
                    <button type="submit" class="btn-reset">
                        Reset Password
                    </button>
                </form>
            </div>
        <?php else: ?>
            <div class="reset-password-body">
                <div class="invalid-token">
                    <h2>❌ Invalid Reset Link</h2>
                    <p>This password reset link is invalid, expired, or has already been used.</p>
                    <a href="/forgot_password.php" class="btn btn-outline">Request New Reset Link</a>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const passwordInput = document.getElementById('password');
    const confirmPasswordInput = document.getElementById('confirm_password');
    const passwordStrength = document.getElementById('passwordStrength');
    
    // Password requirements
    const requirements = {
        length: document.getElementById('req-length'),
        uppercase: document.getElementById('req-uppercase'),
        lowercase: document.getElementById('req-lowercase'),
        number: document.getElementById('req-number'),
        match: document.getElementById('req-match')
    };
    
    function checkPasswordStrength(password) {
        let strength = 0;
        let feedback = '';
        
        if (password.length >= 8) strength++;
        if (/[A-Z]/.test(password)) strength++;
        if (/[a-z]/.test(password)) strength++;
        if (/[0-9]/.test(password)) strength++;
        if (/[^A-Za-z0-9]/.test(password)) strength++;
        
        if (strength <= 2) {
            feedback = 'Weak password';
            passwordStrength.className = 'password-strength strength-weak';
        } else if (strength <= 3) {
            feedback = 'Medium strength';
            passwordStrength.className = 'password-strength strength-medium';
        } else {
            feedback = 'Strong password';
            passwordStrength.className = 'password-strength strength-strong';
        }
        
        return { strength, feedback };
    }
    
    function updateRequirements(password, confirmPassword) {
        // Length
        if (password.length >= 8) {
            requirements.length.classList.add('met');
            requirements.length.querySelector('.requirement-icon').textContent = '✓';
        } else {
            requirements.length.classList.remove('met');
            requirements.length.querySelector('.requirement-icon').textContent = '○';
        }
        
        // Uppercase
        if (/[A-Z]/.test(password)) {
            requirements.uppercase.classList.add('met');
            requirements.uppercase.querySelector('.requirement-icon').textContent = '✓';
        } else {
            requirements.uppercase.classList.remove('met');
            requirements.uppercase.querySelector('.requirement-icon').textContent = '○';
        }
        
        // Lowercase
        if (/[a-z]/.test(password)) {
            requirements.lowercase.classList.add('met');
            requirements.lowercase.querySelector('.requirement-icon').textContent = '✓';
        } else {
            requirements.lowercase.classList.remove('met');
            requirements.lowercase.querySelector('.requirement-icon').textContent = '○';
        }
        
        // Number
        if (/[0-9]/.test(password)) {
            requirements.number.classList.add('met');
            requirements.number.querySelector('.requirement-icon').textContent = '✓';
        } else {
            requirements.number.classList.remove('met');
            requirements.number.querySelector('.requirement-icon').textContent = '○';
        }
        
        // Match
        if (password && confirmPassword && password === confirmPassword) {
            requirements.match.classList.add('met');
            requirements.match.querySelector('.requirement-icon').textContent = '✓';
        } else {
            requirements.match.classList.remove('met');
            requirements.match.querySelector('.requirement-icon').textContent = '○';
        }
    }
    
    passwordInput.addEventListener('input', function() {
        const password = this.value;
        const confirmPassword = confirmPasswordInput.value;
        
        if (password.length > 0) {
            const { feedback } = checkPasswordStrength(password);
            passwordStrength.textContent = feedback;
            passwordStrength.style.display = 'block';
        } else {
            passwordStrength.style.display = 'none';
        }
        
        updateRequirements(password, confirmPassword);
    });
    
    confirmPasswordInput.addEventListener('input', function() {
        updateRequirements(passwordInput.value, this.value);
    });
});
</script>

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