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

class Documents extends SiteController {
  function __construct () {
    parent::__construct();
    $this->data['page'] = 'documents';
    $this->data['metatags'] = $this->getMetatags($this->data['page']);
  }

  public function index () {
    $this->load->model('internBannerModel');
    $this->data['banner'] = $this->internBannerModel->getRowWhere(['slug' => 'documents']);

    $this->data['isLoggedIn'] = $this->isLoggedIn();

    $this->load->model('DocumentModel');
    $this->data['documents'] = $this->DocumentModel->getAll();

    $this->load->view('documents', $this->data);
  }

  private function isLoggedIn () {
    $user = $this->session->userdata('user');
    return is_array($user) && array_key_exists('id', $user);
  }

  public function validate () {
    $username = antiInjection($this->input->post('username'));
    $password = antiInjection($this->input->post('password'));

    $this->load->model('UserModel');
    $validUser = $this->UserModel->validate($username, $password);

    if ($validUser) {
      $this->session->set_userdata('user', [
        'id' => $validUser->id,
        'name' => $validUser->name
      ]);
      $this->session->set_flashdata('success', 'Login efetuado');
    } else {
      $this->session->set_flashdata('error', 'Credenciais inválidas');
    }

    redirect('documentos');
  }

  public function logout () {
    $this->session->unset_userdata('user');
    $this->session->set_flashdata('success', 'Logout efetuado');
    redirect('documentos');
  }
}