<?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 vaccination_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('vaccination', array('id_vaccination' => $id), TRUE);
      } else if ($idAnimal) {
        $response = $this->DAO->selectEntity('vaccination', array('id_animal' => $idAnimal,'status' => 1), false);
      } else{
        $response = $this->DAO->selectEntity('vw_vaccination', array('status' => 1), false);
      }
    }
    $this->response($response, $response['status_code']);
  }


  function vaccinationDoc_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_vaccination', array('id_vaccination' => $id, 'status' => 1), FALSE);
      } else {
        $response = $this->DAO->selectEntity('doc_vaccination', array('status' => 1), false);
      }
    }
    $this->response($response, $response['status_code']);
  }
  function vaccination_post()
  {
    $folder_name = "vaccination";
    $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(
          "id_animal" => "required and unique",
          "date_vaccination" => "required and unique",
          "vaccine" => "required and unique",
         
        )
      );
    } else {
      $this->form_validation->set_data($data);
      $this->form_validation->set_rules('id_animal', 'id_animal', 'required');
      $this->form_validation->set_rules('date_vaccination', 'date_vaccination', 'required');
      $this->form_validation->set_rules('vaccine', 'vaccine', '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');
        $vaccination = array(
          "id_animal" => $this->post('id_animal'),
          "date_vaccination" => $this->post('date_vaccination'),
          "vaccine" => $this->post('vaccine'),
          "revaccination" => $this->post('revaccination'),
          "comments" => $this->post('comments'),
          "created_user" => $this->post('created_user'),
          "created_date"=>$currentDate,

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

  function vaccination_put()
  {
    $id = $this->get('id');
    if ($id) {
      $dataExists = $this->DAO->selectEntity('vaccination', array('id_vaccination' => $id), TRUE);
      if ($dataExists) {
        if (count($this->put()) > 12) {
          $response = array(
            "status" => "error",
            "status_code" => 409,
            "message" => "Too many data was sent",
            "validations" => array(
              // "id_animal" => "required and unique",
              "date_vaccination" => "required and unique",
              "vaccine" => "required and unique",
              "revaccination" => "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(
              // "id_animal" => "required and unique",
              "date_vaccination" => "required and unique",
              "vaccine" => "required and unique",
              
              
            ),
            "data" => null
          );
        } else {
          $this->form_validation->set_data($this->put());
          // $this->form_validation->set_rules('id_animal', 'id_animal', 'required');
          $this->form_validation->set_rules('date_vaccination', 'date_vaccination', 'required');
          $this->form_validation->set_rules('vaccine', 'vaccine', '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(
              "id_animal" => $this->put('id_animal'),
              "date_vaccination" => $this->put('date_vaccination'),
              "vaccine" => $this->put('vaccine'),
              "revaccination" => $this->put('revaccination'),
              "comments" => $this->put('comments'),
              "updated_date" => $currentDate,
              "updated_user" => $this->put('updated_user'),
              
            );

            $response = $this->DAO->saveOrUpdateItem('vaccination', $data, array('id_vaccination' => $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 vaccination_delete()
  {
    $id = $this->get('id');
    if ($id) {
      $dataExists = $this->DAO->selectEntity('vaccination', array('id_vaccination' => $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('vaccination', $births, array('id_vaccination' => $id));
      } else {
        $response = array(
          "status" => "error",
          "status_code" => 409,
          "message" => "the code of vaccination 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 vaccinationDoc_delete()
  {
    $id = $this->get('id');
    if ($id) {
      $dataExists = $this->DAO->selectEntity('doc_vaccination', 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_vaccination', $births, array('id_document' => $id));
      } else {
        $response = array(
          "status" => "error",
          "status_code" => 409,
          "message" => "the code of vaccination 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;
  }

}
