<?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', []);
        $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);
        });

        $totalCount = $q->count();
        $results = $q->offset($page * 30)->take(30)->get();
        return Response::json(['items' => $results, 'total_count' => $totalCount, 'page' => $page]);
    }

    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);
        }
    }
}