<?php

namespace Datacake\Core\Admin\Crud;

use Datacake\Core\Admin\Crud\BaseCrud;

use Datacake\Core\Models\IspCity;
use Datacake\Core\Wda\CityApi;

class CityCrud extends BaseCrud {
	public $parent_page = 'isp_city';
    public $columns = [
		'id'=>'id',
		'name'=>'Nome',
		'short_name'=>'Nome Curto',
		'code'=>'Código',
		'lat'=>'Latitude',
		'long'=>'Longitude',
		'remote_id'=>'WDA ID',
		'redirect_url'=>'Link Externo'
	];
	public $sortableColumns = [
		'id'=>array( 'id', true ),
		'name'=>array('name', true),
		'short_name'=>array('short_name', true),
		'code'=>array('code', true),
		'lat'=>array('lat', true),
		'long'=>array('long', true),
		'remote_id'=>array('remote_id', true),
		'redirect_url'=>array('redirect_url', true),
		
    ];
	
	public $info = [
		'singular' => 'Cidade', //singular name of the listed records
		'plural' => 'Cidades', //plural name of the listed records
		'ajax' => true,
	];
	public $cityApi;
    public function __construct($args = array()) {
		$this->entity = new IspCity();
		
		parent::__construct($args);

		$this->cityApi = new CityApi();
		
	}
	
	public function sync(){
		echo "Start Sync";
		$apiCitiesQuery = $this->cityApi
			->setJsonApiFields([
				'created','updated','name','short_name',
				'id','code','lat','long',
				'redirect_url','is_neighborhood','neighborhood_name'
			])
			->setJsonApiPage()
			->list();
				
        
        if($apiCitiesQuery->isSuccessful()){
            if($apiCitiesQuery->hasDocument()){
				
				foreach ($apiCitiesQuery->document()->primaryResources() as $key => $doc) {
					
					$entity = IspCity::where('remote_id',$doc->id())->first();
					
					$data = [
						'name'=>$doc->attribute('name'),
						'short_name'=>$doc->attribute('short_name'),
						'code'=>$doc->attribute('code')?$doc->attribute('code'):$doc->attribute('name'),
						'lat'=>$doc->attribute('lat'),
						'long'=>$doc->attribute('long'),
						'remote_id'=>$doc->id(),
						'redirect_url'=>$doc->attribute('redirect_url'),
						'is_neighborhood'=>$doc->attribute('is_neighborhood'),
						'neighborhood_name'=>$doc->attribute('neighborhood_name'),
					];
					if($entity){
						$entity->update($data);
					}else{
						$entity = new IspCity();
						$entity->create($data);
					}
					
					
				}
				$this->redir_with_message('Sync realizado com sucesso');
				return;
				
            }
        }
		$this->redir_with_message('','Erro ao realizar sync');

	}
	
	public function menu_items($role, $plugin_name){
		add_submenu_page("isp", 
			__('Cidades', $plugin_name), 
			__('Cidades', $plugin_name), 
			$role, $this->parent_page, [$this, 'list']
		);
		add_submenu_page(null, 
			__('Nova Cidade', $plugin_name), 
			__('Nova Cidade', $plugin_name), 
			$role, $this->parent_page.'_edit', [$this, 'edit']
		);
		add_action($this->parent_page.'_delete', [$this, 'delete']);
		add_action($this->parent_page.'_sync', [$this, 'sync']);
	}

	public function edit_html($entity =null) {
		?>
		<h2><?php echo $entity ? "Editando Cidade" : "Nova Cidade" ?></h2>
		<form method="post">
			<input type="hidden" name="id" value="<?php echo $entity ? $entity->id : ""?>">
			<table class="form-table" role="presentation">
				<tbody>
					<tr>
						<th scope="row">
							<label>Nome</label>
						</th>
						<td>
							<input type="text" name="name" id="nome" value="<?php echo $entity ? $entity->name : ""?>"  required>
						</td>
					</tr>
					<tr>
						<th scope="row">
							<label>Nome Curto</label>
						</th>
						<td>
							<input type="text" name="short_name" id="short_name" value="<?php echo $entity ? $entity->short_name : ""?>"  required>
						</td>
					</tr>
					<tr>
						<th scope="row">
							<label>Code</label>
						</th>
						<td>
							<input type="text" name="code" id="code" value="<?php echo $entity ? $entity->code : ""?>"  required>
						</td>
					</tr>
					<tr>
						<th scope="row">
							<label>Latitude</label>
						</th>
						<td>
							<input type="text" name="lat" id="lat" value="<?php echo $entity ? $entity->lat : ""?>">
						</td>
					</tr>
					<tr>
						<th scope="row">
							<label>Longitude</label>
						</th>
						<td>
							<input type="text" name="long" id="long" value="<?php echo $entity ? $entity->long : ""?>">
						</td>
					</tr>
					<tr>
						<th scope="row">
							<label>Link de Redirecionamento</label>
						</th>
						<td>
							<input type="text" name="redirect_url" id="redirect_url" value="<?php echo $entity ? $entity->redirect_url : ""?>">
						</td>
					</tr>
					<tr>
						<th scope="row">
							<label>É um bairro?</label>
						</th>
						<td>
							<?php $checked = ""; ?>
							<?php  if($entity->is_neighborhood){
								$checked ='checked="checked"';
							}?>
							<input type="hidden" name="is_neighborhood" value="0" />
							<input type="checkbox" <?php echo $checked; ?> name="is_neighborhood" id="is_neighborhood" value="1" >
						</td>
					</tr>
					<tr>
						<th scope="row">
							<label>Nome do Bairro</label>
						</th>
						<td>
							<input type="text" name="neighborhood_name" id="neighborhood_name" value="<?php echo $entity ? $entity->neighborhood_name : ""?>" >
						</td>
					</tr>
				</tbody>
			</table>
			<?php echo submit_button("Salvar");?>
			
		</form>
		
		<?php
	}
}