<?php

namespace App\Core\Service;

use App\Core\Repository\OfferContactMapping\OfferContactMappingRepository;
use App\Core\Validator\OfferContactMapping\OfferContactMappingCreateValidator;
use App\Core\Validator\OfferContactMapping\OfferContactMappingAddValidator;


use App;
use Illuminate\Support\Facades\Log;
use Exception;
use App\Exceptions\ApiErrorException;

class OfferContactMappingService
{

    private $offerContactMappingRepository;
    private $offerContactMappingCreateValidator;
    private $offerContactMappingAddValidator;


    public function __construct(

        OfferContactMappingRepository $offerContactMappingRepository,
        OfferContactMappingCreateValidator $offerContactMappingCreateValidator,
        OfferContactMappingAddValidator $offerContactMappingAddValidator
    )
    {
        $this->offerContactMappingRepository = $offerContactMappingRepository;
        $this->offerContactMappingCreateValidator = $offerContactMappingCreateValidator;
        $this->offerContactMappingAddValidator = $offerContactMappingAddValidator;
    }

    public function create($param = [])
    {
        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {

            $validationResult = $this->offerContactMappingCreateValidator->validate($param);

            if ($validationResult->errors()->first()) {
                $errors = $validationResult->errors()->all();
                throw new ApiErrorException($errors);
            }

            $insertData =
                [
                    "offer_id" => fillOnUndefined($param, "offer_id"),
                    "property_executive_id" => fillOnUndefined($param, "property_executive_id"),
                    "status" => fillOnUndefined($param, "status", 0),
                    "created_by" => fillOnUndefined($param, "created_by"),
                    "updated_by" => fillOnUndefined($param, "updated_by"),
                    "created_at" => time(),
                    "updated_at" => time(),
                ];

            $userCreateResult = $this->offerContactMappingRepository->create($insertData);
            if ($userCreateResult['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }
            $userData = $userCreateResult["data"];
            $response = [
                'status' => true,
                'data' => $userData,
            ];

        } 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 output($response);
    }

    public function select($param = [], $column = ['*'])
    {

        $response = ['status' => -1, 'message' => '', 'data' => null];

        try {

            $data = $this->offerContactMappingRepository->findByCriteria($param, $column);

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

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

        return output($response);
    }

    public function update($id, $param = [])
    {

        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {

            $updateResult = $this->offerContactMappingRepository->update($id, $param);
            if ($updateResult['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }
            $updateData = $updateResult["data"];
            $response = [
                'status' => true,
                'data' => $updateData,
            ];

        } 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 output($response);
    }

    public function updateOrCreate($criteria = [], $saveData = [])
    {
        $response = ['status' => -1, 'message' => '', 'data' => null];

        try {

            $data = $this->offerContactMappingRepository->updateOrCreate($criteria, $saveData);
            if ($data['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }
            $response = [
                'status' => true,
                'data' => $data,
            ];

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

        return output($response);


    }

    public function insertContactMapping($param = [])
    {

        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {

            $validationResult = $this->offerContactMappingAddValidator->validate($param);
            if ($validationResult->errors()->first()) {
                $errors = $validationResult->errors()->all();
                throw new ApiErrorException($errors);
            }
            $insertDataArray = [] ;
            foreach ($param['contact_mapping'] as $item) {
                $insertDataArray[] =
                    [
                        "offer_id" => fillOnUndefined($param, "offer_id"),
                        "property_executive_id" => $item,
                        "status" => fillOnUndefined($param, "status", 1),
                        "created_by" => fillOnUndefined($param, "user_id"),
                        "updated_by" => fillOnUndefined($param, "user_id"),
                        "created_at" => time(),
                        "updated_at" => time(),
                    ];
            }

            $offerContactInsertResult = $this->offerContactMappingRepository->createAll($insertDataArray);
            if ($offerContactInsertResult['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }
            $userData = $offerContactInsertResult["data"];
            $response = [
                'status' => true,
                'data' => $userData,
            ];

        } 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 output($response);

    }

    public function updateContactMapping($param = [], $offerContactMapping)
    {

        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {

            $validationResult = $this->offerContactMappingAddValidator->validate($param);
            if ($validationResult->errors()->first()) {
                $errors = $validationResult->errors()->all();
                throw new ApiErrorException($errors);
            }

            $insertThisIds = array_diff($param['contact_mapping'], $offerContactMapping);
            $deleteThisIds = array_diff($offerContactMapping, $param['contact_mapping']);

            $insertDataArray = [] ;
            foreach ($insertThisIds as $item) {
                $insertDataArray[] =
                    [
                        "offer_id" => fillOnUndefined($param, "offer_id"),
                        "property_executive_id" => $item,
                        "status" => fillOnUndefined($param, "status", 1),
                        "created_by" => fillOnUndefined($param, "user_id"),
                        "updated_by" => fillOnUndefined($param, "user_id"),
                        "created_at" => time(),
                        "updated_at" => time(),
                    ];
            }

            $offerContactInsertResult = $this->offerContactMappingRepository->createAll($insertDataArray);
            if ($offerContactInsertResult['status'] != 'success') {
                throw new Exception('api-unknown_error');
            }

            $requestData = [
                'criteria' => [
                    ['field' => 'offer_id', 'condition' => '=', 'value' => fillOnUndefined($param, "offer_id")],
                ],
                "whereIn" =>
                    [
                        ["field" => "property_executive_id", "value" => $deleteThisIds]
                    ]
            ];
            $eraseMappingData = $this->offerContactMappingRepository->findByCriteria($requestData, ['id']);
            $eraseMappingData = $eraseMappingData ? $eraseMappingData : [] ;
            $deleteThisIds = collect($eraseMappingData)->keyBy('id')->keys()->all();

            if($deleteThisIds){
                $deleteThisArray = $this->offerContactMappingRepository->destroy($deleteThisIds);
                if ($deleteThisArray['status'] != 'success') {
                    throw new Exception('api-unknown_error');
                }
            }

            $userData = $offerContactInsertResult["data"];
            $response = [
                'status' => true,
                'data' => $userData,
            ];

        } 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 output($response);

    }


}
