<?php

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

class Roles extends CI_Controller {

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

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

		// 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->model('role_model');
		$data['roles'] = $this->role_model->get();
		$this->load->view('templates_admin/roles', $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);
	}

}