<?php
/**
 * Process Password Reset
 */
require_once 'config.php';
require_once 'auth-helpers.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: forgot-password.php');
    exit;
}

$email = trim($_POST['email'] ?? '');
$password = $_POST['password'] ?? '';
$confirmPassword = $_POST['confirm_password'] ?? '';
$error = '';

// Validate inputs
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $error = 'Invalid email address';
} elseif (empty($password) || empty($confirmPassword)) {
    $error = 'Please fill in all fields';
} elseif ($password !== $confirmPassword) {
    $error = 'Passwords do not match';
} else {
    // Validate password strength
    $validation = validatePassword($password);
    
    if (!$validation['valid']) {
        $error = $validation['message'];
    } else {
        // Reset password
        $resetResult = resetPassword($conn, $email, $password);
        
        if ($resetResult['success']) {
            // Clear session
            unset($_SESSION['otp_verified']);
            unset($_SESSION['verified_email']);
            unset($_SESSION['otp_id']);
            unset($_SESSION['reset_email']);
            unset($_SESSION['reset_initiated']);
            
            // Redirect to login with success message
            header('Location: login.php?success=' . urlencode('Password reset successfully. Please log in with your new password.'));
            exit;
        } else {
            $error = $resetResult['message'];
        }
    }
}

// Redirect back with error
header('Location: reset-password.php?email=' . urlencode($email) . '&error=' . urlencode($error));
exit;
?>
