<?php

namespace App\DataFixtures;

use App\Entity\MemberCase;
use App\Entity\StaffNote;
use App\Enums\ReferralServiceType;
use DateTime;
use DateTimeZone;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
use Doctrine\Persistence\ObjectManager;

class StaffNoteFixture extends Fixture implements DependentFixtureInterface
{
    public function load(ObjectManager $manager): void
    {
        if(!$_ENV['CREATE_STAFF_NOTES']) {
            return;
        }
        $cases = $manager->getRepository(MemberCase::class)->findAll();

        $gen = \Faker\Factory::create();

        foreach ($cases as $case) {
            /** @var MemberCase $case */
            $note = new StaffNote();
            $admitDate = new DateTime($case->getAdmitDate()?->format('Y-m-d').' '.$gen->time('H:i:s'), new DateTimeZone($_ENV['COMPANY_TIMEZONE']));
            $admitDate->add(\DateInterval::createFromDateString('7 day'));
            $note->setDate($admitDate);
            $note->setMemberCase($case);
            $note->setServicesProvided($gen->randomElements(ReferralServiceType::class, $gen->numberBetween(1, 3)));

            while ($admitDate->getTimestamp() < time()) {
                $workerSignDatetime = clone $admitDate;
                $workerSignDatetime->setTime($gen->time('H'), $gen->time('i'), $gen->time('s'));
                $workerSignDatetime->add(\DateInterval::createFromDateString('1 day'));
                $note->setWorkerSignDatetime($workerSignDatetime);

                $supervisorSignDatetime = clone $admitDate;
                $supervisorSignDatetime->setTime($gen->time('H'), $gen->time('i'), $gen->time('s'));
                $supervisorSignDatetime->add(\DateInterval::createFromDateString('1 day'));
                $note->setSupervisorSignDatetime($supervisorSignDatetime);

                $note->setNote($gen->text(200));
                $note->setRecommendations($gen->text(20));

                $manager->persist($note);

                $admitDate->add(\DateInterval::createFromDateString('14 days'));
                $note = clone $note;
                $note->setDate(clone $admitDate);
            }
        }

        $manager->flush();
    }

    public function getDependencies(): array
    {
        return [
            MemberCaseFixture::class,
        ];
    }
}
