<?php
// Robust budget creation helper functions
include 'db.php';

function createSafeBudget($pdo, $user_id, $group_id = null, $initial_balance = 0, $created_by = 1) {
    try {
        // Validate inputs
        if (!$user_id && !$group_id) {
            throw new Exception("Either user_id or group_id must be provided");
        }
        
        // Check if user exists
        if ($user_id) {
            $user_check = $pdo->prepare("SELECT id FROM users WHERE id = ?");
            $user_check->execute([$user_id]);
            if (!$user_check->fetch()) {
                throw new Exception("User with ID $user_id does not exist");
            }
        }
        
        // Check if group exists (if group_id provided)
        if ($group_id) {
            $group_check = $pdo->prepare("SELECT id FROM user_groups WHERE id = ?");
            $group_check->execute([$group_id]);
            if (!$group_check->fetch()) {
                // If group doesn't exist, fall back to user-specific budget
                $group_id = null;
            }
        }
        
        // Check if budget already exists
        if ($group_id) {
            $existing_check = $pdo->prepare("SELECT id FROM budgets WHERE group_id = ? AND is_active = 1");
            $existing_check->execute([$group_id]);
        } else {
            $existing_check = $pdo->prepare("SELECT id FROM budgets WHERE user_id = ? AND is_active = 1");
            $existing_check->execute([$user_id]);
        }
        
        if ($existing_budget = $existing_check->fetch()) {
            return [
                'success' => true,
                'budget_id' => $existing_budget['id'],
                'message' => 'Budget already exists',
                'new_budget' => false
            ];
        }
        
        // Create new budget
        if ($group_id) {
            $stmt = $pdo->prepare("
                INSERT INTO budgets (group_id, balance, total_spent, is_active, created_by) 
                VALUES (?, ?, 0, 1, ?)
            ");
            $stmt->execute([$group_id, $initial_balance, $created_by]);
        } else {
            $stmt = $pdo->prepare("
                INSERT INTO budgets (user_id, balance, total_spent, is_active, created_by) 
                VALUES (?, ?, 0, 1, ?)
            ");
            $stmt->execute([$user_id, $initial_balance, $created_by]);
        }
        
        $budget_id = $pdo->lastInsertId();
        
        return [
            'success' => true,
            'budget_id' => $budget_id,
            'message' => 'Budget created successfully',
            'new_budget' => true
        ];
        
    } catch (Exception $e) {
        return [
            'success' => false,
            'budget_id' => null,
            'message' => 'Failed to create budget: ' . $e->getMessage(),
            'new_budget' => false
        ];
    }
}

function addTokensToBudget($pdo, $budget_id, $amount, $description = 'Token credit', $created_by = 1) {
    try {
        $pdo->beginTransaction();
        
        // Get current balance
        $balance_stmt = $pdo->prepare("SELECT balance FROM budgets WHERE id = ?");
        $balance_stmt->execute([$budget_id]);
        $current_balance = $balance_stmt->fetchColumn();
        
        if ($current_balance === false) {
            throw new Exception("Budget not found");
        }
        
        $new_balance = $current_balance + $amount;
        
        // Update budget balance
        $update_stmt = $pdo->prepare("UPDATE budgets SET balance = ? WHERE id = ?");
        $update_stmt->execute([$new_balance, $budget_id]);
        
        // Log transaction
        $log_stmt = $pdo->prepare("
            INSERT INTO token_transactions 
            (budget_id, transaction_type, amount, description, balance_after, created_by) 
            VALUES (?, 'credit', ?, ?, ?, ?)
        ");
        $log_stmt->execute([$budget_id, $amount, $description, $new_balance, $created_by]);
        
        $pdo->commit();
        
        return [
            'success' => true,
            'new_balance' => $new_balance,
            'message' => "Added $amount tokens successfully. New balance: $new_balance"
        ];
        
    } catch (Exception $e) {
        $pdo->rollBack();
        return [
            'success' => false,
            'new_balance' => null,
            'message' => 'Failed to add tokens: ' . $e->getMessage()
        ];
    }
}

// Test the functions if run directly
if (basename(__FILE__) == basename($_SERVER['SCRIPT_NAME'])) {
    echo "Testing budget creation functions...\n\n";
    
    // Test creating a budget for user 1
    $result = createSafeBudget($pdo, 1, null, 50.00);
    echo "Create user budget: " . ($result['success'] ? '✓' : '✗') . " " . $result['message'] . "\n";
    
    if ($result['success']) {
        // Test adding tokens
        $add_result = addTokensToBudget($pdo, $result['budget_id'], 25.00, 'Test credit');
        echo "Add tokens: " . ($add_result['success'] ? '✓' : '✗') . " " . $add_result['message'] . "\n";
    }
    
    echo "\nDone!\n";
}
?>
