<?php

namespace App\Services;

use App\Http\Resources\CompanyResource;
use App\Models\Company;
use App\Models\CompanyConfiguration;
use App\Models\Store;
use App\Models\User;
use App\Models\UserERP;
use App\Traits\HasResponse;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;

class CompanyService
{
    use HasResponse;

    public function list($withPagination)
    {
        $company = Company::companyFilters() # Filtrado por el modelo
            ->orderBy('id', 'desc');

        $company = !empty($withPagination)
            ? $company->paginate($withPagination['perPage'], page: $withPagination['page'])
            : $company->get();

        return $this->successResponse('Lectura exitosa.', CompanyResource::collection($company->load('membership')));
    }

    public function register($params)
    {
        DB::beginTransaction();
        try {
            # Verificar duplicidad de RUT en compañías y usuarios
            $rutExistingCompany = Company::where('rut', $params['rut'])->first();
            $rutExistingUser = User::where('rut', $params['rut'])->first();
            if ($rutExistingCompany || $rutExistingUser) return $this->errorResponse('El rut ya se encuentra registrado.', 400);

            $company = Company::create([
                'rut'           => $params['rut'],
                'business_name' => $params['business_name'],
                'address'       => $params['address'],
                'email'         => $params['email'],
                'phone'         => $params['phone'] ?? null,
                'giro'          => $params['giro'] ?? null,
                'iddistrict'    => $params['iddistrict'] ?? null,
                'idmembership'  => '3'
            ]);
            $company->fresh();

            # Se crea la configuración por defecto
            $companyConfiguration = CompanyConfiguration::create([
                'idcompany' => $company->id,
                'inventory_configuration' => 2,
            ]);

            // $createUserERP = $this->createUserERP($params['rut']);

            # Se crea la bodega general
            Store::create([
                'code'          => $params['rut'],
                'name'          => 'general',
                'description'   => 'Bodega general',
                'idcompany'     => $company->id
            ]);

            DB::commit();
            return $this->successResponse('Compañía creada satisfactoriamente.', $company);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->externalError('durante la creación de una compañía.', $th->getMessage());
        }
    }

    public function update($id, $params)
    {
        DB::beginTransaction();
        try {
            # Verificar validez de la compañía
            $validate = $this->verifyCompany($id);
            if (!$validate->original['status']) return $validate;

            $company = Company::find($id);
            $company->update($params);

            DB::commit();
            return $this->successResponse('Compañía actualizada satisfactoriamente.', $company);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->externalError('durante la actualización de una compañía.', $th->getMessage());
        }
    }

    public function delete($id)
    {
        DB::beginTransaction();
        try {
            # Verificar validez de la compañía
            $validate = $this->verifyCompany($id);
            if (!$validate->original['status']) return $validate;

            $company = Company::find($id);
            $company->update(['status' => 2]);

            DB::commit();
            return $this->successResponse('Compañía eliminada satisfactoriamente.', $company);
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->externalError('durante la eliminación de una compañía.', $th->getMessage());
        }
    }

    private function verifyCompany($idCompany)
    {
        $company = Company::activeForID($idCompany)->first();
        if (!$company) return $this->errorResponse('La compañía seleccionada no esta disponible', 400);

        return $this->successResponse('OK');
    }

    private function createUserERP($rut)
    {
        DB::beginTransaction();
        try {
            $userERP = UserERP::create([
                'rut'                   => $rut,
                'user'                  => 'usuario',
                'password'              => bcrypt('demoerp'),
                'encrypted_password'    => Crypt::encryptString('demoerp')
            ]);
            $userERP->fresh();

            DB::commit();
            return $this->successResponse('Usuario ERP creado satisfactoriamente.');
        } catch (\Throwable $th) {
            DB::rollBack();
            return $this->externalError('durante la creación de un usuario ERP.', $th->getMessage());
        }
    }

    // private function loginERP($rut)
    // {
    //     try {
    //         $body = json_encode([
    //             'username' => 'erpsoftnet',
    //             'password' => 'softnet.,2023',
    //             'rut'      => $rut
    //         ]);
    //         $loguin = Http::withBody($body,'application/json')->post('http://api.softnet.cl/login');
    //         $apitoken = isset(json_decode($loguin)->token) ? json_decode($loguin)->token : null;

    //         return $this->successResponse('ok', $apitoken);
    //     } catch (\Throwable $th) {
    //         return null;
    //     }
    // }
}
