<?php

namespace App\Geo\City;

use ORM\DBInstance;
use \App\Core\Template\Output as Output;
use App\Core\Datatables\Datatables as Datatables;

use \App\Geo\City\Classes\City as City;

class CityController extends \DefaultController
{

    protected $_class   = City::class;
    protected $_baseUrl = 'city';

    /**
     * Index
     *   Show the main City list
     */
    function index()
    {
        Output::render('index');
    }

    /**
     * Create
     *
     * Render the main City formulary
     */
    function create()
    {
        Output::render('form', ['id' => 0]);
    }

    /**
     * Store
     *
     * Store the param on the database
     * @param City $city
     */
    function store(City $city)
    {
    }

    /**
     * Search
     *
     * Store the param on the database
     * @param City $city
     */
    function search()
    {
    }

    /**
     * Show
     *
     * Render one register
     *
     * @param City $city
     */
    function show($city)
    {
        if(is_ajax_request()){
            \RR\Response::json( City::findOne(['code' => ['=', $city]]) )->send();
            return;
        }else{
            $city = City::findOne($city);
        }
    }

    /**
     * Edit
     *
     * Render the formular for a database City
     *
     * @param City $city
     */
    function edit(City $city)
    {
        Output::render('form', $city);
    }

    /**
     * Update
     * Store the changes of the param on the database
     *
     * @param City $city
     */
    function update(City $city)
    {
    }

    /**
     * Destroy
     * If the object has soft delete.
     *
     * @param City $city
     */
    function destroy(City $city)
    {
    }

    /**
     * Purge
     * Remove object even with soft delete.
     *
     * @param City $city
     */
    function purge(City $city)
    {
    }

    public static function searchOrCreate($data)
    {

        if ($city = City::findOne(['code' => ['=', $data->ibge]])) {
            return $city;
        }

        $city = new City();
        $city->name = $data->localidade;
        $city->code = $data->ibge;
        $city->state_id = $data->state;
        $city->country_id = $data->country;
        $city->save();

        return $city;
    }

    function searchTable()
    {
        $records = [];
        $total = 0;

        try {
            if ($_POST['search']['value'] != '') {
                $search = [];
                foreach ($this->_class::_searchable as $searchable) {
                    $search[$searchable] = ['OR like', $_POST['search']['value']];
                }
                $records = $this->_class::findMany($search, $this->_class::_listable)->get(true);
            } else {
                $records = $this->_class::findAll($this->_class::_listable, ['limit' => $_POST['length'], 'offset' => $_POST['start']])->get();
            }
            $total = DBInstance::queryOne("SELECT count(*) as count FROM {" . $this->_class::_tableName .  '}')->count;
        } catch (\Exception $e) {
            if (APP_STATUS != 'production') {
                for ($i = $_POST['start']; $i <= $_POST['length'] + $_POST['start']; $i++) {
                    $line = new \stdClass();
                    $line->id = $i;
                    $line->name = md5($i);
                    $records[] = $line;
                }
                $total = 10000;
            }
        }

        if (!is_array($records)) {
            $records = [$records];
        }

        foreach ($records as $record) {
            if ($_GET['selective'] == 'true') {
                $record->id = Datatables::getActionMenu($record->id, $this->_baseUrl);
            } else {
                $record->id = Datatables::getSelectMenu($record->code);
            }
        }

        \RR\Response::json([
            'draw' => $_POST['draw'],
            'recordsTotal' => $total,
            'recordsFiltered' => $total,
            'data' => $records
        ])->send();
    }
}
