<?php

namespace App\Observers;

use App\Mail\SendCredentials;
use App\Models\Company;
use App\Models\CompanyDefaultPermissions;
use App\Models\DetailUserCompany;
use App\Models\Url;
use App\Models\User;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Mail;

class CompanyObserver
{
    # Al crear
    public function created(Company $company): void
    {

        # Revisar que plan seleccionó la empresa
        switch ($company->idmembership) {
            case '1':
                $data = config("plans.plans.basic.permissions", []);
                break;
            case '2':
                $data = config("plans.plans.standar.permissions", []);
                break;
            case '3':
                $data = config("plans.plans.pro.permissions", []);
                break;
        }

        $admin      = $data['admin'];
        $seller     = $data['seller'];
        $supplier   = $data['supplier'];
        $customer   = $data['customer'];

        # Generar registros para los valores por defecto en permisos por sus tipos de usuarios
        $data = [
            [
                'idcompany'     => $company->id,
                'iduser_type'   => 2, #Administrador
                'permissions'   => json_encode($admin)
            ],
            [
                'idcompany'     => $company->id,
                'iduser_type'   => 3, #Vendedor
                'permissions'   => json_encode($seller)
            ],
            [
                'idcompany'     => $company->id,
                'iduser_type'   => 4, #Proveedor
                'permissions'   => json_encode($supplier)
            ],
            [
                'idcompany'     => $company->id,
                'iduser_type'   => 5, #Cliente
                'permissions'   => json_encode($customer)
            ]
        ];

        CompanyDefaultPermissions::insert($data);

        # Crear un administrador para la empresa y mandarlo al correo
        if ($company->id == 1) return;

        $password = $this->generatePassword($company->rut, 12);;
        $username = 'admin'.$company->rut;

        $admin = User::create([
            'rut'                   => $company->rut,
            'email'                 => $company->email,
            'username'              => $username,
            'password'              => bcrypt($password),
            'idcompany'             => $company->id,
            'encrypted_password'    => Crypt::encryptString($password),
            'status_confirm'        => 1
        ]);

        DetailUserCompany::create([
            'iduser'        => $admin->id,
            'iduser_type'   => 2,
            'idprivilege'   => 1,
            'idcompany'     => $company->id,
            'status_confirm'=> 1
        ]);

        $rut_company    = base64_encode($company->rut);
        $username       = base64_encode($username);
        $rut            = base64_encode($admin->rut);
        $password64     = base64_encode($password);
        $iduser_type    = base64_encode(2);
        $url_autologin  = Url::find(2)->url . "/?rut_company=$rut_company&username=$username&rut=$rut&password=$password64&iduser_type=$iduser_type";

        Mail::to($admin->email)->send(new SendCredentials($company->business_name, $admin->rut, 'Administrador', $password, $url_autologin));
    }

    private function generatePassword($rut, $desiredPasswordLength) {
        # Lista de caracteres especiales
        $specialCharacters = './,-_';

        # Mezclar números y caracteres especiales
        $combinedString = $rut . str_shuffle($specialCharacters);

        # Obtener la contraseña de la longitud deseada
        $password = substr(str_shuffle($combinedString), 0, $desiredPasswordLength);

        return $password;
    }
}
