<?php
class ExpenseController {
    private $db;
    public function __construct() { $this->db = Database::getInstance(); }

    public function index() {
        $search = $_GET['search'] ?? ''; $category = $_GET['category'] ?? '';
        $page = max(1, intval($_GET['pg'] ?? 1)); $perPage = ITEMS_PER_PAGE; $cid = Auth::user()['company_id'];
        $where = "WHERE e.deleted_at IS NULL AND e.company_id = ?"; $params = [$cid];
        if ($search) { $where .= " AND (e.description LIKE ? OR v.company_name LIKE ?)"; $s = "%$search%"; $params = array_merge($params, [$s,$s]); }
        if ($category) { $where .= " AND e.category = ?"; $params[] = $category; }
        $total = $this->db->fetchColumn("SELECT COUNT(*) FROM expenses e LEFT JOIN vendors v ON e.vendor_id=v.id $where", $params);
        $offset = ($page - 1) * $perPage;
        $expenses = $this->db->fetchAll("SELECT e.*, v.company_name as vendor_name, p.name as property_name FROM expenses e LEFT JOIN vendors v ON e.vendor_id=v.id LEFT JOIN properties p ON e.property_id=p.id $where ORDER BY e.expense_date DESC LIMIT $perPage OFFSET $offset", $params);
        $monthTotal = $this->db->fetchColumn("SELECT COALESCE(SUM(amount),0) FROM expenses WHERE company_id=? AND deleted_at IS NULL AND MONTH(expense_date)=MONTH(CURDATE()) AND YEAR(expense_date)=YEAR(CURDATE())", [$cid]);
        $pagination = paginationHtml($total, $page, $perPage, '?page=expenses');
        require 'app/views/expenses/index.php';
    }

    public function create() {
        $expense = null; $cid = Auth::user()['company_id'];
        $vendors = $this->db->fetchAll("SELECT id, company_name FROM vendors WHERE company_id=? AND deleted_at IS NULL ORDER BY company_name", [$cid]);
        $properties = $this->db->fetchAll("SELECT id, name FROM properties WHERE company_id=? AND deleted_at IS NULL ORDER BY name", [$cid]);
        require 'app/views/expenses/form.php';
    }

    public function store() {
        CSRF::verify();
        $v = new Validator($_POST); $v->required('description')->required('amount')->required('expense_date');
        if ($v->fails()) { flash('error', implode('<br>', $v->errors())); redirect('?page=expenses&action=create'); }
        $this->db->insert('expenses', [
            'company_id' => Auth::user()['company_id'], 'property_id' => $_POST['property_id'] ?: null,
            'unit_id' => $_POST['unit_id'] ?: null, 'vendor_id' => $_POST['vendor_id'] ?: null,
            'category' => $_POST['category'] ?? null, 'description' => $_POST['description'],
            'amount' => $_POST['amount'], 'expense_date' => $_POST['expense_date'],
            'payment_method' => $_POST['payment_method'] ?? null, 'reference_number' => $_POST['reference_number'] ?? null,
            'notes' => $_POST['notes'] ?? null,
        ]);
        flash('success', 'Expense recorded.'); redirect('?page=expenses');
    }

    public function edit($id) {
        $cid = Auth::user()['company_id'];
        $expense = $this->db->fetch("SELECT * FROM expenses WHERE id=? AND company_id=? AND deleted_at IS NULL", [$id, $cid]);
        if (!$expense) { flash('error', 'Expense not found.'); redirect('?page=expenses'); }
        $vendors = $this->db->fetchAll("SELECT id, company_name FROM vendors WHERE company_id=? AND deleted_at IS NULL ORDER BY company_name", [$cid]);
        $properties = $this->db->fetchAll("SELECT id, name FROM properties WHERE company_id=? AND deleted_at IS NULL ORDER BY name", [$cid]);
        require 'app/views/expenses/form.php';
    }

    public function update($id) {
        CSRF::verify();
        $this->db->update('expenses', [
            'property_id' => $_POST['property_id'] ?: null, 'unit_id' => $_POST['unit_id'] ?: null,
            'vendor_id' => $_POST['vendor_id'] ?: null, 'category' => $_POST['category'] ?? null,
            'description' => $_POST['description'], 'amount' => $_POST['amount'],
            'expense_date' => $_POST['expense_date'], 'payment_method' => $_POST['payment_method'] ?? null,
            'reference_number' => $_POST['reference_number'] ?? null, 'notes' => $_POST['notes'] ?? null,
        ], 'id = ? AND company_id = ?', [$id, Auth::user()['company_id']]);
        flash('success', 'Expense updated.'); redirect('?page=expenses');
    }

    public function delete($id) {
        CSRF::verify();
        $this->db->softDelete('expenses', 'id = ? AND company_id = ?', [$id, Auth::user()['company_id']]);
        flash('success', 'Expense deleted.'); redirect('?page=expenses');
    }
}
