<?php
require_once '../config/database.php';
require_once '../config/auth_enhanced.php';

if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized access']);
    exit;
}

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

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    $stmt = $pdo->prepare("
        SELECT 
            id,
            name,
            description,
            budget_limit,
            created_at,
            updated_at,
            (SELECT COALESCE(SUM(amount), 0) 
             FROM transactions 
             WHERE category_id = expense_categories.id 
             AND YEAR(created_at) = YEAR(NOW())) as yearly_spent,
            (SELECT COUNT(*) 
             FROM transactions 
             WHERE category_id = expense_categories.id) as transaction_count
        FROM expense_categories 
        ORDER BY name ASC
    ");
    $stmt->execute();
    $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Calculate budget usage percentages
    foreach ($categories as &$category) {
        if ($category['budget_limit'] > 0) {
            $category['budget_usage_percent'] = round(($category['yearly_spent'] / $category['budget_limit']) * 100, 2);
        } else {
            $category['budget_usage_percent'] = 0;
        }
        
        // Format amounts
        $category['budget_limit'] = number_format($category['budget_limit'], 2);
        $category['yearly_spent'] = number_format($category['yearly_spent'], 2);
    }
    
    echo json_encode($categories);
    
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}
?>
