<?php
/**
 * Reset Password Page
 * OBGYN Research & Collaboration Platform
 */

require_once 'config/config.php';

// Redirect if already logged in
if (isLoggedIn()) {
    redirect(SITE_URL . '/researcher/dashboard.php');
}

$pageTitle = 'Reset Password';
$error = '';
$success = '';
$token = $_GET['token'] ?? '';
$validToken = false;

// Verify token exists
if (empty($token)) {
    $error = 'Invalid reset token.';
} else {
    // Check if token is valid (not expired)
    try {
        $db = getDB();
        $stmt = $db->prepare("
            SELECT id, first_name FROM users 
            WHERE reset_token = ? 
            AND reset_token_expiry > NOW()
        ");
        $stmt->execute([$token]);
        $user = $stmt->fetch();
        
        if ($user) {
            $validToken = true;
        } else {
            $error = 'Invalid or expired reset token.';
        }
    } catch (Exception $e) {
        $error = 'An error occurred. Please try again.';
    }
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $validToken) {
    validateCSRF();
    
    $password = $_POST['password'] ?? '';
    $confirmPassword = $_POST['confirm_password'] ?? '';
    
    if (empty($password) || empty($confirmPassword)) {
        $error = 'Please fill in all fields.';
    } elseif ($password !== $confirmPassword) {
        $error = 'Passwords do not match.';
    } elseif (strlen($password) < 8) {
        $error = 'Password must be at least 8 characters long.';
    } else {
        $result = resetPassword($token, $password);
        
        if ($result['success']) {
            $success = $result['message'];
            $validToken = false; // Prevent form from showing again
        } else {
            $error = $result['message'];
        }
    }
}

include 'templates/header.php';
?>

<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-6 col-lg-5">
            <div class="card shadow-lg mt-5">
                <div class="card-body p-5">
                    <div class="text-center mb-4">
                        <?php if ($success): ?>
                            <i class="fas fa-check-circle fa-4x text-success mb-3"></i>
                            <h2 class="fw-bold text-success">Password Reset!</h2>
                        <?php else: ?>
                            <i class="fas fa-lock fa-3x text-primary mb-3"></i>
                            <h2 class="fw-bold">Reset Password</h2>
                            <p class="text-muted">Enter your new password</p>
                        <?php endif; ?>
                    </div>
                    
                    <?php if ($success): ?>
                        <div class="alert alert-success" role="alert">
                            <i class="fas fa-check-circle"></i> <?php echo e($success); ?>
                        </div>
                        
                        <div class="text-center mt-4">
                            <p class="mb-3">Your password has been successfully reset. You can now login with your new password.</p>
                            <a href="<?php echo SITE_URL; ?>/login.php" class="btn btn-primary btn-lg w-100">
                                <i class="fas fa-sign-in-alt"></i> Login Now
                            </a>
                        </div>
                    <?php elseif ($error && !$validToken): ?>
                        <div class="alert alert-danger" role="alert">
                            <i class="fas fa-exclamation-circle"></i> <?php echo e($error); ?>
                        </div>
                        
                        <div class="text-center mt-4">
                            <p class="mb-3">The reset link may have expired or is invalid.</p>
                            
                            <div class="d-grid gap-2">
                                <a href="<?php echo SITE_URL; ?>/forgot-password.php" class="btn btn-outline-primary">
                                    <i class="fas fa-redo"></i> Request New Reset Link
                                </a>
                                <a href="<?php echo SITE_URL; ?>/login.php" class="btn btn-outline-secondary">
                                    <i class="fas fa-arrow-left"></i> Back to Login
                                </a>
                            </div>
                        </div>
                    <?php else: ?>
                        <?php if ($error): ?>
                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                <i class="fas fa-exclamation-circle"></i> <?php echo e($error); ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        <?php endif; ?>
                        
                        <form method="POST" action="" class="needs-validation" novalidate id="resetPasswordForm">
                            <?php echo csrfField(); ?>
                            
                            <div class="mb-3">
                                <label for="password" class="form-label">New Password</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fas fa-lock"></i></span>
                                    <input type="password" class="form-control" id="password" name="password" 
                                           placeholder="Enter new password" required minlength="8">
                                    <button class="btn btn-outline-secondary" type="button" id="togglePassword">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                    <div class="invalid-feedback">
                                        Password must be at least 8 characters long.
                                    </div>
                                </div>
                                <small class="form-text text-muted">
                                    Must be at least 8 characters long.
                                </small>
                            </div>
                            
                            <div class="mb-3">
                                <label for="confirm_password" class="form-label">Confirm New Password</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fas fa-lock"></i></span>
                                    <input type="password" class="form-control" id="confirm_password" name="confirm_password" 
                                           placeholder="Confirm new password" required minlength="8">
                                    <button class="btn btn-outline-secondary" type="button" id="toggleConfirmPassword">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                    <div class="invalid-feedback">
                                        Please confirm your password.
                                    </div>
                                </div>
                            </div>
                            
                            <div id="passwordMatch" class="alert alert-danger d-none" role="alert">
                                <i class="fas fa-exclamation-circle"></i> Passwords do not match!
                            </div>
                            
                            <div class="mb-3">
                                <div class="password-strength">
                                    <small class="text-muted">Password strength:</small>
                                    <div class="progress" style="height: 5px;">
                                        <div id="passwordStrengthBar" class="progress-bar" role="progressbar" style="width: 0%"></div>
                                    </div>
                                    <small id="passwordStrengthText" class="text-muted"></small>
                                </div>
                            </div>
                            
                            <button type="submit" class="btn btn-primary w-100 py-2 mb-3">
                                <i class="fas fa-key"></i> Reset Password
                            </button>
                            
                            <div class="text-center">
                                <a href="<?php echo SITE_URL; ?>/login.php" class="text-decoration-none">
                                    <i class="fas fa-arrow-left"></i> Back to Login
                                </a>
                            </div>
                        </form>
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="text-center mt-3">
                <a href="<?php echo SITE_URL; ?>/index.php" class="text-decoration-none">
                    <i class="fas fa-home"></i> Back to Home
                </a>
            </div>
        </div>
    </div>
</div>

<script>
// Toggle password visibility
document.getElementById('togglePassword')?.addEventListener('click', function() {
    const passwordInput = document.getElementById('password');
    const icon = this.querySelector('i');
    
    if (passwordInput.type === 'password') {
        passwordInput.type = 'text';
        icon.classList.remove('fa-eye');
        icon.classList.add('fa-eye-slash');
    } else {
        passwordInput.type = 'password';
        icon.classList.remove('fa-eye-slash');
        icon.classList.add('fa-eye');
    }
});

document.getElementById('toggleConfirmPassword')?.addEventListener('click', function() {
    const passwordInput = document.getElementById('confirm_password');
    const icon = this.querySelector('i');
    
    if (passwordInput.type === 'password') {
        passwordInput.type = 'text';
        icon.classList.remove('fa-eye');
        icon.classList.add('fa-eye-slash');
    } else {
        passwordInput.type = 'password';
        icon.classList.remove('fa-eye-slash');
        icon.classList.add('fa-eye');
    }
});

// Password strength checker
document.getElementById('password')?.addEventListener('input', function() {
    const password = this.value;
    const strengthBar = document.getElementById('passwordStrengthBar');
    const strengthText = document.getElementById('passwordStrengthText');
    
    let strength = 0;
    let text = '';
    let color = '';
    
    if (password.length >= 8) strength += 25;
    if (password.match(/[a-z]/)) strength += 25;
    if (password.match(/[A-Z]/)) strength += 25;
    if (password.match(/[0-9]/)) strength += 12.5;
    if (password.match(/[^a-zA-Z0-9]/)) strength += 12.5;
    
    if (strength <= 25) {
        text = 'Weak';
        color = 'bg-danger';
    } else if (strength <= 50) {
        text = 'Fair';
        color = 'bg-warning';
    } else if (strength <= 75) {
        text = 'Good';
        color = 'bg-info';
    } else {
        text = 'Strong';
        color = 'bg-success';
    }
    
    strengthBar.style.width = strength + '%';
    strengthBar.className = 'progress-bar ' + color;
    strengthText.textContent = text;
});

// Check password match
document.getElementById('confirm_password')?.addEventListener('input', function() {
    const password = document.getElementById('password').value;
    const confirmPassword = this.value;
    const matchAlert = document.getElementById('passwordMatch');
    
    if (confirmPassword.length > 0) {
        if (password !== confirmPassword) {
            matchAlert.classList.remove('d-none');
        } else {
            matchAlert.classList.add('d-none');
        }
    } else {
        matchAlert.classList.add('d-none');
    }
});

// Form validation
document.getElementById('resetPasswordForm')?.addEventListener('submit', function(e) {
    const password = document.getElementById('password').value;
    const confirmPassword = document.getElementById('confirm_password').value;
    
    if (password !== confirmPassword) {
        e.preventDefault();
        document.getElementById('passwordMatch').classList.remove('d-none');
        return false;
    }
});
</script>

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