<?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\TicketBundle\DataFixtures\ORM;

use Chill\DocStoreBundle\Entity\StoredObject;
use Chill\DocStoreBundle\Service\StoredObjectManagerInterface;
use Chill\TicketBundle\Entity\Motive;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Bundle\FixturesBundle\FixtureGroupInterface;
use Doctrine\Persistence\ObjectManager;

final class LoadMotives extends Fixture implements FixtureGroupInterface
{
    public function __construct(private readonly StoredObjectManagerInterface $storedObjectManager) {}

    public static function getGroups(): array
    {
        return ['ticket'];
    }

    public function load(ObjectManager $manager)
    {
        $docs = [
            ['label' => '🌙 De 21h à 07h du matin', 'path' => __DIR__.'/docs/peloton_1.pdf'],
            ['label' => '☀️ De 07h à 21h', 'path' => __DIR__.'/docs/peloton_2.pdf'],
            ['label' => 'Dimanche et jours fériés', 'path' => __DIR__.'/docs/schema_1.png'],
        ];
        $motivesByLabel = [];

        foreach (explode("\n", self::MOTIVES) as $row) {
            if ('' === trim($row)) {
                continue;
            }

            $data = str_getcsv($row);
            if ('' === $data[0]) {
                continue;
            }

            $labels = explode(' > ', (string) $data[0]);
            $parent = null;

            while (count($labels) > 0) {
                $label = array_shift($labels);
                dump($labels);
                if (isset($motivesByLabel[$label])) {
                    $motive = $motivesByLabel[$label];
                } else {
                    $motive = new Motive();
                    $motive->setLabel(['fr' => $label]);
                    $motivesByLabel[$label] = $motive;
                }

                if (null !== $parent) {
                    $motive->setParent($parent);
                }

                $manager->persist($motive);
                $parent = $motive;

                if (0 === count($labels)) {
                    // this is the last one, we add data
                    $numberOfDocs = (int) $data[2];
                    for ($i = 1; $i <= $numberOfDocs; ++$i) {
                        $doc = $docs[$i - 1];
                        $storedObject = new StoredObject();
                        $storedObject->setTitle($doc['label']);

                        $content = file_get_contents($doc['path']);
                        $contentType = match (substr($doc['path'], -3, 3)) {
                            'pdf' => 'application/pdf',
                            'png' => 'image/png',
                            default => throw new \UnexpectedValueException('Not supported content type here'),
                        };
                        $this->storedObjectManager->write($storedObject, $content, $contentType);

                        $motive->addStoredObject($storedObject);
                        $manager->persist($storedObject);
                    }


                    foreach (array_slice($data, 3) as $supplementaryComment) {
                        if ('' !== trim((string) $supplementaryComment)) {
                            $motive->addSupplementaryComment(['label' => trim((string) $supplementaryComment)]);
                        }
                    }
                }
            }
        }
        $manager->flush();
    }

    private const MOTIVES = <<<'CSV'
        "Motif administratif > Coordonnées",false,"3","Nouvelles coordonnées",
        "Organisation > Horaire de passage",false,"0",
        "Organisation > Livraison > Retard de livraison",false,"0",
        "Organisation > Livraison > Erreur de livraison",false,"0",
        "Organisation > Livraison > Colis incomplet",false,"0",
        "MATLOC",false,"0",
        "Retard DASRI",false,"1",
        "Planning d'astreintes",false,"0",
        "Planning des tournées",false,"0",
        "Contrôle pompe",true,"0",
        "Changement de rendez-vous",false,"0","Date du nouveau rendez-vous","Lieu du nouveau rendez-vous",
        "Renseignement facturation/prestation",false,"0",
        "Décès patient",false,"0","Date et heures du décès","Autorisation préalable du médecin pour le décès",
        "Demande de prise en charge",false,"0",
        "Information absence",false,"0",
        "Demande bulletin de situation",false,"0",
        "Difficultés accès logement",false,"0",
        "Déplacement inutile",false,"0",
        "Problème de prélèvement/de commande",false,"0",
        "Parc auto",false,"0",
        "Demande d'admission",false,"0",
        "Retrait de matériel au domicile",false,"0",
        "Comptes-rendus",false,"0",
        "Démarchage commercial",false,"0",
        "Demande de transport",false,"0",
        "Demande laboratoire",false,"0",
        "Demande admission",false,"0",
        "Suivi de prise en charge",false,"0",
        "Mauvaise adresse",false,"0",
        "Patient absent",false,"0",
        "Annulation",false,"0",
        "Organisation > Livraison > Colis perdu",false,"0",
        "Changement de rendez-vous",false,"0",
        "Coordination interservices",false,"0",
        "Problème de substitution produits",true,"0",
        "Problème ordonnance",false,"3",
        "Réclamations facture",false,"0","Numéro de facture concerné",
        "Préparation urgente",true,"3",
        CSV;
}
