<?php


namespace App\Core\Service;

use App\Core\Repository\TempProperty\TempPropertyRepository;
use App\Core\Validator\TempProperty\TempPropertySearchValidator;
use Illuminate\Http\Request;
use App;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Config;
use Exception;
use App\Exceptions\ApiErrorException;


class TempPropertyService
{
    private $request ;
    private $tempPropertyRepository;
    private $tempPropertySearchValidator;

    public function __construct
    (
        Request $request,
        TempPropertyRepository $tempPropertyRepository,
        TempPropertySearchValidator $tempPropertySearchValidator
    )
    {
        $this->request = $request;
        $this->tempPropertyRepository = $tempPropertyRepository;
         $this->tempPropertySearchValidator = $tempPropertySearchValidator;
    }

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

            $criteria = fillOnUndefined($param , 'criteria');
            $searchData = [] ;
            foreach ($criteria as $item){
                $searchData[$item['field']] = $item['value'];
            }
            $validationResult = $this->tempPropertySearchValidator->validate($searchData);
            if ($validationResult->errors()->first()) {
                $errors = $validationResult->errors()->all();
                throw new ApiErrorException($errors);
            }
            $orWhere[] = ['field' => 'name', 'condition' => 'LIKE', 'value' => $searchData['name']];
            $requestData['orWhere'] = $orWhere;
            $data = $this->tempPropertyRepository->searchTempProperty($requestData, $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 select($param = [], $column = ['*'])
    {
        $response = ['status' => -1, 'message' => '', 'data' => null];
        try {
            $data = $this->tempPropertyRepository->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);
    }

}
