<?php
class PagoMensual extends Conectar {

    public function listar_pagos_mes($mes, $anio) {
        $conectar = parent::conexion();
        parent::set_names();

        $sql = "SELECT f.fic_id, f.fic_nom, f.fic_run, f.fic_valor_mes,
                       COALESCE(p.comprobante, '-') AS comprobante,
                       CASE 
                           WHEN p.id_pago IS NOT NULL THEN 'Pagado'
                           ELSE 'Pendiente'
                       END AS estado
                FROM tm_ficha f
                LEFT JOIN tm_pagos_mensuales p
                       ON f.fic_id = p.fic_id 
                      AND p.mes_pago = ?
                      AND p.anio_pago = ?
                WHERE f.fic_alumno = 1 AND f.fic_estado = 1";
        $stmt = $conectar->prepare($sql);
        $stmt->execute([$mes, $anio]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function registrar_pago($fic_id, $comprobante, $mes, $anio) {
        $conectar = parent::conexion();
        parent::set_names();

        // Evitar duplicados del mismo mes/año
        $sql = "SELECT * FROM tm_pagos_mensuales WHERE fic_id = ? AND mes_pago = ? AND anio_pago = ?";
        $stmt = $conectar->prepare($sql);
        $stmt->execute([$fic_id, $mes, $anio]);
        if ($stmt->fetch()) return false;

        $sql = "INSERT INTO tm_pagos_mensuales (fic_id, mes_pago, anio_pago, fecha_pago, comprobante, monto)
                SELECT ?, ?, ?, CURDATE(), ?, fic_valor_mes
                FROM tm_ficha WHERE fic_id = ?";
        $stmt = $conectar->prepare($sql);
        $stmt->execute([$fic_id, $mes, $anio, $comprobante, $fic_id]);
        return true;
    }
}
?>
