<?php
/**
 * Budget Alert Functions
 */

/**
 * Check budgets and send alerts for approaching/exceeding thresholds
 */
function checkBudgetAlerts() {
    global $pdo;
    
    if (!isset($pdo)) {
        return false;
    }
    
    // Ensure budgets table exists
    try {
        $pdo->query('SELECT 1 FROM budgets LIMIT 1');
    } catch (PDOException $e) {
        return false; // No budgets table
    }
    
    $currentYear = (int)date('Y');
    $currentMonth = (int)date('m');
    $currentQuarter = ceil($currentMonth / 3);
    
    try {
        // Get all active budgets for current year
        $budgetsStmt = $pdo->prepare("
            SELECT b.*, f.name AS fund_name
            FROM budgets b
            JOIN funds f ON b.fund_id = f.id
            WHERE b.budget_year = ?
        ");
        $budgetsStmt->execute([$currentYear]);
        $budgets = $budgetsStmt->fetchAll();
        
        $alerts = [];
        
        foreach ($budgets as $budget) {
            $startDate = $currentYear . '-01-01';
            $endDate = $currentYear . '-12-31';
            
            // Adjust date range based on period
            if ($budget['budget_period'] === 'monthly' && $budget['period_value']) {
                $month = (int)$budget['period_value'];
                if ($month === $currentMonth) {
                    $startDate = sprintf('%d-%02d-01', $currentYear, $month);
                    $endDate = date('Y-m-t', strtotime($startDate));
                } else {
                    continue; // Not current month
                }
            } elseif ($budget['budget_period'] === 'quarterly' && $budget['period_value']) {
                $quarter = (int)$budget['period_value'];
                if ($quarter === $currentQuarter) {
                    $startMonth = ($quarter - 1) * 3 + 1;
                    $startDate = sprintf('%d-%02d-01', $currentYear, $startMonth);
                    $endDate = date('Y-m-t', strtotime(sprintf('%d-%02d-01', $currentYear, $startMonth + 2)));
                } else {
                    continue; // Not current quarter
                }
            }
            // yearly budgets always apply
            
            // Get actual amount
            $actualStmt = $pdo->prepare("
                SELECT COALESCE(SUM(amount), 0) AS total
                FROM transactions
                WHERE fund_id = ? AND transaction_date BETWEEN ? AND ?
            ");
            $actualStmt->execute([$budget['fund_id'], $startDate, $endDate]);
            $actual = (float)$actualStmt->fetchColumn();
            $budgetAmount = (float)$budget['amount'];
            
            if ($budgetAmount <= 0) continue;
            
            $percent = ($actual / $budgetAmount) * 100;
            
            // Check thresholds
            $alertThreshold = (float)getSetting('budget_alert_threshold', '80'); // Default 80%
            $exceedThreshold = (float)getSetting('budget_exceed_threshold', '100'); // Default 100%
            
            if ($percent >= $exceedThreshold) {
                $alerts[] = [
                    'type' => 'exceeded',
                    'fund' => $budget['fund_name'],
                    'budget' => $budgetAmount,
                    'actual' => $actual,
                    'percent' => $percent,
                    'period' => $budget['budget_period'],
                    'period_value' => $budget['period_value']
                ];
            } elseif ($percent >= $alertThreshold) {
                $alerts[] = [
                    'type' => 'approaching',
                    'fund' => $budget['fund_name'],
                    'budget' => $budgetAmount,
                    'actual' => $actual,
                    'percent' => $percent,
                    'period' => $budget['budget_period'],
                    'period_value' => $budget['period_value']
                ];
            }
        }
        
        return $alerts;
    } catch (PDOException $e) {
        error_log('Budget alert check error: ' . $e->getMessage());
        return false;
    }
}

/**
 * Get budget alerts for display
 */
function getBudgetAlerts() {
    return checkBudgetAlerts();
}
