<?php

namespace App\Core\Repository\TempProperty;

use App\Core\Repository\EleqouentAbstractRepository;
use App\Models\TempProperty;

class TempPropertyRepository extends EleqouentAbstractRepository
{
    private $tempProperty;

    public function __construct(TempProperty $tempProperty)
    {
        parent::__construct();
        $this->tempProperty = $tempProperty;
        $this->defaultModel = $this->tempProperty;
    }

    public function searchTempProperty($param, $column = ['*'])
    {
        $get = $this->tempProperty->on('mysql')
            ->orWhere(
                function ($query) use ($param) {
                    if (isset($param['orWhere']))
                    {
                        foreach ($param['orWhere'] as $key => $value)
                        {
                            $query->orWhere($value['field'], $value['condition'], '%'.$value['value'].'%' );
                        }
                    }
                }
            );

        if (isset($param['orWhere']))
        {
            $rawBindings = [];
            $increment = 1;
            $likeTokens = [':fieldName',':fieldName%','%:fieldName','%:fieldName%'];

            $rawSqlPiece = 'case ';
            foreach ($likeTokens as $perLikeToken)
            {
                foreach ($param['orWhere'] as $key => $value)
                {
                    $rawSqlPiece.= 'when '.$value['field'].' LIKE ? then '.$increment.' ';
                    $increment++;
                }
            }
            foreach ($likeTokens as $perLikeToken)
            {
                foreach ($param['orWhere'] as $key => $value)
                {
                    $rawBindings[] = str_replace(":fieldName",$value['value'],$perLikeToken);
                }
            }

            $rawSqlPiece .= 'end';
        }

        if (isset($rawSqlPiece))
        {
            $get->orderByRaw($rawSqlPiece . " ASC",$rawBindings);
        }
        $get->take(10);
        $get = isset($param["firstRow"]) ? $get->first($column) : $get->get($column);

        return ($get) ? $get->toArray() : [];
    }

}
