<?php
require_auth();
$method = $_SERVER['REQUEST_METHOD']; $d = input();
if ($method === 'GET') {
    require_permission('finance.view');
    $s = db()->query('SELECT e.*, p.name AS property_name FROM expenses e LEFT JOIN properties p ON p.id=e.property_id ORDER BY expense_date DESC LIMIT 500');
    json_ok($s->fetchAll());
}
csrf_check();
if ($method === 'POST') {
    require_permission('finance.manage');
    $err = v_required($d, ['description','amount','expense_date']);
    if ($err) json_error('Validation failed',422,$err);
    db()->prepare('INSERT INTO expenses (property_id,category,description,amount,currency,expense_date,created_by) VALUES (?,?,?,?,?,?,?)')
        ->execute([!empty($d['property_id'])?(int)$d['property_id']:null, v_str($d,'category',80) ?: 'general', v_str($d,'description',255), v_positive_number($d['amount'], 'amount'), substr($d['currency']??'USD',0,8), v_date($d['expense_date'], 'expense_date'), current_user()['id']??null]);
    audit('expense.create','expense', db()->lastInsertId());
    json_ok([], 'Expense recorded');
}
if ($method === 'DELETE') {
    require_permission('finance.manage');
    $id = (int)($d['id'] ?? 0);
    if (!$id) json_error('id required',422);
    db()->prepare('DELETE FROM expenses WHERE id=?')->execute([$id]);
    audit('expense.delete','expense',$id);
    json_ok([], 'Deleted');
}
json_error('Method not allowed',405);
