<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\PersonBundle\DataFixtures\ORM;

use Chill\CustomFieldsBundle\CustomFields\CustomFieldChoice;
use Chill\CustomFieldsBundle\CustomFields\CustomFieldText;
use Chill\CustomFieldsBundle\CustomFields\CustomFieldTitle;
use Chill\CustomFieldsBundle\Entity\CustomField;
use Chill\CustomFieldsBundle\Entity\CustomFieldsDefaultGroup;
use Chill\CustomFieldsBundle\Entity\CustomFieldsGroup;
use Chill\PersonBundle\Entity\Person;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ObjectManager;

class LoadCustomFields extends AbstractFixture implements OrderedFixtureInterface
{
    private ?CustomField $cfText = null;

    private ?CustomField $cfChoice = null;

    /**
     * /**
     * LoadCustomFields constructor.
     */
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
        private readonly CustomFieldChoice $customFieldChoice,
        private readonly CustomFieldText $customFieldText,
    ) {}

    // put your code here
    public function getOrder(): int
    {
        return 10003;
    }

    public function load(ObjectManager $manager): void
    {
        $this->loadFields($manager);
        $this->loadData($manager);
        $manager->flush();
    }

    private function createCustomFieldChoice()
    {
        return $this->customFieldChoice;
    }

    private function createCustomFieldText()
    {
        return $this->customFieldText;
    }

    private function loadData(ObjectManager $manager)
    {
        $personIds = $this->entityManager
            ->createQuery('SELECT person.id FROM ChillPersonBundle:Person person')
            ->getScalarResult();

        // get possible values for cfGroup
        $choices = array_map(
            static fn ($a) => $a['slug'],
            $this->cfChoice->getOptions()['choices']
        );
        // create faker
        $faker = \Faker\Factory::create('fr_FR');
        // select a set of people and add data
        foreach ($personIds as $id) {
            // add info on 1 person on 2
            if (1 === random_int(0, 1)) {
                /** @var Person $person */
                $person = $manager->getRepository(Person::class)->find($id);
                $person->setCFData([
                    'remarques' => $this->createCustomFieldText()
                        ->serialize($faker->text(random_int(150, 250)), $this->cfText),
                    'document-d-identite' => $this->createCustomFieldChoice()
                        ->serialize([$choices[array_rand($choices)]], $this->cfChoice),
                ]);
            }
        }
    }

    private function loadFields(ObjectManager $manager)
    {
        $cfGroup = (new CustomFieldsGroup())
            ->setEntity(Person::class)
            ->setName(['fr' => 'Données']);
        $manager->persist($cfGroup);

        // make this group default for Person::class
        $manager->persist(
            (new CustomFieldsDefaultGroup())
                ->setCustomFieldsGroup($cfGroup)
                ->setEntity(Person::class)
        );

        // create title field
        $customField0 = (new CustomField())
            ->setActive(true)
            ->setName(['fr' => 'Données personnalisées'])
            ->setSlug('personal-data')
            ->setOrdering(10)
            ->setType('title')
            ->setOptions([CustomFieldTitle::TYPE => CustomFieldTitle::TYPE_TITLE])
            ->setCustomFieldsGroup($cfGroup);
        $manager->persist($customField0);

        // create text field
        $this->cfText = $customFieldText = (new CustomField())
            ->setActive(true)
            ->setName(['fr' => 'Remarques'])
            ->setSlug('remarques')
            ->setOrdering(20)
            ->setType('text')
            ->setOptions(['maxLength' => 5000])
            ->setCustomFieldsGroup($cfGroup);
        $manager->persist($customFieldText);

        // create choice field
        $this->cfChoice = $customFieldChoice = (new CustomField())
            ->setActive(true)
            ->setName(['fr' => "Document d'identité"])
            ->setSlug('document-d-identite')
            ->setOrdering(30)
            ->setType('choice')
            ->setCustomFieldsGroup($cfGroup)
            ->setOptions([
                'multiple' => true,
                'other' => false,
                'expanded' => true,
                'active' => true,
                'slug' => 'document-d-identite',
                'choices' => [
                    [
                        'name' => ['fr' => "Carte d'identité"],
                        'active' => true,
                        'slug' => 'carte-d-identite',
                    ],
                    [
                        'name' => ['fr' => 'Passeport'],
                        'active' => true,
                        'slug' => 'passeport',
                    ],
                    [
                        'name' => ['fr' => 'Titre de séjour'],
                        'active' => true,
                        'slug' => 'passeport',
                    ],
                ],
            ]);
        $manager->persist($customFieldChoice);
    }
}
