<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Home extends CI_Controller
{

	public function __construct()
	{
		parent::__construct();
		$this->load->library('form_validation');
		$this->load->model('Categories_model');
		$this->load->model('Products_model');
		$this->load->model('Settings_model');
		$this->load->model('Promo_model');

		if ('%BASE_URL%/' == base_url() || '%BASE_URL%' == base_url()) {
			$url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]/install";
			redirect($url);
			exit;
		}
	}

	public function index()
	{
		// if ('%BASE_URL%/' == base_url() || '%BASE_URL%' == base_url()) {
		// 	$url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]/install";
		// 	redirect($url);
		// 	exit;
		// }


		$data['title'] =  $this->Settings_model->general()["app_name"];
		$data['css'] = 'style';
		$data['responsive'] = 'style-responsive';
		$data['setting'] = $this->Settings_model->getSetting();
		$data['categories'] = $this->Categories_model->getCategories();
		$data['categoriesLimit'] = $this->Categories_model->getCategoriesLimit();
		$data['promo'] = $this->Promo_model->getPromo();
		$data['getPromo'] = $this->Promo_model->getPromoLimit();
		$data['recent'] = $this->Products_model->getProductsLimit(0);
		$data['best'] = $this->Products_model->getBestProductsLimit();
		$data['allProducts'] = $this->db->get('products');
		$this->db->where('status !=', 0);
		$this->db->limit(100);
		$this->db->order_by('id', 'desc');
		$data['invoice'] = $this->db->get('invoice');
		$data['banner_popup'] = $this->db->get('banner_popup')->row_array();
		$this->load->view('templates/header', $data);
		$this->load->view('templates/navbar');
		$this->load->view('templates/subnavbar');
		$this->load->view('templates/banner');
		$this->load->view('index');
		$this->load->view('templates/footer_tmpl');
		$this->load->view('templates/footer_real');
	}

	public function sitemap()
	{
		$data['categories'] = $this->db->get('categories');
		$data['products'] = $this->db->get('products');
		$data['pages'] = $this->db->get('pages');
		$this->load->view('sitemap', $data);
	}

	public function notfound()
	{
		$data['title'] = 'Page Not Found - 404';
		$this->load->view('templates/header', $data);
		$this->load->view('templates/navbar');
		$this->load->view('templates/subnavbar');
		$this->load->view('404');
		$this->load->view('templates/footer_tmpl');
		$this->load->view('templates/footer_real');
	}

	public function login()
	{
		$this->load->helper('cookie');
		if ($this->session->userdata('admin')) {
			redirect(base_url() . 'administrator');
		} else {
			$cookie = get_cookie('djehbicd');
			if ($cookie != NULL) {
				$getCookie = $this->db->get_where('admin', ['cookie' => $cookie])->row_array();
				if ($getCookie) {
					$dataCookie = $getCookie;
					$dataSession = [
						'id' => $dataCookie['id']
					];
					$this->session->set_userdata('admin', true);
					$this->session->set_userdata($dataSession);
					redirect(base_url() . 'administrator');
				}
			}
		}
		$this->form_validation->set_rules('username', 'username', 'required', ['required' => 'username wajib diisi']);
		if ($this->form_validation->run() == false) {
			$this->load->view('login');
		} else {
			$username = $this->input->post('username');
			$password = $this->input->post('password');
			$cookie = $this->input->post('cookie');
			$admin = $this->db->get_where('admin', ['username' => $username])->row_array();

			if ($admin) {
				if (password_verify($password, $admin['password'])) {
					$data = [
						'id' => $admin['id']
					];

					if ($cookie != NULL) {
						$key = random_string('alnum', 64);
						set_cookie('djehbicd', $key, 3600 * 24 * 30 * 12);
						$this->db->set('cookie', $key);
						$this->db->update('admin');
					}

					$this->session->set_userdata('admin', true);
					$this->session->set_userdata($data);

					redirect(base_url() . 'administrator');
				} else {
					$this->session->set_flashdata('failed', '<div class="alert alert-danger" role="alert">
                              Password salah!
                            </div>');
					redirect(base_url() . 'login/admin');
				}
			} else {
				$this->session->set_flashdata('failed', '<div class="alert alert-danger" role="alert">
                Username salah!
              </div>');
				redirect(base_url() . 'login/admin');
			}
		}
	}

	public function license()
	{

		$this->load->helper('cookie');
		if (!$this->session->userdata('admin')) {
			redirect(base_url() . 'login/admin');
		}

		$data = license_read();

		$license_data = [];

		if (is_array($data) && base_url() == $data['string'] && strtotime('now') < $data['active_end']) {
			//redirect(base_url() . 'administrator');
			$license_data = $data;
		}

		$rules = [
			[
				'field' => 'email',
				'label' => 'Email',
				'rules' => 'required|valid_email',
			],
			[
				'field' => 'password',
				'label' => 'Password',
				'rules' => 'required',
			],
			[
				'field' => 'code',
				'label' => 'Code',
				'rules' => 'required',
			]
		];

		$this->form_validation->set_rules($rules);
		if ($this->form_validation->run() == false) {
			$enable = true;
			if (is_curl_enabled() === false) {
				$this->session->set_flashdata('failed', '<div class="alert alert-danger" role="alert">
    PHP curl extension tidak aktif di dalam server Anda, silahkan aktifkan terlebih dahulu
</div>');
				$enable = false;
			}
			$data = [
				'enable' => $enable,
				'lic' => $license_data,
			];

			$this->load->view('license', $data);
		} else {
			$email = $this->input->post('email');
			$password = $this->input->post('password');
			$code = $this->input->post('code');
			$action = $this->input->post('action');

			if ($action == 'activate') {
				try {
					register_license($email, $password, $code);
					check_license();

					$this->session->set_flashdata('license_activated', '<div class="alert alert-success" role="alert">Lisensi Anda berhasil di aktifkan </div>');

					redirect(base_url() . 'administrator');
				} catch (Exception $e) {
					$this->session->set_flashdata('failed', '<div class="alert alert-danger" role="alert">' . $e->getMessage() . '</div>');

					redirect(base_url() . 'license');
				}
			} else {
				try {
					delete_license($email, $password, $code);

					redirect(base_url() . 'license');
				} catch (Exception $e) {
					$this->session->set_flashdata('failed', '<div class="alert alert-danger" role="alert">' . $e->getMessage() . '</div>');

					redirect(base_url() . 'license');
				}
			}
		}
	}
}
