<?php
header('Content-Type: application/json');
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/auth.php';

$response = ['success' => false, 'message' => '', 'username' => ''];
$token = $_GET['token'] ?? $_POST['token'] ?? '';

if (empty($token)) {
    $response['message'] = "Invalid or missing password reset token.";
    echo json_encode($response);
    exit();
}

try {
    $stmt = $pdo->prepare("SELECT id, username, reset_token_expires FROM users WHERE reset_token = ?");
    $stmt->execute([$token]);
    $user = $stmt->fetch();
    
    if (!$user || strtotime($user['reset_token_expires']) < time()) {
        $response['message'] = "The password reset token is invalid or has expired.";
        echo json_encode($response);
        exit();
    }
    
    $response['username'] = $user['username'];
} catch (PDOException $e) {
    $response['message'] = "An unexpected error occurred. Please try again later.";
    error_log("Reset password token check error: " . $e->getMessage());
    echo json_encode($response);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $response['message'] = "Security check failed (CSRF). Please try again.";
    } else {
        $new_password = $_POST['new_password'] ?? '';
        $confirm_password = $_POST['confirm_password'] ?? '';
        
        if (empty($new_password) || empty($confirm_password)) {
            $response['message'] = "All fields are required.";
        } elseif ($new_password !== $confirm_password) {
            $response['message'] = "New password and confirmation password do not match.";
        } elseif (strlen($new_password) < 6) {
            $response['message'] = "Password must be at least 6 characters long.";
        } else {
            try {
                $new_hash = password_hash($new_password, PASSWORD_DEFAULT);
                $stmt_update = $pdo->prepare("
                    UPDATE users 
                    SET password = ?, reset_token = NULL, reset_token_expires = NULL 
                    WHERE id = ?
                ");
                $stmt_update->execute([$new_hash, $user['id']]);
                
                $_SESSION['flash_success'] = "Password has been reset successfully. You can now log in.";
                $response['success'] = true;
                $response['redirect'] = 'login.php';
            } catch (PDOException $e) {
                $response['message'] = "An unexpected error occurred. Please try again later.";
                error_log("Reset password update error: " . $e->getMessage());
            }
        }
    }
} else {
    // If GET request, just return token verification success
    $response['success'] = true;
}

echo json_encode($response);
