<?php
session_start();
require_once '../config/database.php';
require_once '../config/security.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    requireCSRFToken();
    $identifier = trim($_POST['identifier']); // username or email
    $full_name = trim($_POST['full_name']);
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];

    // Validate inputs
    if (empty($identifier) || empty($full_name) || empty($new_password) || empty($confirm_password)) {
        header('Location: ../forgot_password.php?error=empty');
        exit();
    }

    // Check if passwords match
    if ($new_password !== $confirm_password) {
        header('Location: ../forgot_password.php?error=password');
        exit();
    }

    // Password length validation
    if (strlen($new_password) < 6) {
        header('Location: ../forgot_password.php?error=password');
        exit();
    }

    $conn = getDBConnection();

    // Find user by username or email AND verify full name
    $stmt = $conn->prepare("SELECT id, username, full_name FROM users WHERE (username = ? OR email = ?)");
    $stmt->bind_param("ss", $identifier, $identifier);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows == 0) {
        // User not found
        header('Location: ../forgot_password.php?error=notfound');
        $stmt->close();
        $conn->close();
        exit();
    }

    $user = $result->fetch_assoc();
    $stmt->close();

    // Verify full name matches (case-insensitive)
    if (strcasecmp(trim($user['full_name']), trim($full_name)) !== 0) {
        header('Location: ../forgot_password.php?error=notfound');
        $conn->close();
        exit();
    }

    // Hash new password
    $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);

    // Update password
    $stmt = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
    $stmt->bind_param("si", $hashed_password, $user['id']);

    if ($stmt->execute()) {
        // Create notification
        $message = "Your password has been successfully reset.";
        $stmt_notif = $conn->prepare("INSERT INTO notifications (user_id, message, is_read) VALUES (?, ?, FALSE)");
        $stmt_notif->bind_param("is", $user['id'], $message);
        $stmt_notif->execute();
        $stmt_notif->close();

        header('Location: ../forgot_password.php?success=1');
    } else {
        header('Location: ../forgot_password.php?error=failed');
    }

    $stmt->close();
    $conn->close();
} else {
    header('Location: ../forgot_password.php');
    exit();
}
?>
