<?php

use Opencartvip\Opencart\Controller;
use Opencartvip\Utils\Arr;
use Opencartvip\Utils\Profiler;
use Opencartvip\Utils\Request;
use Opencartvip\Utils\Str;

class ControllerOpencartvipAdminBar extends Controller {

	public function index() {
		if (!$this->opencartvip->isAdmin() || Request::isAjax() || Request::isPost()) {
			return;
		}

		$route = Arr::get($this->request->get, 'route');

		if (Str::startsWith($route, 'extension/') || Str::startsWith($route, 'api/')) {
			return;
		}

		\Opencartvip\Utils\Profiler::end('opencartvip/admin_bar');

		$data['stats'] = Profiler::getStats();

		$data['ttfb'] = number_format(microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'], 3) * 1000;

		echo $this->renderView('opencartvip/admin_profiler', $data);

		if (!$this->opencartvip->settings->get('adminBar')) {
			return;
		}

//		$data['total_time'] = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'];
//		$data['query_time'] = \DB::$time;
//		$data['query_count'] = count(\DB::$log);
//		$data['queries'] = \DB::$log;

		$token = Arr::get($this->session->data, 'user_token');

		$data['edit_layout'] = 'admin/index.php?route=opencartvip/opencartvip&user_token=' . $token . '#/layout/edit/' . $this->opencartvip->document->getLayoutId();
		$data['edit_skin'] = 'admin/index.php?route=opencartvip/opencartvip&user_token=' . $token . '#/skin/edit/' . $this->opencartvip->settings->get('active_skin');

		$header_desktop = Arr::get(explode('/', $this->opencartvip->settings->get('headerDesktop')), 0);
		$header_mobile = Arr::get(explode('/', $this->opencartvip->settings->get('headerMobile')), 0);

		$data['desktop_headers'] = array();

		$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "opencartvip_module` WHERE `module_type` LIKE 'header_desktop_%' ORDER BY module_name ASC");

		foreach ($query->rows as $row) {
			$data['desktop_headers'][] = array(
				'name'     => 'Desktop: ' . $row['module_name'],
				'value'    => $row['module_id'] . '/' . $row['module_type'],
				'selected' => $header_desktop === $row['module_id'],
			);
		}

		$data['mobile_headers'] = array();

		$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "opencartvip_module` WHERE `module_type` LIKE 'header_mobile%' ORDER BY module_name ASC");

		foreach ($query->rows as $row) {
			$data['mobile_headers'][] = array(
				'name'     => 'Mobile: ' . $row['module_name'],
				'value'    => $row['module_id'] . '/' . $row['module_type'],
				'selected' => $header_mobile === $row['module_id'],
			);
		}

		echo $this->renderView('opencartvip/admin_bar', $data);
	}

	public function save() {
		if (!$this->opencartvip->isAdmin()) {
			return;
		}

		if ($value = Arr::get($this->request->post, 'headerDesktop')) {
			$this->model_opencartvip_settings->updateSetting('headerDesktop', $value);
		}

		if ($value = Arr::get($this->request->post, 'headerMobile')) {
			$this->model_opencartvip_settings->updateSetting('headerMobile', $value);
		}

		return $this->renderJson('success');
	}

}
