<?php

declare(strict_types=1);

namespace App\Modules\Administration\Repositories;

use System\Database\QueryBuilder;

final class DynamicFormSectionRepository
{
    public function __construct(
        private QueryBuilder $query
    ) {
    }

public function byForm(
    int $formId
): array {
    return $this->query
        ->table('dynamic_form_sections')
        ->where('form_id', $formId)
        ->where('status', 1)
        ->orderBy('sort_order', 'ASC')
        ->get();
}

    public function find(
        int $id
    ): ?array {
        return $this->query
            ->table('dynamic_form_sections')
            ->find($id);
    }

    public function create(
        array $data
    ): bool {
        return $this->query
            ->table('dynamic_form_sections')
            ->insert($data);
    }

    public function update(
        int $id,
        array $data
    ): bool {
        return $this->query
            ->table('dynamic_form_sections')
            ->where('id', $id)
            ->update($data);
    }

    public function nextSortOrder(
        int $formId
    ): int {
        $sections = $this->byForm($formId);

        if (empty($sections)) {
            return 1;
        }

        $maximum = 0;

        foreach ($sections as $section) {
            $order = (int) (
                $section['sort_order']
                ?? 0
            );

            if ($order > $maximum) {
                $maximum = $order;
            }
        }

        return $maximum + 1;
    }
    public function hasActiveFields(
    int $sectionId
): bool {
    $fields = $this->query
        ->table('dynamic_form_fields')
        ->where('section_id', $sectionId)
        ->where('status', 1)
        ->get();

    return !empty($fields);
}


public function deactivate(
    int $id
): bool {
    return $this->query
        ->table('dynamic_form_sections')
        ->where('id', $id)
        ->update([
            'status' =>
                0,

            'updated_at' =>
                date('Y-m-d H:i:s')
        ]);
}
}