<?php

namespace App\Traits;

use Exception;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use App\Models\Application\Client;
use App\Models\Application\RequestClient;

trait RequestsTrait
{
    use UserLoggedTrait;

    protected function convertClient(RequestClient $client)
    {
        DB::beginTransaction();

        if (!Client::where([
            ['fk_site', $client->fk_site],
            ['fk_office', $client->fk_office],
            ['is_active', true],
        ])->where(function ($query) use ($client) {
            $query->where([
                ['firstname', $client->firstname],
                ['lastname', $client->lastname],
                ['secondlastname', $client->secondlastname],
            ])->orWhere('curp', $client->curp);
        })->exists()) {
            Client::create($client);

            $client->udpate([
                'available' => false,
                'fk_userupdater' => $this->user()->id,
            ]);

            DB::commit();
            return true;
        }

        DB::rollBack();
        return false;
    }
}
