<?php

class MonthlyBill {
    public static function getYear($year) {
        $db = Database::getInstance();
        $months = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 
                   'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
        
        $result = [];
        foreach ($months as $month) {
            $bill = $db->fetchOne(
                "SELECT * FROM monthly_bills WHERE year = ? AND month = ?",
                [$year, $month]
            );
            $result[$month] = $bill;
        }
        
        return $result;
    }

    public static function save($data) {
        $db = Database::getInstance();

        $activeHouses = House::countActive();

        if (isset($data['amount_per_house']) && !empty($data['amount_per_house'])) {
            $amountPerHouse = $data['amount_per_house'];
        } else {
            $amountPerHouse = round($data['total_amount'] / $activeHouses, 2);
        }

        $existing = $db->fetchOne(
            "SELECT id FROM monthly_bills WHERE year = ? AND month = ?",
            [$data['year'], $data['month']]
        );

        if ($existing) {
            $db->execute(
                "UPDATE monthly_bills SET total_amount = ?, amount_per_house = ?, due_date = ? WHERE id = ?",
                [
                    $data['total_amount'],
                    $amountPerHouse,
                    $data['due_date'] ?? null,
                    $existing['id']
                ]
            );
            return $existing['id'];
        } else {
            $db->execute(
                "INSERT INTO monthly_bills (year, month, total_amount, amount_per_house, due_date)
                 VALUES (?, ?, ?, ?, ?)",
                [
                    $data['year'],
                    $data['month'],
                    $data['total_amount'],
                    $amountPerHouse,
                    $data['due_date'] ?? null
                ]
            );
            return $db->lastInsertId();
        }
    }

    public static function updatePayments($year, $month) {
        $db = Database::getInstance();
        
        $bill = $db->fetchOne(
            "SELECT * FROM monthly_bills WHERE year = ? AND month = ?",
            [$year, $month]
        );
        
        if (!$bill) {
            return false;
        }
        
        $houses = House::getActive();
        
        foreach ($houses as $house) {
            $monto_esperado = $bill['amount_per_house'];
            
            if ($house['consumption_only'] && $year >= 2025) {
                $monto_esperado = max(0, $monto_esperado - 100.00);
            }
        }
        
        return true;
    }
}
