<?php

class ConditionOption
{
    private PDO $db;

    public function __construct()
    {
        $this->db = Database::getInstance();
    }

    public function getAll(): array
    {
        $stmt = $this->db->query('SELECT * FROM condition_options ORDER BY sort_order ASC, id ASC');
        return $stmt->fetchAll();
    }

    public function getByType(string $type): array
    {
        $stmt = $this->db->prepare('SELECT * FROM condition_options WHERE type = :type OR type = "both" ORDER BY sort_order ASC, id ASC');
        $stmt->execute(['type' => $type]);
        return $stmt->fetchAll();
    }

    public function findById(int $id): ?array
    {
        $stmt = $this->db->prepare('SELECT * FROM condition_options WHERE id = :id LIMIT 1');
        $stmt->execute(['id' => $id]);
        $row = $stmt->fetch();
        return $row ?: null;
    }

    public function create(array $data): int
    {
        $stmt = $this->db->prepare(
            'INSERT INTO condition_options (label, description, sort_order, type) VALUES (:label, :description, :sort_order, :type)'
        );
        $stmt->execute([
            'label'       => $data['label'],
            'description' => $data['description'] ?? null,
            'sort_order'  => $data['sort_order'] ?? 0,
            'type'        => $data['type'] ?? 'both',
        ]);
        return (int)$this->db->lastInsertId();
    }

    public function update(int $id, array $data): bool
    {
        $stmt = $this->db->prepare(
            'UPDATE condition_options SET label = :label, description = :description, sort_order = :sort_order, type = :type WHERE id = :id'
        );
        return $stmt->execute([
            'label'       => $data['label'],
            'description' => $data['description'] ?? null,
            'sort_order'  => $data['sort_order'] ?? 0,
            'type'        => $data['type'] ?? 'both',
            'id'          => $id,
        ]);
    }

    public function delete(int $id): bool
    {
        $stmt = $this->db->prepare('DELETE FROM condition_options WHERE id = :id');
        return $stmt->execute(['id' => $id]);
    }
}
