<?php

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

class Admin extends CI_Controller {

	public function __construct() {
		parent::__construct();

		$this->load->library('form_validation');
		$this->load->driver('session');

		//$this->load->spark('birdseed/1.0.0');

		// check if user is logged in and redirect to login page if needed
		$logged_in = $this->session->userdata('logged_in');
		$method = $this->uri->segment(2);
		if ($logged_in == FALSE) { // user is not logged in
			if ($method != 'login' AND $method != 'registration' AND $method != 'reset_password') { // no need to redirect from here
				redirect(base_url().'admin/login', 'refresh');
			}
		} else { // user is already logged in
			if ($method == 'login' OR $method == 'registration' OR $method == 'reset_password') { // no need to redirect from here
				redirect(base_url().'admin/', 'refresh');
			}
		}

	}

	public function index() {
		//$this->load->spark('example-spark/1.0.0'); // Don't forget to add the version!
		//$this->example_spark->printHello(); // echo's "Hello from the example spark!"

		$data['username'] = $this->session->userdata('username');
		$this->load->view('templates_admin/index', $data);
	}

	public function login() {
		$data['login_message'] = '';
		$this->form_validation->set_rules('username', 'Username', 'trim|required');
		$this->form_validation->set_rules('password', 'Password', 'trim|required');
		if ($this->form_validation->run() == FALSE) { // login validation error
			$this->load->view('templates_admin/login', $data);
		} else { // login validation success
			$this->db->where('username', $this->input->post('username'));
			$this->db->where('password', md5($this->input->post('password')));
			$query = $this->db->get('users'); // lets check if user exist
			if ($query->num_rows() == 1) { // username exists in database; username and password match
				$login_session_data = array(
					'username' => $this->input->post('username'),
					//'email' => 'johndoe@site.com',
					'logged_in' => TRUE
				);
				$this->session->set_userdata($login_session_data); // store session data in cookies
				redirect(base_url().'admin/', 'refresh');
			} else { // login error
				$data['login_message'] = 'Incorrect username or password.';
				$this->load->view('templates_admin/login', $data);
			}
		}

	}

	public function registration() {

		$data['registration_message'] = '';
		$this->form_validation->set_rules('username', 'Username', 'trim|required|is_unique[users.username]|alpha_numeric');
		$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
		$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[8]');

		if ($this->form_validation->run() == FALSE) { // registration validation error
			$this->load->view('templates_admin/registration', $data);
		} else { // registration validation success
			$registration_data = array(
				'username' => $this->input->post('username'),
				'email' => $this->input->post('email'),
				'password' => md5( $this->input->post('password') )
			);
			$insert = $this->db->insert('users', $registration_data);
			if ($insert == TRUE) {
				$data['registration_message'] = 'Username was created successfully.';
			} else {
				$data['registration_message'] = 'Registration error.';
			}
			$this->load->view('templates_admin/registration', $data);
		}

	}


	public function logout() {
		$this->session->sess_destroy();
		redirect(base_url().'admin/login', 'refresh');
	}


	public function posts() {
		$this->load->model('post_model');
		$data['posts'] = $this->post_model->get_all();
		$this->load->view('templates_admin/posts', $data);
	}


	public function post_delete($id) {
		$this->load->model('post_model');
		$this->post_model->delete($id);
		redirect(base_url().'admin/posts');
	}


	public function post_edit($id = 0) {
		$this->load->model('post_model');

		if ($id) {
			$data['post'] = $this->post_model->get_post_by('id', $id);
			count($data['post']) || $data['errors'][] = 'post could not be found';
		} else {
			$data['post'] = array(
				'title' => '',
				'slug' => '',
				'published' => date('Y-m-d H:i:s'),
				'content' => ''
			);
		}

		$this->form_validation->set_rules('title', 'Title', 'trim|required');
		$this->form_validation->set_rules('slug', 'Slug', 'trim|required'); // |is_unique[posts.slug] // not working on update
		$this->form_validation->set_rules('published', 'Published', 'trim|required');
		$this->form_validation->set_rules('content', 'Content', 'trim|required');

		if ($this->form_validation->run() == TRUE) {
			$data = $this->post_model->array_from_post(array(
				'title',
				'slug',
				'published',
				'content'
			));
			if ($id) {
				$this->post_model->update($data, $id);
				redirect('admin/post_edit/'.$id);
			} else {
				$insert_id = $this->post_model->create($data);
				redirect('admin/post_edit/'.$insert_id);
			}
		}

		$this->load->view('templates_admin/post_edit', $data);
	}

}