<?php

namespace MintyPHP\Repository\CustomField;

use MintyPHP\DB;

/** Retrieves selectable options for tenant-scoped custom field definitions. */
class TenantCustomFieldOptionRepository implements TenantCustomFieldOptionRepositoryInterface
{
    private static function unwrapList($rows): array
    {
        if (!is_array($rows)) {
            return [];
        }
        $list = [];
        foreach ($rows as $row) {
            $item = $row['tenant_custom_field_options'] ?? null;
            if (is_array($item)) {
                $list[] = $item;
            }
        }
        return $list;
    }

    public function listByDefinitionIds(array $definitionIds, bool $onlyActive = true): array
    {
        $definitionIds = toIntIds($definitionIds);
        if (!$definitionIds) {
            return [];
        }
        $query = 'select id, definition_id, option_key, label, active, sort_order, created, modified ' .
            'from tenant_custom_field_options where definition_id in (???)';
        $params = [$definitionIds];
        if ($onlyActive) {
            $query .= ' and active = 1';
        }
        $query .= ' order by definition_id asc, sort_order asc, label asc, id asc';
        return self::unwrapList(call_user_func_array(['MintyPHP\\DB', 'select'], array_merge([$query], $params)));
    }

    public function replaceForDefinition(int $definitionId, array $options): bool
    {
        if ($definitionId <= 0) {
            return false;
        }
        $existing = $this->listByDefinitionIds([$definitionId], false);
        $existingByKey = [];
        foreach ($existing as $row) {
            $key = (string) ($row['option_key'] ?? '');
            if ($key !== '') {
                $existingByKey[$key] = $row;
            }
        }

        $keepIds = [];
        foreach ($options as $option) {
            $optionKey = trim((string) ($option['option_key'] ?? ''));
            $label = trim((string) ($option['label'] ?? ''));
            if ($optionKey === '' || $label === '') {
                continue;
            }
            $active = !empty($option['active']) ? 1 : 0;
            $sortOrder = (int) ($option['sort_order'] ?? 100);

            if (isset($existingByKey[$optionKey]['id'])) {
                $optionId = (int) $existingByKey[$optionKey]['id'];
                $keepIds[] = $optionId;
                $updated = DB::update(
                    'update tenant_custom_field_options set label = ?, active = ?, sort_order = ? where id = ?',
                    $label,
                    (string) $active,
                    (string) $sortOrder,
                    (string) $optionId
                );
                if ($updated === false) {
                    return false;
                }
                continue;
            }

            $insertId = DB::insert(
                'insert into tenant_custom_field_options (definition_id, option_key, label, active, sort_order, created) values (?,?,?,?,?,NOW())',
                (string) $definitionId,
                $optionKey,
                $label,
                (string) $active,
                (string) $sortOrder
            );
            if ($insertId === false) {
                return false;
            }
            if ($insertId) {
                $keepIds[] = (int) $insertId;
            }
        }

        if (!$keepIds) {
            $deleted = DB::delete('delete from tenant_custom_field_options where definition_id = ?', (string) $definitionId);
            if ($deleted === false) {
                return false;
            }
            return true;
        }

        $deleted = DB::delete(
            'delete from tenant_custom_field_options where definition_id = ? and id not in (???)',
            (string) $definitionId,
            $keepIds
        );
        if ($deleted === false) {
            return false;
        }
        return true;
    }

    public function deleteByDefinitionId(int $definitionId): bool
    {
        if ($definitionId <= 0) {
            return false;
        }
        $result = DB::delete('delete from tenant_custom_field_options where definition_id = ?', (string) $definitionId);
        return $result !== false;
    }
}
