<?php
//Developer: core tech web designTechnology
//Whatsapp: +2349162671360
//Telegram: @jeditech

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

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

// Verify admin status
$stmt = $pdo->prepare("SELECT is_admin FROM users WHERE id = :user_id");
$stmt->bindParam(':user_id', $_SESSION['user_id'], PDO::PARAM_INT);
$stmt->execute();
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$admin || $admin['is_admin'] != 1) {
    echo json_encode(['status' => '0', 'msg' => 'Unauthorized access']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user_id = filter_var($_POST['user_id'], FILTER_VALIDATE_INT);
    $amount = filter_var($_POST['amount'], FILTER_VALIDATE_FLOAT);
    $fund_type = isset($_POST['fund_type']) ? $_POST['fund_type'] : 'main_balance';
    
    if (!$user_id || !$amount || $amount <= 0) {
        echo json_encode(['status' => '0', 'msg' => 'Invalid input']);
        exit();
    }
    
    try {
        // Check if user exists
        $stmt = $pdo->prepare("SELECT username FROM users WHERE id = :user_id");
        $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$user) {
            echo json_encode(['status' => '0', 'msg' => 'User not found']);
            exit();
        }
        
        // Update balance based on fund type
        if ($fund_type === 'referral_balance') {
            $stmt = $pdo->prepare("UPDATE users SET referral_balance = referral_balance + :amount WHERE id = :user_id");
        } else {
            $stmt = $pdo->prepare("UPDATE users SET main_balance = main_balance + :amount WHERE id = :user_id");
        }
        
        $stmt->bindParam(':amount', $amount, PDO::PARAM_STR);
        $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
        
        if ($stmt->execute()) {
            $balance_type = $fund_type === 'referral_balance' ? 'Referral Balance' : 'Main Balance';
            echo json_encode([
                'status' => '1', 
                'msg' => 'Successfully added ₦' . number_format($amount, 2) . ' to ' . $user['username'] . '\'s ' . $balance_type
            ]);
        } else {
            echo json_encode(['status' => '0', 'msg' => 'Failed to add funds']);
        }
        
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'Database error: ' . $e->getMessage()]);
    }
} else {
    echo json_encode(['status' => '0', 'msg' => 'Invalid request method']);
}
?>