<?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 diseases_get()
  {
    $id = $this->get('id');
    $idAnimal = $this->get('idAnimal');
    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('diseases', array('id_diseases' => $id), TRUE);
      } else if ($idAnimal) {
        $response = $this->DAO->selectEntity('diseases', array('id_animal' => $idAnimal,'status' => 1), false);
      } else{
        $response = $this->DAO->selectEntity('vw_diseases', array('status' => 1), false);
      }
    }
    $this->response($response, $response['status_code']);
  }

  function diseasesDoc_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('doc_diseases', array('id_diseases' => $id, 'status' => 1), FALSE);
       } else {
        $response = $this->DAO->selectEntity('doc_diseases', array('status' => 1), false);
      }
    }
    $this->response($response, $response['status_code']);
  }

  function diseases_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(
          "diseases" => "required and unique",
          "date_diseases" => "required and unique",
          "id_animal" => "required and unique",
        )
      );
    } else {
      $this->form_validation->set_data($data);
      $this->form_validation->set_rules('diseases', 'diseases', 'required');
      $this->form_validation->set_rules('date_diseases', 'date_diseases', 'required');
      $this->form_validation->set_rules('id_animal', 'id_animal', '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 {
        date_default_timezone_set('America/Mexico_City');
        $currentDate = date('Y-m-d H:i:s');
        $folder_name= "diseases";
        $deworming = array(
          "diseases" => $this->post('diseases'),
          "date_diseases" => $this->post('date_diseases'),
          "id_animal" => $this->post('id_animal'),
          "comment" => $this->post('comment'),
          "created_user" => $this->post('created_user'),
          "created_date"=>$currentDate,
        );
        $diseasesResponse = $this->DAO->saveOrUpdateItem('diseases', $deworming, null, true);

        if ($diseasesResponse['key']) {
          $this->load->library('upload');
          $files = $_FILES;
          $cpt = count($_FILES['doc_diseases']['name']);
          for ($i = 0; $i < $cpt; $i++) {
            $tmp = explode('.', $files['doc_diseases']['name'][$i]);
            $ext = end($tmp);
            $file = 'DOC-' . uniqid() . $i . '.' . $ext;
            $_FILES['userfile']['name'] = $file;
            $_FILES['userfile']['type'] = $files['doc_diseases']['type'][$i];
            $_FILES['userfile']['tmp_name'] = $files['doc_diseases']['tmp_name'][$i];
            $_FILES['userfile']['error'] = $files['doc_diseases']['error'][$i];
            $_FILES['userfile']['size'] = $files['doc_diseases']['size'][$i];
            $this->upload->initialize($this->set_upload_options($folder_name));
            $this->upload->do_upload();
            $savedoc['doc_diseases'] = $_FILES['userfile']['name'];
            $savedoc['id_diseases'] = $diseasesResponse['key'];
            $this->DAO->saveOrUpdateItem('doc_diseases', $savedoc);
          }
          $response = array(
            "status" => "success",
            "status_code" => 200,
            "key" => $diseasesResponse['key'],
            "message" =>  "Vehículo registrado exitosamente.",
            "data" => null,
          );
        }
         else {
          $response = array(
            "status" => "error",
            "status_code" => 409,
            "message" =>  $diseasesResponse['message'],
            "data" => null,
          );
        }
      }
    }
    $this->response($response, $response['status_code']);
  }

  function diseases_put()
  {
    $id = $this->get('id');
    if ($id) {
      $dataExists = $this->DAO->selectEntity('diseases', array('id_diseases' => $id), TRUE);
      if ($dataExists) {
        if (count($this->put()) > 12) {
          $response = array(
            "status" => "error",
            "status_code" => 409,
            "message" => "Too many data was sent",
            "validations" => array(
              "diseases" => "required and unique",
              "date_diseases" => "required and unique",
              "comment" => "required and unique",
              "id_animal" => "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(
              "diseases" => "required and unique",
              "date_diseases" => "required and unique",
              "comment" => "required and unique",
              "id_animal" => "required and unique",
            ),
            "data" => null
          );
        } else {
          $this->form_validation->set_data($this->put());
          $this->form_validation->set_rules('diseases', 'diseases', 'required');
          $this->form_validation->set_rules('date_diseases', 'date_diseases', 'required');
          $this->form_validation->set_rules('id_animal', 'id_animal', 'required');
          $this->form_validation->set_rules('comment', 'comment', '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 {
            date_default_timezone_set('America/Mexico_City');
            $currentDate = date('Y-m-d H:i:s');
          
            $data = array(
              "diseases" => $this->put('diseases'),
              "date_diseases" => $this->put('date_diseases'),
              "id_animal" => $this->put('id_animal'),
              "comment" => $this->put('comment'),
              "updated_date" => $currentDate,
              "updated_user" => $this->put('updated_user'),
              
            );

            $response = $this->DAO->saveOrUpdateItem('diseases', $data, array('id_diseases' => $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 diseases_delete()
  {
    $id = $this->get('id');
    if ($id) {
      $dataExists = $this->DAO->selectEntity('diseases', array('id_diseases' => $id), TRUE);
      if ($dataExists['data']) {
        date_default_timezone_set('America/Mexico_City');
        $currentDate = date('Y-m-d H:i:s');
        $births = array(
          'status' => 0,
          'updated_date' => $currentDate
        );
        $response = $this->DAO->updateData('diseases', $births, array('id_diseases' => $id));
      } else {
        $response = array(
          "status" => "error",
          "status_code" => 409,
          "message" => "the code of diseases 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']);
  }

  function diseasesDoc_delete()
  {
    $id = $this->get('id');
    if ($id) {
      $dataExists = $this->DAO->selectEntity('doc_diseases', array('id_document' => $id), TRUE);
      if ($dataExists['data']) {
        date_default_timezone_set('America/Mexico_City');
        $currentDate = date('Y-m-d H:i:s');
        $births = array(
          'status' => 0,
          'updated_date' => $currentDate
        );
        $response = $this->DAO->updateData('doc_diseases', $births, array('id_document' => $id));
      } else {
        $response = array(
          "status" => "error",
          "status_code" => 409,
          "message" => "the code of diseases 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']);
  }



  function set_upload_options($folder_name)
  {
    $config = array();
    $config['upload_path'] = "uploads/{$folder_name}";
    $config['allowed_types'] = '*';
    $config['max_size'] = '0'; // 0 = no file size limit
    $config['max_width']  = '0';
    $config['max_height']  = '0';
    $config['overwrite'] = TRUE;
    return $config;
  }

}
