<?php
namespace Datacake\Core\Admin;

use Datacake\Core\Admin\Crud\CityCrud;
use Datacake\Core\Admin\Crud\RedirectCrud;
use Datacake\Core\Wda\CityApi;
use Datacake\Core\ORM\WP\Post;
use Datacake\Core\Models\IspCity;
/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Datacake_core
 * @subpackage Datacake_core/admin
 * @author     Datacake <ajuda@datacake.com.br>
 */
class DatacakeCoreAdmin {

	/**
	 * The ID of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $plugin_name    The ID of this plugin.
	 */
	private $plugin_name;

	/**
	 * The version of this plugin.
	 *
	 * @since    1.0.0
	 * @access   private
	 * @var      string    $version    The current version of this plugin.
	 */
	private $version;
	private $global_settings = array();
	private $user_role = 'admin';
	
	/**
	 * Initialize the class and set its properties.
	 *
	 * @since    1.0.0
	 * @param      string    $plugin_name       The name of this plugin.
	 * @param      string    $version    The version of this plugin.
	 */
	public function __construct( $plugin_name, $version ) {

		$this->plugin_name = $plugin_name;
		$this->version = $version;
		$this->global_settings = $this->get_global_settings();

		$this->set_user_role();

	}

	/**
	 * TODO: Move this function to abstract class and exted current class
	 */
	public function get_val($arr, $key, $default = ''){
		$arr = (array)$arr;	
		
		if(is_array($key)){
			$a = $arr;
			foreach($key as $k => $v){
				$a = $this->get_val($a, $v, $default);				
			}
			return $a;
			/*$val = $default;
			foreach($key as $k => $v){
				$val = (array)$val;
				$val = (isset($val[$v])) ? $val[$v] : $default;
			}*/
		}else{						
			$val = (isset($arr[$key])) ? $arr[$key] : $default;			 		
		}
		return $val;
	}
	/**
	 * This function will add cookie groups to w3 full page cache
	 * we need to disable browser cache on the plugin for that to work
	 */
	public function w3tc_pgcache_cookiegroups_filter($cookiegroups){
		$cityEntity = new IspCity();
		$cities = $cityEntity->orderBy('id','ASC')->get();
        if (!empty($cities)) {
			foreach ($cities as $key => $city) {
				$cookiegroups[ "isp_city_".$city->id ] = array(
					'enabled' => true,
					'cache'   => true,
					'cookies' => "city=".$city->id,
				);
			}
		}	
		return $cookiegroups;
	}
	/**
	 * TODO: Move this function to abstract class and exted current class
	 */
	public function get_global_settings(){
		$gs = get_option('isp-global-settings', '');
		if(!is_array($gs)){
			$gs = json_decode($gs, true);
		}
		
		return apply_filters('isp_get_global_settings', $gs);
	}

	/**
	 * Register the stylesheets for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_styles() {

		wp_enqueue_style( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'css/datacake_core-admin.css', array(), $this->version, 'all' );

	}

	/**
	 * Register the JavaScript for the admin area.
	 *
	 * @since    1.0.0
	 */
	public function enqueue_scripts() {

		wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'js/datacake_core-admin.js', array( 'jquery' ), $this->version, false );

	}
	/**
	 * set the user role, to restrict plugin usage to certain groups
	 * @since: 6.0
	 **/
	public function set_user_role(){
		$this->user_role = $this->get_val($this->global_settings, 'permission', 'admin');
	}
	
	/**
	 * Register new Menu Page
	 */
	public function admin_menu()
	{
		$role = 'manage_options';
		add_menu_page(
			"Datacake ISP", "Datacake ISP", $role, "isp", 
			[$this, 'edit_settings'], 'dashicons-admin-site-alt3'
		);
		
		// Adding Menu for City
		$cityCrud = new CityCrud();
		$cityCrud->menu_items($role, $this->plugin_name);
		
		// Adding Menu for Redirect
		$redirectCrud = new RedirectCrud();
		$redirectCrud->menu_items($role, $this->plugin_name);

		
		
	}
	public function save_settings()
	{
		$result = [
			'status'=>false,
			'message'=>'Starting'
		];
		
		$data = [
			"email" => sanitize_email($_POST['email']),
			"url" =>esc_url($_POST['url']),
			"password" => sanitize_text_field($_POST['password']),
			"google_api_key" => sanitize_text_field($_POST['google_api_key'])
			
		];
		$data_redirect = null;
		$pageId = null;
		if(isset($_POST['page_redirect'])){
			$pageId = sanitize_key($_POST['page_redirect']);
			update_option('datacake_redir_page_id',$pageId);
		}
		$force_redirect = false;
		if(isset($_POST['force_redirect'])){
			$force_redirect = sanitize_key($_POST['force_redirect']);
		}
		update_option('datacake_redir_force',$force_redirect);
		
		
		
		if($data['email'] && $data['url'] && $data['password']){
			delete_transient('datacake_api_token');
			update_option('datacake_api',$data);
			$result['status'] = true;
			$result['message'] = 'Salvo com sucesso';
			// TODO: TEST API
			try {
				$cityApi = new CityApi([
					'raiseError'=>true,
				]);
				$cityApi->getRequestBuilder();
			} catch (\Throwable $th) {
				$result['status'] = false;
				$error = $th->getMessage();
				$result['message'] = "Configurações salvas, mas credenciais e dados da API Datacake parecem estar erradas.\n<b>$error</b>";
			
			}
			
			
				
			
		} else {
			delete_transient('datacake_api_token');
			update_option('datacake_api',$data);
			$result['message'] = 'Removido as configurações';
		}
		return $result;
	}

	public function edit_settings()
	{

		if (isset($_REQUEST['action'])) {
			$result = $this->save_settings();
			if ($result['message']) {
				?>
					<div class="notice is-dismissible <?php echo $result['status']?'notice-success':'notice-error' ?>">
						<p><?php echo $result['message'] ?></p>
					</div>
				<?php
			}
		}

		$postEntity = new Post();
		$posts = $postEntity->select('ID','post_title','post_name')->where('post_type','page')->get();
		$data_redirect = get_option('datacake_redir_page_id',null);
		
		$data = get_option('datacake_api', null);
		$force_redirect = get_option('datacake_redir_force',null);
		if($data){
			$data = $data;
			
		}else{
			$data = [
				'email'=> '',
				'password'=> '',
				'url'=> ''
			];
		}

	

		?>
            <div class="wrap">
                <h2>Configurações Datacake ISP</h2>
                <form method="post">
					<div class="form-wrap">
						<input type="hidden" name="action" value="save_config"/>
						<table class="form-table">
							<tbody>
								<!-- TODO change to APIKEY + EMAIL -->
								<tr>
									<th scope="row">LINK BASE API</th>
									<td>
										<input type="text" name="url" id="url" value="<?php echo isset($data['url']) ? $data['url'] : ""; ?>" >
										<small style="padding-left:35px;">http://exemplo.com.br/</small>
										
									</td>
								</tr>
								<tr>
									<th scope="row">USER EMAIL</th>
									<td>
										<input type="email" name="email" id="email" value="<?php echo isset($data['email']) ? $data['email'] : ""; ?>" >
										
									</td>
								</tr>
								<tr>
									<th scope="row">USER_PASSWORD</th>
									<td>
										<input type="password" name="password" id="password" value="<?php echo isset($data['password']) ? $data['password'] : ""; ?>" >
										
										</small>
									</td>
								</tr>
								<tr>
									<th scope="row">GOOGLE API TOKEN</th>
									<td>
										<input type="google_api_key" name="google_api_key" id="google_api_key" value="<?php echo isset($data['google_api_key']) ? $data['google_api_key'] : ""; ?>" >
									</td>
								</tr>
								<tr>
									<th scope="row">BASE REDIRECT (PAGINA PADRÃO)</th>
									<td>
									<select type="text" name="page_redirect" id="page_redirect" required>
										<option>-- SELECIONE --</option>
										<?php foreach ($posts as $key => $post): ?>
											<?php $selected = ($data_redirect == $post->ID ? "selected='selected'" : "") ?>
											<option value='<?php echo $post->ID; ?>'  <?php echo $selected;?> ><?php echo $post->post_title." - (".$post->post_name.")" ?></option>
										<?php endforeach; ?>
									</select>
										
									</td>
								</tr>
								<tr>
									<th scope="row">Forçar Redirect</th>
									<td>
											
										<input type="checkbox" name="force_redirect" id="force_redirect" value="1" <?php echo $force_redirect ? 'checked="checked"':''?> >
									</td>
								</tr>
							</tbody>
						</table>

						<div class="form-field">
							<?php echo submit_button("SALVAR"); ?>
						</div>
						
						<?php 
							$token = get_transient('datacake_api_token');
						?>
						<div class="notice <?php echo $token?'notice-success':'notice-error' ?>">
								<?php if($token): ?>
									API Configurada com <b>sucesso</b>
								<?php else: ?>
									Não Configurado corretamente
								<?php endif; ?>
						</div>
                    </div>
        		
				</form>

				<!-- SYNC BUTTONS -->
				<button id="dk_core_sync_products" class="button action pull <?php echo $token?'':'disabled' ?>">
					<span class="dashicons dashicons-image-rotate"></span>
					Sincronizar Produtos
				</button>

				<!-- SYNC CHANNELS -->
				<button id="dk_core_sync_canais" class="button action pull <?php echo $token?'':'disabled' ?>">
					<span class="dashicons dashicons-image-rotate"></span>
					Sincronizar Canais
				</button>
				<div id="dk_core_sync_contents_products" >
											
				</div>
				<div id="dk_core_sync_contents_canais" >
											
				</div>
            </div>
		<?php
	
	}
}
