<?php

namespace Modules\Bitrix\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use Modules\Main\Models\Deal\Deal;
use Modules\Main\Models\Deal\DealStatus;
use App\Notifications\UniqueContact;
use App\Notifications\NotUniqueContact;
use App\Notifications\Deal\DealUnique;
use App\Notifications\Deal\DealNotUnique;

use Modules\Bitrix\Models\BitrixId;

use Illuminate\Support\Facades\Log;

class BitrixApiController extends Controller
{
    public const ACTION_CONFIRM_DEAL = 'confirm_deal';
    public const ACTION_UPDATE_CONTRACT = 'update_contract';
    public const ACTION_CONFIRM_COMPANY = 'confirm_company';
    public function index(Request $request)
    {
        if (!$bxId = BitrixId::where('token', $request->token)->first()) {
            return false;
        };
        $object = $bxId->bitrixable;
        //print_r($object);die();
        switch ($request->action) {
            case $this::ACTION_CONFIRM_DEAL:
                $this->confirmDeal($object, $request);
                break;
            case $this::ACTION_UPDATE_CONTRACT:
                $this->updateContract($object, $request);
                break;
            case $this::ACTION_CONFIRM_COMPANY:
                $this->confirmCompany($request, $object);
                break;
        }
        return false;
    }

    public function confirmCompany(Request $request, $company)
    {
        $confirmer = new ConfirmCompanyController;
        $confirmer($request, $company);
    }
    public function confirmDeal(Deal $deal, Request $request)
    {
        $agent = $deal->agent;
        $request->is_unique = json_decode($request->is_unique, true);//т.к. приходит в строке
        if ($request->is_unique == true) {
            $deal->status = DealStatus::UNIQUE;
            if ($request->has('unique_until')) {
                $deal->unique_until = $request->unique_until;
            }
            $agent->user->notify(new UniqueContact($deal));
        } else {
            $deal->status = DealStatus::NOT_UNIQUE;
            $agent->user->notify(new NotUniqueContact($deal));
        }

        if (!$agent->bitrixId()) {
            $agent->setBitrixId($request->agent_id);
        }

        Log::build([
            'driver' => 'single',
            'path' => storage_path('logs/bitrix.log'),
        ])->error(
                json_encode(
                    [
                        'is_unique' => $request->is_unique,
                        'deal' => $deal->id,
                        'status' => $deal->status
                    ]
                )
            );
        $deal->save();
        return $deal->id;
    }

    public function updateContract(Deal $deal, Request $request)
    {
        //print_r($request->all());die();
        $contract = new ContractUpdateController;
        $contract($deal, $request);
    }
}
