<?php
/**
 * Created by PhpStorm.
 * User: cbarranco
 * Date: 7/8/16
 * Time: 3:01 PM
 */

namespace Hilco\Controllers;

use Illuminate\Http\Request;
use Response;

trait HasSelect2Search {

    /**
     * Default method, override this for it to work.
     */
    public function getS2SearchModel() {
        return false;
    }

    // As an explanation of the filters, both are just collections
    // of 'ands', the orFilters are just the set that you want or'd
    // against the andFilters, e.g.:
    // andFilters: [
    //     {
    //         column: 'cust_name',
    //         .....
    //     }
    // ],
    // orFilters: [
    //     {
    //         column: 'cust_no',
    //         .....
    //     }
    // ]
    public function s2search(Request $request) {
        $page = $request->get('page', 0);
        $andFilters = $request->get('andFilters', []);
        $orFilters = $request->get('orFilters', []);
        $rawFilters = $request->get('rawFilters', []);
        $q = $this->getS2SearchModel();
        if (!$q) return Response::json([]);

        $q->where(function($query) use ($andFilters){
            $this->parseFilters($query, $andFilters);
        });

        $q->orWhere(function($query) use ($orFilters){
            $this->parseFilters($query, $orFilters);
        });


        foreach($rawFilters as $rawFilter) {
            $sql = \Illuminate\Support\Arr::get($rawFilter, 'sql');
            $value = \Illuminate\Support\Arr::get($rawFilter, 'value');
            $q->orWhereRaw($sql, $value);
        }

//        dd($q->toSql(), $q->getBindings());
        $totalCount = $q->count();
        $pageSize = $this->getS2PageSize();
        if ($pageSize == -1) {
            $results = $q->get();
            $hasMore = false;
        } else {
            $results = $q->offset(($page - 1)* $pageSize)->take($pageSize)->get();
            $hasMore = ($totalCount > ($page * $pageSize));
        }

        $results = $this->formatS2Results($results);

        return Response::json(['items' => $results, 'total_count' => $totalCount, 'page' => $page, 'pagination' => ['more' => $hasMore]]);

    }
    public function getS2PageSize() {
        return 30;
    }
    public function formatS2Results($results) {
        return $results;
    }

    public function s2preselect(Request  $request, $id) {
        $q = $this->getS2SearchModel();
        $result =  $q->where('id', $id)->get();
        return Response::json($this->formatS2Results($result)[0]);
    }

    private function parseFilters($query, $filters) {
        foreach ($filters as $filter) {
            $column = \Illuminate\Support\Arr::get($filter, 'column');
            $operator = \Illuminate\Support\Arr::get($filter, 'operator', '=');
            $value = \Illuminate\Support\Arr::get($filter, 'value');
            if (strtolower($operator) == 'like') $value = "%$value%";
            $query->where($column, $operator, $value);
        }
    }
}