<?php

namespace domain\User\User;

use common\helpers\CSV;
use domain\_\AbstractGenerator;
use yii\base\ErrorException;

class UsersCreditCsvGenerator extends AbstractGenerator
{
    protected UserSolver $userSolver;
    protected UserRepository $userRepository;

    public function loadDependencies(): void
    {
        $this->userSolver = $this->loadService(UserSolver::class);
        $this->userRepository = $this->loadService(UserRepository::class);
    }

    public function exportUsersCreditAsCsv(string $type)
    {
        if($type == 'negative') {
            $filename = 'Utilisateurs_credit_negatif.csv';
            $usersArray = $this->userRepository->findUsersWithNegativeCredit();
        }
        elseif($type == 'positive') {
            $filename = 'Utilisateurs_credit_positif.csv';
            $usersArray = $this->userRepository->findUsersWithPositiveCredit();
        }
        else {
            throw new ErrorException('Le paramètre $type est invalide.');
        }

        $data = [
            ['Client', 'Email', 'Téléphone', 'Cagnotte']
        ];
        foreach($usersArray as $user) {
            $data[] = [
                $this->userSolver->getUsernameFromArray($user, true),
                $user['email'],
                $user['phone'],
                CSV::formatNumber($user['credit']),
            ];
        }

        CSV::send($filename, $data);
    }
}