<?php
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/admin_auth.php'; // session already started

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

try {
    $account_number = trim($_POST['account_number'] ?? '');
    $type = strtolower(trim($_POST['type'] ?? ''));
    $amount = floatval($_POST['amount'] ?? 0);
    $status = strtolower(trim($_POST['status'] ?? 'successful'));
    $description = trim($_POST['description'] ?? '');

    if ($account_number === '' || $type === '' || $amount <= 0) {
        echo json_encode(['status' => 'error', 'message' => 'Please fill all required fields properly.']);
        exit;
    }

    if (!isset($_SESSION['user_id'])) {
        echo json_encode(['status' => 'error', 'message' => 'Unauthorized access — please log in as admin.']);
        exit;
    }

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

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

    $user_id = $user['id'];
    $old_balance = floatval($user['account_balance']);
    $new_balance = $old_balance;
    $reference = strtoupper(uniqid('TXN'));

    // ✅ Adjust balance according to transaction type
    if ($status === 'successful') {
        if ($type === 'deposit') {
            $new_balance = $old_balance + $amount;
        } elseif (in_array($type, ['withdrawal', 'transfer'])) {
            if ($old_balance < $amount) {
                echo json_encode(['status' => 'error', 'message' => 'Insufficient balance for this transaction.']);
                exit;
            }
            $new_balance = $old_balance - $amount;
        }
    }

    // ✅ Insert the transaction
    $insert = $pdo->prepare("INSERT INTO transactions 
        (user_id, account_number, reference, type, amount, description, status, created_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, NOW())");
    $insert->execute([$user_id, $account_number, $reference, $type, $amount, $description, $status]);

    // ✅ Update user balance + Send notification
    if ($status === 'successful' && in_array($type, ['deposit', 'withdrawal', 'transfer'])) {
        $update = $pdo->prepare("UPDATE users SET account_balance = ? WHERE id = ?");
        $update->execute([$new_balance, $user_id]);

        // ✅ Notify the user
        if ($type === 'deposit') {
            sendNotification($pdo, $user_id, "Deposit Successful", "Your account has been credited with ₦{$amount}. New balance: ₦{$new_balance}");
        } elseif ($type === 'withdrawal') {
            sendNotification($pdo, $user_id, "Withdrawal Successful", "You withdrew ₦{$amount}. New balance: ₦{$new_balance}");
        } elseif ($type === 'transfer') {
            sendNotification($pdo, $user_id, "Transfer Successful", "You sent ₦{$amount} from your account. New balance: ₦{$new_balance}");
        }
    }

    echo json_encode([
        'status' => 'success',
        'message' => ucfirst($type) . ' transaction added successfully.',
        'reference' => $reference,
        'new_balance' => number_format($new_balance, 2)
    ]);

} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => 'Server error: ' . $e->getMessage()]);
}
?>
