<?php

namespace App\Core\Service\ThirdPartyServices;

use App\Exceptions\ApiErrorException;

use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Exception;


class MondayService
{

    private $authorization;
    private $contactBoardId;

    public function __construct(
        Client $restClient
    )
    {
        $this->restClient = $restClient;
        $this->url = 'https://api.monday.com/v2';

        $this->authorization = 'eyJhbGciOiJIUzI1NiJ9.eyJ0aWQiOjEzMTcwODMyNiwidWlkIjoyMjE2NDU2MiwiaWFkIjoiMjAyMS0xMS0wNFQxNzo1OTo0Ni4wMDBaIiwicGVyIjoibWU6d3JpdGUiLCJhY3RpZCI6OTAxNjcyOSwicmduIjoidXNlMSJ9.VT5EjPvtx2CzoF-ZktcrqLSyxp3A6gmgnNdfDwdIExE';
        $this->contactBoardId = 1306161833;
    }

    public function requestPost($query)
    {
        $response = ['status' => false, 'message' => ''];

        try {
            $this->restClient = new Client(['http_errors' => false]);
            $res = $this->restClient->post($this->url,
                [
                    'headers' => [
                        'Content-Type' => 'application/json',
                        'Authorization' => $this->authorization
                    ],
                    'body' => json_encode(['query' => $query]),
                ]
            );

            $getResponseBody = $res->getBody();
            $getResponse = $getResponseBody->getContents();
            $getResponse = json_decode($getResponse, 1);

            if(isset($getResponse['errors'])) {
                throw new ApiErrorException(pickItemFromArray('message',$getResponse['errors']));
            }

            $response = ["status" => true, 'message' => '', "data" => $getResponse['data']];

        } catch (ApiErrorException $e) {
            $response['message'] = implode(', ', $e->getMessageArr());
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
        }

        return $response;

    }

    public function createBoardItems($params = [])
    {
        $response = ['status' => false, 'message' => ''];

        try {

            $columnValues = [
                'text' => $params['property_name'],
                'email' => [
                    'email' => $params['email'],
                    'text' => $params['email'],
                ],
                'phone' => [
                    'phone' => str_replace(' ', '', $params['phone']),
                ],
                'long_text4' => 'SignupForm',
                'metin' => mb_strtoupper($params['language']),
                'tarih' => [
                    'date' => Carbon::now()->toDateString(),
                    'time' => Carbon::now()->format('H:i:s')
                ],
            ];

            $columnValues = json_encode(json_encode($columnValues));

            $nameSurname = $params['name'] . ' ' . $params['surname'];

            $query = <<<BUR
mutation { create_item (board_id: {$this->contactBoardId}, item_name: "{$nameSurname}", column_values : {$columnValues} ) { id } }
BUR;

            $responseData = $this->requestPost($query);

            if(!$responseData['status']) {
                throw new ApiErrorException($responseData['message']);
            }

            $response = [
                'status' => true,
                'data' => $responseData['data']
            ];

        } catch (ApiErrorException $e) {
            $response['message'] = implode(', ', $e->getMessageArr());
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
        }

        return $response;
    }

}
