<?php
//Developer: core tech web designTechnology
// Admin "Debit User" - Deduct funds from a user's balance

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

// Load config
$config_path = dirname(__DIR__, 2) . '/include/config.php';
if (!file_exists($config_path)) {
    echo json_encode(['status' => '0', 'msg' => 'Configuration file not found']);
    exit();
}
include($config_path);

// Verify current user is admin
if (!isset($_SESSION['user_id']) || !isset($_SESSION['is_admin']) || $_SESSION['is_admin'] != 1) {
    echo json_encode(['status' => '0', 'msg' => 'Unauthorized. Admin access required.']);
    exit();
}

// Validate request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => '0', 'msg' => 'Invalid request method']);
    exit();
}

$target_user_id = isset($_POST['user_id']) ? intval($_POST['user_id']) : 0;
$amount = isset($_POST['amount']) ? floatval($_POST['amount']) : 0;
$fund_type = isset($_POST['fund_type']) ? trim($_POST['fund_type']) : 'main_balance';
$reason = isset($_POST['reason']) ? trim($_POST['reason']) : '';

if ($target_user_id <= 0) {
    echo json_encode(['status' => '0', 'msg' => 'Invalid user ID']);
    exit();
}

if ($amount <= 0) {
    echo json_encode(['status' => '0', 'msg' => 'Amount must be greater than zero']);
    exit();
}

// Validate fund type
$allowed_types = ['main_balance', 'referral_balance'];
if (!in_array($fund_type, $allowed_types)) {
    echo json_encode(['status' => '0', 'msg' => 'Invalid balance type']);
    exit();
}

try {
    // Get current balance
    $stmt = $pdo->prepare("SELECT id, username, $fund_type FROM users WHERE id = :id LIMIT 1");
    $stmt->execute([':id' => $target_user_id]);
    $target_user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$target_user) {
        echo json_encode(['status' => '0', 'msg' => 'User not found']);
        exit();
    }

    $current_balance = floatval($target_user[$fund_type]);

    if ($amount > $current_balance) {
        echo json_encode([
            'status' => '0',
            'msg' => 'Insufficient balance. User has NGN' . number_format($current_balance, 2) . ' in ' . str_replace('_', ' ', $fund_type)
        ]);
        exit();
    }

    // Deduct the amount
    $stmt = $pdo->prepare("UPDATE users SET $fund_type = $fund_type - :amount WHERE id = :id");
    $stmt->execute([':amount' => $amount, ':id' => $target_user_id]);

    $new_balance = $current_balance - $amount;
    $balance_label = ($fund_type === 'main_balance') ? 'Main Balance' : 'Referral Balance';

    echo json_encode([
        'status' => '1',
        'msg' => 'Successfully debited NGN' . number_format($amount, 2) . ' from ' . $target_user['username'] . '. New ' . $balance_label . ': NGN' . number_format($new_balance, 2)
    ]);

} catch (PDOException $e) {
    error_log("Debit user error: " . $e->getMessage());
    echo json_encode(['status' => '0', 'msg' => 'Database error occurred']);
}
