<?php

namespace Modules\Admin\Http\Controllers;

use Modules\Docs\Models\Document;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Modules\Main\Models\Agent\Agent;
use App\Models\Deal\Contract;
use App\Models\Deal\Deal;
use App\Models\Deal\DealStatus;
use Modules\Bitrix\Models\BitrixId;
use App\Models\User;
use App\Models\Bitrix\SendClient;
//use App\Models\User\UserRole;
//use App\Models\User\Role;

class AdminBitrixController extends Controller
{
    public function index()
    {
        return view('admin::bitrix.index', [

        ]);
    }
    public function agents()
    {
        return view('admin::bitrix.agents', [
            'agents' => Agent::all()
        ]);
    }
    public function setAgentId(Request $request, Agent $agent)
    {
        $agent->setBitrixId($request->id);
        return back()->withSuccess('ID агента обновлен');
    }
    public function syncDeals(Agent $agent)
    {
        $importedCount = 0;
        $url = 'https://b24alfa.pro/channels/lk/getDealsOfContact?id=' . $agent->bitrixId();
        $data = file_get_contents($url);
        $deals = json_decode($data, true);
        foreach ($deals as $deal)
        {
            $inDeal = $deal['deal'];//входящие данные по сделке

            if (count($deal['contacts']) == 0)
            {
                continue;
            }
            $client = false;
            //Загрузка контактов
            if ($deal['contacts'][0]['phone'])
            {
                $client = User::firstOrCreate(
                    ['phone' => $deal['contacts'][0]['phone']],
                    [
                        'name'  => $deal['contacts'][0]['name'],
                        'phone' => $deal['contacts'][0]['phone']
                    ]
                );
            }
            ;
            $dealItem = false; //собственный, не из битрикса
            $bitrixId = BitrixId::where('bx_id', $inDeal['deal_id'])
                ->where('bitrixable_type', Deal::class);
            //Загрузка сделок
            if ($bitrixId->count() == 0)
            {
                $dealItem = Deal::create([
                    'client_id'  => $client->id,
                    'complex_id' => $inDeal['complex_id'],
                    'agent_id'   => $agent->id,
                    'status'     => DealStatus::UNIQUE,
                ]);
                $dealItem->setBitrixId($deal['deal']['deal_id']);
            }
            else
            {
                $bitrixId = $bitrixId->first();
                $dealItem = Deal::find($bitrixId->bitrixable_id);
            }
            if ($dealItem)
            {
                $importedCount++;
                $contract = Contract::updateOrCreate(
                    ['deal_id' => $dealItem->id],
                    [
                        'price'    => $inDeal['price'],
                        'square'   => $inDeal['square'],
                        'floor'    => $inDeal['floor'],
                        'room'     => $inDeal['room'],
                        'plan7_id' => $inDeal['plan7_id']
                    ]
                );
                $this->sendDealToBitrix($dealItem);
            }
        }
        return back()->with('success', 'Импортировано ' . $importedCount . ' сделок');
    }

    function sendDealToBitrix(Deal $deal)
    {
        $deal->refresh();
        $client = $deal->user;
        $agent = $deal->agent;
        $clientName = $client->getPartialsName();
        $agentName = $agent->user->getPartialsName();
        $data = [
            'CLIENT_FIRST_NAME'  => $clientName['firstName'],
            'CLIENT_SECOND_NAME' => $clientName['secondName'],
            'CLIENT_PHONE'       => $client->phone,
            'BROKER_FIRST_NAME'  => $agentName['firstName'],
            'BROKER_SECOND_NAME' => $agentName['secondName'],
            'BROKER_PHONE'       => $agent->user->phone,
            'BROKER_INN'         => $agent->company->inn,
            'OBJECT_NAME'        => $deal->complex->name,
            'CALLBACK_URL'       => route('api.client', ['hash' => $deal->confirm_token]),
        ];
        $sender = new SendClient($deal->id, $data);
        $sender->setBitrixId($deal->bitrixId());
        $sender->setAgentId($deal->agent->bitrixId());
        $response = $sender->send();
        if ($response)
        {
            return $response;
        }
        else
        {
            return false;
        }
    }
}