<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    protected function search(Request $request, $model)
    {
        $query = $model::query();
        $searchFields = $model::searchFields;
        foreach ($searchFields as &$field) {
            if ($field['type'] == 'date') {
                $field['value'] = ['', ''];
                $sDate = $request->get($field['name'] . '_s', false);
                $eDate = $request->get($field['name'] . '_e', false);
                if (!empty($sDate)) {
                    $query->where($field['name'], '>', $sDate);
                    $field['value'][0] = $sDate;
                }
                if (!empty($eDate)) {
                    $query->where($field['name'], '<', $eDate);
                    $field['value'][1] = $eDate;
                }
            } elseif ($field['type'] == 'like') {
                $field['value'] = '';
                $likeValue = $request->get($field['name'], false);
                if (!empty($likeValue)) {
                    $query->where($field['name'], 'LIKE', '%' . $likeValue . '%');
                    $field['value'] = $likeValue;
                }
            } else {
                $field['value'] = '';
                $value = $request->get($field['name'], false);
                if (!empty($value)) {
                    $query->where($field['name'], $value);
                    $field['value'] = $value;
                }
            }
        }
        return [
            'isSearch' => !empty($model::searchFields),
            'isEdit' => !empty($model::editFields),
            'isCreate' => !empty($model::createFields),
            'searchFields' => $searchFields,
            'titles' => $model::columns,
            'nav' => $model::nav,
            'list' => $query->paginate()
        ];
    }

    public function getModel($model)
    {
        return "App\\".ucfirst($model);
    }
}
