<?php
require_once __DIR__ . '/../models/Income.php';
class IncomeController {
    public function index() {
        if (!isset($_SESSION['user'])) { header('Location: index.php?controller=auth&action=login'); exit; }
        $model = new Income();
        $year = $_GET['year'] ?? date('Y');
        $month = $_GET['month'] ?? date('m');
        $incomes = $model->getByMonthYear($month, $year);
        include __DIR__ . '/../views/income/list.php';
    }

    public function add() {
        if (!isset($_SESSION['user'])) { header('Location: index.php?controller=auth&action=login'); exit; }
        $errors = []; $msg='';
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!verify_csrf($_POST['csrf'] ?? '')) { $errors[] = 'Invalid CSRF token.'; }
            $apartment = trim($_POST['apartment'] ?? '');
            $amount = trim($_POST['amount'] ?? '');
            $date = trim($_POST['date'] ?? '');
            if ($amount === '' || !is_numeric($amount)) $errors[] = 'Valid amount is required.';
            if ($date === '') $errors[] = 'Date is required.';
            if (empty($errors)) {
                $model = new Income();
                $model->create(['apartment'=>$apartment,'amount'=>$amount,'category'=>$_POST['category'] ?? '','note'=>$_POST['note'] ?? '','date'=>$date]);
                $msg = 'Income added.';
            }
        }
        include __DIR__ . '/../views/income/add.php';
    }

    public function edit() {
        if (!isset($_SESSION['user'])) { header('Location: index.php?controller=auth&action=login'); exit; }
        $id = $_GET['id'] ?? null;
        $model = new Income();
        $income = $model->get($id);
        if (!$income) { echo 'Income not found'; exit; }
        $errors = [];
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!verify_csrf($_POST['csrf'] ?? '')) { $errors[] = 'Invalid CSRF token.'; }
            $apartment = trim($_POST['apartment'] ?? '');
            $amount = trim($_POST['amount'] ?? '');
            $date = trim($_POST['date'] ?? '');
            if ($amount === '' || !is_numeric($amount)) $errors[] = 'Valid amount is required.';
            if ($date === '') $errors[] = 'Date is required.';
            if (empty($errors)) {
                $model->update($id, ['apartment'=>$apartment,'amount'=>$amount,'category'=>$_POST['category'] ?? '','note'=>$_POST['note'] ?? '','date'=>$date]);
                header('Location: index.php?controller=income&action=index');
                exit;
            }
        }
        include __DIR__ . '/../views/income/edit.php';
    }

    public function delete() {
        if (!isset($_SESSION['user'])) { header('Location: index.php?controller=auth&action=login'); exit; }
        $id = $_GET['id'] ?? null;
        $model = new Income();
        $model->delete($id);
        header('Location: index.php?controller=income&action=index');
        exit;
    }
}
?>