<?php
session_start();
header('Content-Type: application/json');

// Security checks
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access.']);
    exit;
}

require_once '../config/database.php'; // Correct path from api/ to config/
$input = json_decode(file_get_contents('php://input'), true);

// CSRF Check
if (!isset($input['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $input['csrf_token'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid security token.']);
    exit;
}

$accountNumber = $input['accountNumber'] ?? '';
if (empty($accountNumber)) {
    echo json_encode(['success' => false, 'message' => 'Account number is required.']);
    exit;
}

try {
    $database = new Database();
    $db = $database->getConnection();

    $stmt = $db->prepare("SELECT id, first_name, last_name FROM users WHERE account_number = ? AND id != ? AND role = 'user' AND status = 'active'");
    $stmt->execute([$accountNumber, $_SESSION['user_id']]);
    $recipient = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($recipient) {
        $lastNameInitial = strtoupper(substr($recipient['last_name'], 0, 1));
        $recipientName = htmlspecialchars($recipient['first_name'] . ' ' . $lastNameInitial . '.');
        echo json_encode(['success' => true, 'name' => $recipientName, 'id' => $recipient['id']]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid or inactive recipient account number.']);
    }
} catch (Exception $e) {
    error_log("Verify Account API Error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'A server error occurred.']);
}
