<?php
class ExpenseTypes extends Model
{
    public function allActive(): array
    {
        $db = new DB();
        return $db->mySelect(
            "SELECT et.c0d, et.slug, et.display_name, et.description,
                    et.gl_debit_account_id, et.scope,
                    et.requires_truck, et.requires_driver, et.requires_vendor, et.requires_trip,
                    coa.account_code AS gl_code, coa.account_name AS gl_name
               FROM expense_types et
          LEFT JOIN chart_of_accounts coa ON coa.c0d = et.gl_debit_account_id
              WHERE et.active = 1 AND et.tenant_id = :t
           ORDER BY et.sort_order ASC, et.display_name ASC",
            [':t' => defined('DEFAULT_TENANT_ID') ? DEFAULT_TENANT_ID : 1]
        ) ?: [];
    }

    public function byId(int $id): array
    {
        $db = new DB();
        $rs = $db->mySelect(
            "SELECT et.*, coa.account_code AS gl_code, coa.account_name AS gl_name
               FROM expense_types et
          LEFT JOIN chart_of_accounts coa ON coa.c0d = et.gl_debit_account_id
              WHERE et.c0d = :id LIMIT 1",
            [':id' => $id]
        );
        return $rs[0] ?? [];
    }

    public function bySlug(string $slug): array
    {
        $db = new DB();
        $rs = $db->mySelect(
            "SELECT * FROM expense_types WHERE slug = :s AND tenant_id = :t LIMIT 1",
            [':s' => trim($slug), ':t' => defined('DEFAULT_TENANT_ID') ? DEFAULT_TENANT_ID : 1]
        );
        return $rs[0] ?? [];
    }
}
