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

class Winner extends MY_Controller {
	function __construct(){
        parent::__construct();
		$this->load->model('winner_model');
		$this->load->model('setting_model');
		$this->load->model('user_model');
        $this->load->library('form_validation');
		
		// Check Session Login
		if(!isset($_SESSION['logged_in'])){
			redirect(site_url('auth/login'));
		}
	}
	
	public function index(){
		$data['judul_app'] = $this->setting_model->get_by_id(1);
		if(isset($_GET['search'])){
			$filter = array();
            if(!empty($_GET['username']) && $_GET['username'] != ''){
                $filter['winner.username ='] = $_GET['username'];
			}

			$total_row = $this->winner_model->count_total_filter($filter);
			$data['winners'] = $this->winner_model->get_filter($filter,url_param());
		}else{
			$total_row = $this->winner_model->count_total();
			$data['winners'] = $this->winner_model->get_all(url_param());
		}
		$data['paggination'] = get_paggination($total_row,get_search());

		$this->load->view('winner/index',$data);
	}
	
	public function create(){
		$data['judul_app'] = $this->setting_model->get_by_id(1);
		$code_winner = $this->winner_model->get_last_id();
		$this->load->view('winner/form',$data);
	}

	public function edit($id = ''){
		$data['judul_app'] = $this->setting_model->get_by_id(1);
		$check_id = $this->winner_model->get_by_id($id);
		if($check_id){
			$data['winner'] = $check_id[0];
			$this->load->view('winner/form',$data);
		}else{
			redirect(site_url('winner'));
		}
	}

	public function save($id = ''){
		$this->form_validation->set_rules('username', 'ID', 'required');
		$this->form_validation->set_rules('winner', 'Nama', 'required');

		$data['username'] = escape($this->input->post('username'));
		$data['winner'] = escape($this->input->post('winner'));

		if ($this->form_validation->run() != FALSE && !empty($id)) {
			// EDIT
			$check_id = $this->winner_model->get_by_id($id);
			if($check_id){
				unset($data['id']);
				$this->winner_model->update($id,$data);
			}
		}elseif($this->form_validation->run() != FALSE && empty($id)){
			// INSERT NEW
			$this->winner_model->insert($data);
		}else{
			$this->session->set_flashdata('form_false', 'Harap periksa form anda.');
			redirect(site_url('winner/create'));
		}
		redirect(site_url('winner'));
	}
	public function delete($id){
		$check_id = $this->winner_model->get_by_id($id);
		if($check_id){
			$this->winner_model->delete($id);
		}
		redirect(site_url('winner'));
	}
	public function export_csv(){
		$filter = false;
		if(isset($_GET['search'])) {
			$filter = array();
			if (!empty($_GET['value']) && $_GET['value'] != '') {
				$filter[$_GET['search_by'] . ' LIKE'] = "%" . $_GET['value'] . "%";
			}
		}
		$data = $this->winner_model->get_all_array($filter);
		$this->csv_library->export('winner.csv',$data);
	}
}
