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

class Main extends MY_Controller {
	function __construct(){
        parent::__construct();
		// Check Session Login
		$this->load->model('setting_model');
		$this->load->model('winner_model');
		$this->load->model('register_model');
		$this->load->model('item_model');
		// if(!isset($_SESSION['logged_in'])){
		// 	redirect(site_url('auth/login'));
		// }
	}

	function index(){
		$data['judul_app'] = $this->setting_model->get_by_id(1);
		$data['image'] = $this->item_model->get_all();
		$dimage = $this->item_model->get_all();
		foreach ($dimage as $item) {
			$datav = $item->id_order;
		}
		$datap = [$datav];
		$data['last_value'] = end($datap);	
		$this->load->view('mb/index', $data);
		// $this->load->view('main/index', $data);
	}

	function image(){
		$data['judul_app'] = $this->setting_model->get_by_id(1);
		$data['image'] = $this->item_model->get_all();
		$this->load->view('main/image',$data);
	}

	function check(){
		$voucher = $this->input->post('code');
		$data['register'] = $this->register_model->get_voucher($voucher);
		$data['image'] = $this->item_model->get_all();
		$data['judul_app'] = $this->setting_model->get_by_id(1);
		if (!empty($data['register'])){
			// echo json_encode($data['register']);
			if ($data['register'][0]->used == "1"){
				$this->session->set_flashdata('data_failed', 'Tiket sudah pernah digunakan!');
				redirect(site_url(''));
			}else{
				$this->load->view('mb/claim',$data);
			}
		}else{
			$this->session->set_flashdata('data_failed', 'Harap Periksa Kode Tiket Anda!');
			redirect(site_url(''));
		}
	}

	function check_session($username){
		$data['username'] = $username;
		$data['check'] = $this->register_model->check_username($username);
		$this->load->view('main/check_session',$data);
	}

	function confirm(){
		$voucher = $this->input->post('code');
		$data['register'] = $this->register_model->get_voucher($voucher);
		$check = $data['register'];
		if ($check){
			$data = array(
				'used' => 1
			);
			$data_winner = array(
				'username' => $check[0]->username,
				'winner' => $check[0]->item_value
			);
			$this->register_model->update_voucher($voucher,$data);
			$this->winner_model->insert($data_winner);
		}
	}

	function history(){
		$data['winner'] = $this->winner_model->get_all();
		$this->load->view('main/history',$data);
	} 

	function logout(){
		$this->login_model->unset_session();
		redirect(site_url(''));
	}
}
