<?php
require_once __DIR__ . '/../config/db.php';

class LaundryItemType
{
  public static function allActive(): array
  {
    $stmt = db()->query("
      SELECT code, name, sort_order
      FROM laundry_item_types
      WHERE is_active = 1
      ORDER BY sort_order ASC, name ASC
    ");
    return $stmt->fetchAll();
  }

  public static function all(): array
  {
    $stmt = db()->query("
      SELECT *
      FROM laundry_item_types
      ORDER BY is_active DESC, sort_order ASC, name ASC
    ");
    return $stmt->fetchAll();
  }

  public static function findByCode(string $code): ?array
  {
    $stmt = db()->prepare("SELECT * FROM laundry_item_types WHERE code = ? LIMIT 1");
    $stmt->execute([$code]);
    $row = $stmt->fetch();
    return $row ?: null;
  }

  public static function create(string $code, string $name, int $sortOrder = 0, int $isActive = 1): void
  {
    $stmt = db()->prepare("
      INSERT INTO laundry_item_types (code, name, sort_order, is_active, created_at, updated_at)
      VALUES (?, ?, ?, ?, NOW(), NOW())
    ");
    $stmt->execute([$code, $name, $sortOrder, $isActive]);
  }

  public static function update(string $code, string $name, int $sortOrder = 0, int $isActive = 1): void
  {
    $stmt = db()->prepare("
      UPDATE laundry_item_types
      SET name = ?, sort_order = ?, is_active = ?, updated_at = NOW()
      WHERE code = ?
    ");
    $stmt->execute([$name, $sortOrder, $isActive, $code]);
  }

  public static function delete(string $code): void
  {
    // Prevent delete if already used in items or events
    $c1 = db()->prepare("SELECT COUNT(*) c FROM laundry_bag_items WHERE item_type = ?");
    $c1->execute([$code]);
    $used1 = (int)($c1->fetch()['c'] ?? 0);

    $c2 = db()->prepare("SELECT COUNT(*) c FROM laundry_bag_events WHERE item_type = ?");
    $c2->execute([$code]);
    $used2 = (int)($c2->fetch()['c'] ?? 0);

    if ($used1 > 0 || $used2 > 0) {
      throw new Exception("Cannot delete: this item type is already used in bags/transactions. Deactivate instead.");
    }

    $stmt = db()->prepare("DELETE FROM laundry_item_types WHERE code = ?");
    $stmt->execute([$code]);
  }
}
