<?php
require_once __DIR__ . '/../actions/admin_auth.php';
require_once __DIR__ . '/../includes/db.php';

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

$identifier = trim($_POST['identifier'] ?? '');
$amount = floatval($_POST['amount'] ?? 0);
$description = trim($_POST['description'] ?? 'Manual Funding');

if (!$identifier || $amount <= 0) {
  echo json_encode(['status'=>'error', 'message'=>'Please enter a valid email/account number and amount.']);
  exit;
}

// ✅ Locate user by email or account number
$stmt = $pdo->prepare("SELECT id, account_balance, fullname FROM users WHERE email = ? OR account_number = ?");
$stmt->execute([$identifier, $identifier]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user) {
  echo json_encode(['status'=>'error', 'message'=>'User not found.']);
  exit;
}

// ✅ Generate unique transaction reference
$reference = 'ADM' . strtoupper(bin2hex(random_bytes(4)));

// ✅ Update balance
$new_balance = $user['account_balance'] + $amount;
$pdo->prepare("UPDATE users SET account_balance = ? WHERE id = ?")->execute([$new_balance, $user['id']]);

// ✅ Log transaction
$stmt = $pdo->prepare("
  INSERT INTO transactions (user_id, type, amount, description, reference, status)
  VALUES (?, 'credit', ?, ?, ?, 'successful')
");
$stmt->execute([$user['id'], $amount, $description, $reference]);

echo json_encode([
  'status'=>'success',
  'message'=>"₦" . number_format($amount, 2) . " has been credited to {$user['fullname']} successfully."
]);
