<?php
namespace App\Controllers;

use Core\Controller;
use App\Helpers\Helper;

class ExpenseController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->requireRole(['super_admin','property_owner','accountant']);
    }

    public function index(): void
    {
        $expenses = $this->db->fetchAll(
            "SELECT e.*, p.name AS property_name FROM expenses e LEFT JOIN properties p ON p.id=e.property_id ORDER BY e.expense_date DESC"
        );
        $total = array_sum(array_column(array_filter($expenses, fn($e)=>$e['status']==='approved'), 'amount'));
        $properties = $this->db->fetchAll("SELECT id,name FROM properties ORDER BY name");
        $this->adminView('expense.index', compact('expenses','total','properties') + ['title'=>'Expenses']);
    }

    public function store(): void
    {
        $this->verifyCsrf();
        $data = [
            'property_id'  => $this->input('property_id') ?: null,
            'category'     => Helper::sanitize($this->input('category','')),
            'description'  => $this->input('description',''),
            'amount'       => (float)$this->input('amount',0),
            'expense_date' => $this->input('expense_date', date('Y-m-d')),
            'vendor'       => Helper::sanitize($this->input('vendor','')) ?: null,
            'status'       => 'approved',
            'created_by'   => (int)$_SESSION['user_id'],
            'created_at'   => date('Y-m-d H:i:s'),
            'updated_at'   => date('Y-m-d H:i:s'),
        ];
        if (!empty($_FILES['receipt']['name'])) {
            $path = Helper::uploadFile($_FILES['receipt'],'documents',ALLOWED_DOC_TYPES);
            if ($path) $data['receipt'] = $path;
        }
        $this->db->insert('expenses', $data);
        Helper::setFlash('success','Expense recorded.');
        $this->redirect(APP_URL.'/admin/expenses');
    }

    public function update(string $id): void
    {
        $this->verifyCsrf();
        $this->db->update('expenses', [
            'category'    => Helper::sanitize($this->input('category','')),
            'description' => $this->input('description',''),
            'amount'      => (float)$this->input('amount',0),
            'expense_date'=> $this->input('expense_date'),
            'status'      => $this->input('status','approved'),
            'updated_at'  => date('Y-m-d H:i:s'),
        ], 'id=?', [$id]);
        Helper::setFlash('success','Expense updated.');
        $this->redirect(APP_URL.'/admin/expenses');
    }

    public function destroy(string $id): void
    {
        $this->verifyCsrf();
        $this->db->delete('expenses','id=?',[$id]);
        Helper::setFlash('success','Expense deleted.');
        $this->redirect(APP_URL.'/admin/expenses');
    }
}
