<?php

use Restserver\Libraries\REST_Controller;

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

require APPPATH . 'libraries/REST_Controller.php';
require APPPATH . 'libraries/Format.php';

class Api extends REST_Controller
{

  function __construct()
  {
    parent::__construct();
    $this->load->model('DAO');
  }

  function user_get()
  {
    $id = $this->get('id');
    if (count($this->get()) > 1) {
      $response = array(
        "status" => "error",
        "status_code" => 409,
        "message" => "Too many params was sent",
        "validations" => array(
          "id" => "Send Id (Get) to get specific brand, or empty to get all brands"
        ),
        "data" => null
      );
    } else {
      if ($id) {
        $response = $this->DAO->selectEntity('usuario', array('id_usuario' => $id), TRUE);
      } else {
        $response = $this->DAO->selectEntity('usuario', array('status' => 1));
      }
    }
    $this->response($response, $response['status_code']);
  }


  function user_post()
  {
    $data = $this->post();
    if (count($data) == 0 || count($data) > 12) {
      $response = array(
        "status" => "error",
        "status_code" => 409,
        "message" => count($data) == 0 ? 'No data received' : 'Too many data received',
        "data" => count($data),
        "validations" => array(
          "nombre_usuario" => "required and unique",
          "apellido_paterno" => "required and unique",
        
          "telefono_usuario" => "required and unique",
          "email" => "required and unique",
          "password" => "required and unique",
          "nivel" => "required and unique",
          "img_perfil" => "required and unique",

        )
      );
    } else {
      $this->form_validation->set_data($data);
      $this->form_validation->set_rules('nombre_usuario', 'nombre_usuario', 'required');
      $this->form_validation->set_rules('apellido_paterno', 'apellido_paterno', 'required');
     
      $this->form_validation->set_rules('telefono_usuario', 'telefono_usuario', 'required');
      $this->form_validation->set_rules('email', 'email', 'required');
      $this->form_validation->set_rules('password', 'password	', 'required');
      $this->form_validation->set_rules('nivel', 'nivel', 'required');
      
      if ($this->form_validation->run() == FALSE) {
        $response = array(
          "status" => "error",
          "status_code" => 409,
          "message" => "validations error",
          "data" => null,
          "validations" => $this->form_validation->error_array()
        );
      } else {
        $this->load->library('bcrypt');
        $file = "user".time();
        $config['upload_path'] = 'uploads';
        $config['allowed_types'] = '*';
        $config['max_size'] = '0';
        $config['overwrite'] = TRUE;
        $config['file_name'] = $file;
        $this->load->library('upload', $config);
        if ($this->upload->do_upload("img_perfil")) {
          $doc_data = array('upload_data' => $this->upload->data());
          $imagen = $doc_data['upload_data']['file_name'];
        } else {
          $imagen = '1';
        }
        $user = array(
          "nombre_usuario" => $this->post('nombre_usuario'),
          "apellido_paterno" => $this->post('apellido_paterno'),
          "apellido_materno" => $this->post('apellido_materno'),
          "telefono_usuario" => $this->post('telefono_usuario'),
          "email" => $this->post('email'),
          "password" => $this->bcrypt->hash_password($this->input->post('password')),
          "nivel" => $this->post('nivel'),
          "img_perfil" => $imagen,

        );
        $dataResponse = $this->DAO->saveOrUpdateItem('usuario', $user, null, true);
        if ($dataResponse['status'] == "success") {
          $response = array(
            "status" => "success",
            "status_code" => 200,
            "message" =>  "item created successfully",
            "data" => null,
          );
        } else {
          $response = array(
            "status" => "error",
            "status_code" => 409,
            "message" =>  $dataResponse['message'],
            "data" => null,
          );
        }
      }
    }

    //$this->response($response,200);
    $this->response($response, $response['status_code']);
  }

  function user_put()
  {
    $id = $this->get('id');
    if ($id) {
      $dataExists = $this->DAO->selectEntity('usuario', array('id_usuario' => $id), TRUE);
      if ($dataExists) {
        if (count($this->put()) > 12) {
          $response = array(
            "status" => "error",
            "status_code" => 409,
            "message" => "Too many data was sent",
            "validations" => array(
              "nombre_usuario" => "required and unique",
              "apellido_paterno" => "required and unique",
              "apellido_materno" => "required and unique",
              "telefono_usuario" => "required and unique",
              "email" => "required and unique",
              "password" => "required and unique",
              "nivel" => "required and unique",
              "img_perfil" => "required and unique",
            ),
            "data" => null
          );
        } else if (count($this->put()) == 0) {
          $response = array(
            "status" => "error",
            "status_code" => 409,
            "message" => "No data was sent",
            "validations" => array(
              "nombre_usuario" => "required and unique",
              "apellido_paterno" => "required and unique",
              "apellido_materno" => "required and unique",
              "telefono_usuario" => "required and unique",
              "email" => "required and unique",
              "password" => "required and unique",
              "nivel" => "required and unique",
              "img_perfil" => "required and unique",
            ),
            "data" => null
          );
        } else {

          $this->form_validation->set_data($this->put());
          $this->form_validation->set_rules('nombre_usuario', 'nombre_usuario', 'required');
          $this->form_validation->set_rules('apellido_paterno', 'apellido_paterno', 'required');
          $this->form_validation->set_rules('apellido_materno', 'apellido_materno	', 'required');
          $this->form_validation->set_rules('telefono_usuario', 'telefono_usuario', 'required');
          $this->form_validation->set_rules('email', 'email', 'required');
          $this->form_validation->set_rules('password', 'password	', 'required');
          $this->form_validation->set_rules('nivel', 'nivel', 'required');

          if ($this->form_validation->run() == FALSE) {
            $response = array(
              "status" => "error",
              "status_code" => 409,
              "message" => "Validation fail, see validations object for more details",
              "validations" => $this->form_validation->error_array(),
              "data" => null
            );
          } else {
            $this->load->library('bcrypt');
            $file = "user" . time();
            $config['upload_path'] = 'uploads';
            $config['allowed_types'] = '*';
            $config['max_size'] = '0';
            $config['overwrite'] = TRUE;
            $config['file_name'] = $file;
            $this->load->library('upload', $config);
            if ($this->upload->do_upload("img_perfil")) {
              $doc_data = array('upload_data' => $this->upload->data());
              $imagen = $doc_data['upload_data']['file_name'];
            } else {
              $imagen = '1';
            }


            $data = array(
              "nombre_usuario" => $this->put('nombre_usuario'),
              "apellido_paterno" => $this->put('apellido_paterno'),
              "apellido_materno" => $this->put('apellido_materno'),
              "telefono_usuario" => $this->put('telefono_usuario'),
              "email" => $this->put('email'),
              "password" => $this->bcrypt->hash_password($this->put('password')),
              "nivel" => $this->put('nivel'),
              "img_perfil" => $imagen,
            );

            $response = $this->DAO->saveOrUpdateItem('usuario', $data, array('id_usuario' => $id));
          }
        }
      }
    } else {

      $response = array(
        "status" => "error",
        "status_code" => 409,
        "message" => "Too data was sent",
        "validations" => array(
          "id" => "Required",

        ),
        "data" => null
      );
    }
    $this->response($response, $response['status_code']);
  }


  function user_delete()
  {
    $id = $this->get('id');
    if ($id) {
      $dataExists = $this->DAO->selectEntity('usuario', array('id_usuario' => $id), TRUE);
      if ($dataExists['data']) {
        date_default_timezone_set('America/Mexico_City');
        $currentDate = date('Y-m-d H:i:s');
        $births = array(
          'status' => 0,
          'usuarios_update' => $currentDate
        );
        $response = $this->DAO->updateData('usuario', $births, array('id_usuario' => $id));
      } else {
        $response = array(
          "status" => "error",
          "status_code" => 409,
          "message" => "the code of animal does not exists",
          "validations" => null,
          "data" => null
        );
      }
    } else {
      $response = array(
        "status" => "error",
        "status_code" => 409,
        "message" => "Id wasn't sent",
        "validations" => array(
          "id" => "Required (get)",
        ),
        "data" => null
      );
    }
    $this->response($response, $response['status_code']);
  }
}
