<?php

namespace Modules\Main\Http\Controllers\Company;

use Illuminate\Validation\Rule;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Modules\Main\Models\Company\Company;
use Modules\Main\Models\Company\CompanyType;
use App\Models\Bitrix\SendCompany;
class CreateCompanyController extends Controller
{
    /**
     * Handle the incoming request.
     */
    public function __invoke(Request $request)
    {
        $company = false;
        $request->enum('type', CompanyType::class);
        $validated = $request->validate([
            'name'          => 'required|max:255',
            'email'         => 'required|email|unique:companies',
            'phone'         => 'required',
            'inn'           => 'required_if:type,' . CompanyType::Agency->value . '|unique:companies',
            'type'          => Rule::enum(CompanyType::class),
            'city_id'       => 'required'
        ],
        [
            'inn.required_if' => 'Необходимо указать ИНН агентства'
        ]);

        $request->request->add([
            'secret' => bin2hex(random_bytes(16)),
            'status' => 'new'
        ]);

        $data = $request->only('name', 'email', 'inn', 'legal_address', 'secret', 'status', 'type', 'phone', 'city_id');

        try
        {
            $company = Company::create($data);
        }
        catch (\Exception $e)
        {
            if ($e->getMessage() == 'Error of bitrix identifier getter')
            {
                return back()->withErrors(['msg' => 'Не удалось отправить данные на проверку. Попробуйте позже'])->withInput();
            }
            return back()->withErrors(['msg' => 'Не удалось создать агентство. Попробуйте позже'])->withInput();

        }
        return view('main::company.created');
    }
}
