<?php
require_once __DIR__ . '/../models/Expense.php';
class ExpenseController {
    public function index() {
        if (!isset($_SESSION['user'])) { header('Location: index.php?controller=auth&action=login'); exit; }
        $model = new Expense();
        $year = $_GET['year'] ?? date('Y');
        $month = $_GET['month'] ?? date('m');
        $expenses = $model->getByMonthYear($month, $year);
        include __DIR__ . '/../views/expense/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 Expense();
                $model->create(['apartment'=>$apartment,'amount'=>$amount,'category'=>$_POST['category'] ?? '','note'=>$_POST['note'] ?? '','date'=>$date]);
                $msg = 'Expense added.';
            }
        }
        include __DIR__ . '/../views/expense/add.php';
    }

    public function edit() {
        if (!isset($_SESSION['user'])) { header('Location: index.php?controller=auth&action=login'); exit; }
        $id = $_GET['id'] ?? null;
        $model = new Expense();
        $expense = $model->get($id);
        if (!$expense) { echo 'Expense 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=expense&action=index');
                exit;
            }
        }
        include __DIR__ . '/../views/expense/edit.php';
    }

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