<?php
require_once __DIR__ . '/../config/database.php';
class Income {
    private $pdo;
    public function __construct(){ $this->pdo = Database::getInstance(); }

    public function getTotalIncome() {
    $stmt = $this->pdo->query("SELECT IFNULL(SUM(amount),0) AS total FROM incomes");
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    return $row['total'];
    }

    public function getByMonthYear($month, $year, $sumOnly=false) {
    if ($sumOnly) {
        $stmt = $this->pdo->prepare("SELECT IFNULL(SUM(amount),0) as total FROM incomes WHERE MONTH(date)=? AND YEAR(date)=?");
        $stmt->execute([$month,$year]);
        return $stmt->fetch(PDO::FETCH_ASSOC)['total'];
    } else {
        $stmt = $this->pdo->prepare("SELECT * FROM incomes WHERE MONTH(date)=? AND YEAR(date)=?");
        $stmt->execute([$month,$year]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}


    // public function getByMonthYear($month, $year) {
    //     $stmt = $this->pdo->prepare('SELECT * FROM incomes WHERE YEAR(date)=? AND MONTH(date)=? ORDER BY date DESC');
    //     $stmt->execute([$year, $month]); return $stmt->fetchAll();
    // }

    public function all() {
        $stmt = $this->pdo->query('SELECT * FROM incomes ORDER BY date DESC');
        return $stmt->fetchAll();
    }

    public function get($id) {
        $stmt = $this->pdo->prepare('SELECT * FROM incomes WHERE id = ?');
        $stmt->execute([$id]); return $stmt->fetch();
    }

    public function create($data) {
        $stmt = $this->pdo->prepare('INSERT INTO incomes (apartment, amount, category, note, date) VALUES (?,?,?,?,?)');
        return $stmt->execute([$data['apartment'],$data['amount'],$data['category'],$data['note'],$data['date']]);
    }

    public function update($id, $data) {
        $stmt = $this->pdo->prepare('UPDATE incomes SET apartment=?, amount=?, category=?, note=?, date=? WHERE id=?');
        return $stmt->execute([$data['apartment'],$data['amount'],$data['category'],$data['note'],$data['date'],$id]);
    }

    public function delete($id) {
        $stmt = $this->pdo->prepare('DELETE FROM incomes WHERE id = ?');
        return $stmt->execute([$id]);
    }
}
?>