<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use DB;

class Country extends Model
{
    protected $fillable = ['name', 'iso_code_2','iso_code_3','nationality','dialing_code','status'];

    public function getAllcountries($search = [], $sort = array(), $limit = null, $offset = null) {
        $countryObj = self::select('*');

        if ($search['freetext'] != '') {
            $countryObj->where(function ($query) use ($search) {
                $query->orWhere('name', 'like', "%" . $search["freetext"] . "%");
                $query->orWhere('iso_code_2', 'like', "%" . $search["freetext"] . "%");
                $query->orWhere('iso_code_3', 'like', "%" . $search["freetext"] . "%");
                $query->orWhere('nationality', 'like', "%" . $search["freetext"] . "%");
                $query->orWhere('dialing_code', 'like', "%" . $search["freetext"] . "%");
                $query->orWhere('status', 'like', "%" . $search["freetext"] . "%");
                $query->orWhere(DB::raw("DATE_FORMAT(created_at,'%d-%m-%Y %H:%i:%s')"), "like", "%" . $search['freetext'] . "%");
            });
        }
        $fields = array('', 'name', 'iso_code_2', 'iso_code_3','nationality', 'dialing_code','status','created_at', '');
        if (!empty($sort)) {
            foreach ($sort as $index => $type) {
                if (!empty($fields[$index])) {
                    $countryObj->orderBy($fields[$index], $type);
                }
            }
        }

        if (empty($limit)) {
            return $countryObj->count();
        } else {
            $countryObj->offset($offset);
            $countryObj->limit($limit);
            return $countryObj->get();
        }
    }
}