<?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 ProfileClientsSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $file = file_get_contents('database/seeders/data/profiles-clients-imported-2.json');
        $json = json_decode($file);

        // dd(count($json));

        // Create Super User User
        User::create([
            'email' => "edgarrojas2904@gmail.com",
            'password' => '$2y$10$PLg4Hdvtsp8ZBZDOWpf9V.RH19vBtM51FBTuj2H9TcsUakxk561Ia', // 1234
            'remember_token' => Str::random(10),
            'email_verified_at' => now(),
        ]);

        // Document Types
        $v = DocumentType::where('letter', 'V')->first();
        $e = DocumentType::where('letter', 'E')->first();
        $j = DocumentType::where('letter', 'J')->first();
        $g = DocumentType::where('letter', 'G')->first();


        // Create Super User Profile
        Profile::create([
            'user_id' => 1,
            'profile_type_id' => 1,  // Root User
            // 'profile_type_id' => 3,     // Collector User
            'document_type_id' => $v->id,
            'id_card' => '18105179',
            'names' => 'Edgar Miguel',
            'surnames' => 'Rojas Samuel',
            'phone' => "04168593648",
            'address' => "Carrera 35 entre Av Andres Bello y Calle 23",
        ]);

        // Perfil de Clientes por defecto
        $client = ProfileType::where('slug', 'client')->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
            $firstLetter = strtoupper(substr($item->idCard, 0, 1));
            $documentType = $v;
            if ($firstLetter == 'J') {
                $documentType = $j;
            } else if ($firstLetter == 'G') {
                $documentType = $g;
            } else if ($firstLetter == 'E') {
                $documentType = $e;
            }

            // Now create the profile
            Profile::create([
                'user_id' => $user->id,
                'profile_type_id' => $client->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);

        }
    }
}
