<?php
/**
 * CalloutCategories — Slice 8S-1 · Services Master Data
 *
 * Emergency / Urgent / Routine categories with per-category SLA targets (response +
 * restoration hours) and optional per-hour penalty %. Contracts can override per-project
 * in Slice S2 via service_contract_slas.
 */
class CalloutCategories extends Model
{
    public function all(bool $activeOnly = false): array
    {
        $db = new DB();
        $where = $activeOnly ? "WHERE is_active = 1" : '';
        return $db->mySelect(
            "SELECT c0d, code, name, priority, sla_response_hrs, sla_restoration_hrs,
                    penalty_pct_per_hr, color_hex, is_active
               FROM callout_categories
              $where
              ORDER BY priority",
            []
        ) ?: [];
    }

    public function find(int $id): array
    {
        $db = new DB();
        $r  = $db->mySelect("SELECT * FROM callout_categories WHERE c0d = :id", [':id' => $id]);
        return $r[0] ?? [];
    }

    public function save(array $d): int
    {
        $code = strtoupper(trim((string)($d['code'] ?? '')));
        $name = trim((string)($d['name'] ?? ''));
        if ($code === '' || $name === '') throw new InvalidArgumentException('Code + name required.');
        $db = new DB();
        $id = (int)($d['c0d'] ?? 0);
        $data = [
            ':c'   => $code,
            ':n'   => $name,
            ':p'   => max(1, (int)($d['priority'] ?? 3)),
            ':sr'  => !empty($d['sla_response_hrs']) ? (int)$d['sla_response_hrs'] : null,
            ':srr' => !empty($d['sla_restoration_hrs']) ? (int)$d['sla_restoration_hrs'] : null,
            ':pn'  => isset($d['penalty_pct_per_hr']) && $d['penalty_pct_per_hr'] !== '' ? (float)$d['penalty_pct_per_hr'] : null,
            ':col' => trim((string)($d['color_hex'] ?? '')) ?: null,
            ':a'   => !empty($d['is_active']) ? 1 : 0,
        ];
        if ($id > 0) {
            $data[':id'] = $id;
            $db->insertUpdate(
                "UPDATE callout_categories SET code=:c, name=:n, priority=:p, sla_response_hrs=:sr,
                    sla_restoration_hrs=:srr, penalty_pct_per_hr=:pn, color_hex=:col, is_active=:a
                  WHERE c0d=:id",
                $data
            );
            return $id;
        }
        $fb = $db->insertUpdate(
            "INSERT INTO callout_categories (code, name, priority, sla_response_hrs, sla_restoration_hrs,
                penalty_pct_per_hr, color_hex, is_active)
             VALUES (:c, :n, :p, :sr, :srr, :pn, :col, 1)",
            $data
        );
        return (int)($fb['last_id'] ?? 0);
    }

    public function delete(int $id): void
    {
        $db = new DB();
        $db->insertUpdate("DELETE FROM callout_categories WHERE c0d = :id", [':id' => $id]);
    }
}
