<?php
/**
 * AI Eligibility Check Endpoint
 * Check withdrawal eligibility with AI explanation
 */

require_once __DIR__ . '/../layouts/main.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../classes/AIChatbotService.php';

requireLogin();

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

$input = json_decode(file_get_contents('php://input'), true);
$member_id = $input['member_id'] ?? null;
$withdrawal_type = $input['withdrawal_type'] ?? 'EARLY_EXIT';

if (!$member_id) {
    echo json_encode(['success' => false, 'message' => 'Member ID is required']);
    exit();
}

$chatbotService = new AIChatbotService($conn);
$result = $chatbotService->checkWithdrawalEligibility($member_id, $withdrawal_type);

// Log the interaction
if ($result['success']) {
    $question = "Check eligibility for $withdrawal_type withdrawal";
    $response = $result['ai_explanation'] ?? 'Eligibility checked';
    $chatbotService->logInteraction(
        $_SESSION['user_id'],
        $member_id,
        $question,
        $response
    );
}

echo json_encode($result);
