<?php

class Payment {
    public static function getMatrix($year) {
        $db = Database::getInstance();
        
        $houses = $db->fetchAll(
            "SELECT h.id, h.number, h.status, h.consumption_only, h.owner_name 
             FROM houses h 
             ORDER BY CAST(h.number AS UNSIGNED)"
        );

        $months = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 
                   'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];

        $payments = [];
        foreach ($months as $month) {
            $monthPayments = $db->fetchAll(
                "SELECT house_id, amount, payment_date 
                 FROM payments 
                 WHERE year = ? AND month = ?",
                [$year, $month]
            );
            $payments[$month] = [];
            foreach ($monthPayments as $p) {
                $payments[$month][$p['house_id']] = $p;
            }
        }

        return ['houses' => $houses, 'payments' => $payments, 'months' => $months];
    }

    public static function getExpectedAmount($house, $year, $month) {
        $db = Database::getInstance();
        
        $bill = $db->fetchOne(
            "SELECT * FROM monthly_bills WHERE year = ? AND month = ?",
            [$year, $month]
        );

        if (!$bill) {
            return 0;
        }

        $monto_base = $bill['amount_per_house'];

        if ($house['consumption_only'] && $year >= 2025) {
            $monto_base = max(0, $monto_base - 100.00);
        }

        return round($monto_base, 2);
    }

    public static function update($houseId, $year, $month, $amount, $userId, $notes = null, $paymentMethod = null) {
        $db = Database::getInstance();

        $existing = $db->fetchOne(
            "SELECT id FROM payments WHERE house_id = ? AND year = ? AND month = ?",
            [$houseId, $year, $month]
        );

        if ($amount == 0 && $existing) {
            $db->execute(
                "DELETE FROM payments WHERE id = ?",
                [$existing['id']]
            );
            return ['success' => true, 'deleted' => true];
        }

        if ($existing) {
            $db->execute(
                "UPDATE payments SET amount = ?, payment_date = NOW(), notes = ?, payment_method = ?, created_by = ? WHERE id = ?",
                [$amount, $notes, $paymentMethod, $userId, $existing['id']]
            );
        } else {
            $db->execute(
                "INSERT INTO payments (house_id, year, month, amount, payment_date, notes, payment_method, created_by) 
                 VALUES (?, ?, ?, ?, NOW(), ?, ?, ?)",
                [$houseId, $year, $month, $amount, $notes, $paymentMethod, $userId]
            );
        }

        return ['success' => true, 'deleted' => false];
    }

    public static function getByHouse($houseId, $year = null) {
        $db = Database::getInstance();
        
        if ($year) {
            return $db->fetchAll(
                "SELECT * FROM payments WHERE house_id = ? AND year = ? ORDER BY FIELD(month, 'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre')",
                [$houseId, $year]
            );
        }
        
        return $db->fetchAll(
            "SELECT * FROM payments WHERE house_id = ? ORDER BY year DESC, FIELD(month, 'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre') DESC",
            [$houseId]
        );
    }

    public static function getTotalByYear($year) {
        $db = Database::getInstance();
        $result = $db->fetchOne(
            "SELECT COALESCE(SUM(amount), 0) as total FROM payments WHERE year = ?",
            [$year]
        );
        return $result['total'] ?? 0;
    }
}
