<?php

declare(strict_types=1);

namespace App\Modules\Administration\Repositories;

use System\Database\QueryBuilder;
use PDO;
use System\Contracts\DatabaseInterface;

final class DynamicFormFieldRepository
{
    private PDO $pdo;

    public function __construct(
        private QueryBuilder $query,
        DatabaseInterface $database
    ) {
        $this->pdo = $database->getConnection();
    }
public function updateOrder(
    int $id,
    int $sectionId,
    int $sortOrder
): bool {

    return $this->query
        ->table('dynamic_form_fields')
        ->where('id', $id)
        ->update([
            'section_id' => $sectionId,
            'sort_order' => $sortOrder
        ]);

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

    public function bySection(
        int $sectionId
    ): array {
        return $this->query
            ->table('dynamic_form_fields')
            ->where('section_id', $sectionId)
            ->where('status', 1)
            ->orderBy('sort_order', 'ASC')
            ->get();
    }

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

    public function findByName(
        int $formId,
        string $fieldName
    ): ?array {
        return $this->query
            ->table('dynamic_form_fields')
            ->where('form_id', $formId)
            ->where('field_name', $fieldName)
            ->first();
    }

public function create(
    array $data
): int {
    $created = $this->query
        ->table('dynamic_form_fields')
        ->insert($data);

    if (!$created) {
        return 0;
    }

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

    public function nextSortOrder(
        int $sectionId
    ): int {
        $fields = $this->bySection(
            $sectionId
        );

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

        $maximum = 0;

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

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

        return $maximum + 1;
    }
    public function deactivate(
    int $id
): bool {
    return $this->query
        ->table('dynamic_form_fields')
        ->where('id', $id)
        ->update([
            'status' => 0,
            'updated_at' => date('Y-m-d H:i:s')
        ]);
}
}