<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\User;
use App\Models\Profile;
use App\Models\DocumentType;
use App\Models\ProfileType;
use Illuminate\Support\Str;

class ProfileWorkersSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $file = file_get_contents('database/seeders/data/profiles-workers-imported.json');
        $json = json_decode($file);

        // Document Types
        $v = DocumentType::where('letter', 'V')->first();

        // Perfil de Recaudador por defecto
        $collector = ProfileType::where('slug', 'collector')->first();

        $index = 0;
        $total = count($json);

        foreach ($json as $item) {
            // Verify if the email exist
            $email = ($item->email == '') ? fake()->unique()->safeEmail() : strtolower($item->email);

            // Verify that the email be unique
            $userVerify = User::where('email', $email)->first();
            if ($userVerify) {
                $email = fake()->unique()->safeEmail();
            }

            // Create User Profile
            $user = User::create([
                'email' => $email,
                'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
                'remember_token' => Str::random(10),
                'email_verified_at' => now(),
            ]);

            // Define Document Type
            $documentType = $v;

            // Now create the profile
            Profile::create([
                'user_id' => $user->id,
                'profile_type_id' => $collector->id,
                'document_type_id' => $documentType->id,
                'id_card' => $this->sanitizeNumber($item->idCard),
                'names' => $this->formatWords($item->names),
                'surnames' => ($item->surnames == '') ? null : $this->formatWords($item->surnames),
                'phone' => ($item->phone == '') ? null : $this->sanitizeNumber($item->phone),
                'address' => ($item->address == '') ? null : $this->cleanAddress($item->address)
            ]);
            $this->printProgress($total, $index);
            $index++;
        }
    }

    private function sanitizeNumber(string $number): string
    {
        $charsToClean = ['V', 'G', 'J', 'E', ' ', ',', '.', '-'];
        return str_replace($charsToClean, '', strtoupper($number));
    }

    private function formatWords(string $word): string
    {
        $formatedWord = ucwords(strtolower($word));
        $formatedWord = str_replace(' S.a.c.a.', ' S.A.C.A.', $formatedWord);
        $formatedWord = str_replace(' C.a.', ' C.A.', $formatedWord);
        $formatedWord = str_replace(' S.a.', ' S.A.', $formatedWord);
        return $formatedWord;
    }

    private function cleanAddress(string $word): string
    {
        return ucfirst(strtolower($word));
    }

    private function printProgress($total, $index): void
    {
        // Print progress every $steps%
        $steps = 50;
        $ratio = 50;
        $progress = round($index * 100 * $ratio / $total);
        if ( $progress % $steps == 0 ) {
            print('....'. ($progress / $ratio) .'%');
        }
        if($total == ($index + 1)) {
            print(PHP_EOL. PHP_EOL. '      FINISHED!!' . PHP_EOL. PHP_EOL);

        }
    }
}
