<?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 animals_get()
  {
    $id = $this->get('id');
    if (count($this->get()) > 1) {
      $response = array(
        "status" => "error",
        "status_code" => 409,
        "message" => "Demasiados parametros fueron enviados",
        "validations" => array(
          "id" => "Enviar id para obtener información de un animal, o vacion para obtener todos los animales"
        ),
        "data" => null
      );
    } else {
      if ($id) {
        $response = $this->DAO->selectEntity('animals', array('id_animals' => $id), TRUE);
      } else {
        $response = $this->DAO->selectEntity('vw_animals', array('status' => 1));
      }
    }
    $this->response($response, $response['status_code']);
  }

  function animalesCount_get()
  {
    $id = $this->get('specie');

    if (count($this->get()) > 4) {
      $response = array(
        "status" => "error",
        "status_code" => 409,
        "message" => "Too many params was sent",
        "validations" => array(
          "specie" => "Send Id (Get) to get specific insemination, or empty to get all inseminations"
        ),
        "data" => null
      );
    } else {
      if ($id) {
        $response = $this->DAO->animalsCount($id);
      } else {
        $response = $this->DAO->animalsCount();
      }
    }
    $this->response($response, $response['status_code']);
  }


  function animalsCaninos_get()
  {
    $id = $this->get('id');
    if (count($this->get()) > 1) {
      $response = array(
        "status" => "error",
        "status_code" => 409,
        "message" => "Demasiados parametros fueron enviados",
        "validations" => array(
          "id" => "Enviar id para obtener información de un animal, o vacion para obtener todos los animales"
        ),
        "data" => null
      );
    } else {
      if ($id) {
        $response = $this->DAO->selectEntity('animals', array('id_animals' => $id), TRUE);
      } else {
        $response = $this->DAO->selectEntity('vw_animals', array('status' => 1, 'specie'=> "Caninos"));
      }
    }
    $this->response($response, $response['status_code']);
  }


  function OvinosCount_get()
  {
    $id = $this->get('specie');

    if (count($this->get()) > 4) {
      $response = array(
        "status" => "error",
        "status_code" => 409,
        "message" => "Too many params was sent",
        "validations" => array(
          "specie" => "Send Id (Get) to get specific insemination, or empty to get all inseminations"
        ),
        "data" => null
      );
    } else {
      if ($id) {
        $response = $this->DAO->ovinosCount($id);
      } else {
        $response = $this->DAO->ovinosCount();
      }
    }
    $this->response($response, $response['status_code']);
  }

  function avesCount_get()
  {
    $id = $this->get('specie');

    if (count($this->get()) > 4) {
      $response = array(
        "status" => "error",
        "status_code" => 409,
        "message" => "Too many params was sent",
        "validations" => array(
          "specie" => "Send Id (Get) to get specific insemination, or empty to get all inseminations"
        ),
        "data" => null
      );
    } else {
      if ($id) {
        $response = $this->DAO->avesCount($id);
      } else {
        $response = $this->DAO->avesCount();
      }
    }
    $this->response($response, $response['status_code']);
  }


  function animForReport_get()
  {
    $specie = $this->get('specie');
    // $desde = $this->get('desde');
    // $hasta = $this->get('hasta');
    if (count($this->get()) > 4) {
      $response = array(
        "status" => "error",
        "status_code" => 409,
        "message" => "Too many params was sent",
        "validations" => array(
          "specie" => "Send Id (Get) to get specific insemination, or empty to get all inseminations"
        ),
        "data" => null
      );
    } else {
      if ($specie) {
        $response = $this->DAO->animForReport($specie);
      } else {
        $response = $this->DAO->animForReport();
      }
    }
    $this->response($response, $response['status_code']);
  }


  function inactive_animals_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 an inactive animal, or empty to get all inactives animals"
        ),
        "data" => null
      );
    } else {
      if ($id) {
        $response = $this->DAO->selectEntity('vw_animals', array('id_animals' => $id), TRUE);
      } else {
        $response = $this->DAO->selectEntity('vw_animals', array('status' => 0));
      }
    }
    $this->response($response, $response['status_code']);
  }


  function animalsByEarring_get()
  {
    $id = $this->get('earring');
    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('vw_animals', array('earring' => $id, 'status' => 1), TRUE);
      } else {
        $response = $this->DAO->selectEntity('vw_animals');
      }
    }
    $this->response($response, $response['status_code']);
  }

  function animals_post()
  {
    $data = $this->post();
    if (count($data) == 0 || count($data) > 19) {
      $response = array(
        "status" => "error",
        "status_code" => 409,
        "message" => count($data) == 0 ? 'No se enviaron datos' : 'Demasiados datos fueron enviados',
        "data" => count($data),
        "validations" => array(
          "name" => "Campo opcional.",
          "specie" => "Campo requerido.",
          "race" => "Campo requerido.",
          "gender" => "Campo requerido.",
          "birth_date" => "Campo requerido.",
          "birth_weight" => "Campo opcional.",
          "earring" => "Campo requerido para ovinos y unico.",
          "grapa" => "Campo requerido para ovinos y unico.",
          "mother_earring" => "Campo requerido para ovinos.",
          "father_earring" => "Campo requerido para ovinos.",
          "id_rodeo" => "Campo requerido para ovinos y aves.",
          "comments" => "Campo opcional.",
          "category" => "Campo requerido para ovinos.",
        )
      );
    } else {
      $this->form_validation->set_data($data);
      $this->form_validation->set_rules('specie', 'specie', 'required|callback_valid_specie');
      $this->form_validation->set_rules('race', 'race', 'required');
      $this->form_validation->set_rules('gender', 'gender', 'required|callback_valid_gender');
      $this->form_validation->set_rules('birth_date', 'birth_date', 'required');
      $this->form_validation->set_rules('earring', 'earring', 'is_unique[animals.earring]');
      $this->form_validation->set_rules('id_rodeo', 'id_rodeo', 'callback_rodeo_exists');
      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 {

        $file = strtoupper(substr($this->post('specie'), 0, 3)) .  random_string('alnum', 3);
        $config['upload_path'] = 'uploads/animals-img';
        $config['allowed_types'] = '*';
        $config['max_size'] = '0';
        $config['overwrite'] = TRUE;
        $config['file_name'] = $file;

        $this->load->library('upload', $config);
        if ($this->upload->do_upload("imagenA")) {
          $doc_data = array('upload_data' => $this->upload->data());
          $imagen = $doc_data['upload_data']['file_name'];
        } else {
          $imagen = '1';
        }


        $file = 'REG' . time();
        $config2['upload_path'] = 'uploads/doc_reg';
        $config2['allowed_types'] = '*';
        $config2['max_size'] = '0';
        $config2['overwrite'] = TRUE;
        $config2['file_name'] = $file;
        /* $this->load->library('upload', $config); */
        $this->upload->initialize($config2);
        if ($this->upload->do_upload("doc_reg")) {
          $doc_data = array('upload_data' => $this->upload->data());
          $image_registro = $doc_data['upload_data']['file_name'];
        } else {
          $image_registro = '1';
        }

        $earr = $this->post('earring');

        if ($earr) {
          $earring1 = strtoupper(substr($this->post('specie'), 0, 3)) . $this->post('earring');
        } else {
          if ($this->post('grapa')) {
            $earring1 = strtoupper(substr($this->post('specie'), 0, 3)) . $this->post('grapa');
          } else {
            $earring1 = strtoupper(substr($this->post('specie'), 0, 3) . random_string('alnum', 3));
          }
        }

        $currentDate = date('Y-m-d H:i:s');
        date_default_timezone_set('America/Mexico_City');
        $animal = array(

          "name" => $this->post('name'),
          "specie" => $this->post('specie'),
          "race" => $this->post('race'),
          "gender" => $this->post('gender'),
          "birth_date" => $this->post('birth_date'),
          "birth_weight" => $this->post('birth_weight'),
          "earring" => $earring1,
          "mother_earring" => $this->post('mother_earring'),
          "father_earring" => $this->post('father_earring'),
          "id_rodeo" => $this->post('id_rodeo'),
          "code_registro" => $this->post('code_registro'),
          "doc_registro" => $image_registro,
          "category_id" => $this->post('category'),
          "created_user" => $this->post('created_user'),
          "comments" => $this->post('comments'),
          "image_animals" => $imagen,
          "create_date" => $currentDate,
          "update_date" => $currentDate
        );
        $dataResponse = $this->DAO->saveOrUpdateItem('animals', $animal, null, true);
        if ($dataResponse['status'] == "success") {
          $response = array(
            "status" => "success",
            "status_code" => 200,
            "message" =>  "Animal registrado con exito.",
            "data" => null,
          );
        } else {
          $response = array(
            "status" => "error",
            "status_code" => 409,
            "message" =>  $dataResponse['message'],
            "data" => null,
          );
        }
      }
    }
    $this->response($response, $response['status_code']);
  }
  function animals_excel_post()
  {
    $data = $this->post();
    $dataAnimal = [];
    foreach ($data as $row) {
      $earring = substr($row['specie'], 0, 3) . $row['earring'];
      $grapa = substr($row['specie'], 0, 3)  . $row['grapa'];
      $existsAnimalByEarring = $this->DAO->selectEntity('animals', array('earring' => $earring));
      $existsAnimalByGrapa = $this->DAO->selectEntity('animals', array('earring' => $grapa));
      if (!$existsAnimalByEarring['data'] && !$existsAnimalByGrapa['data']) {
        date_default_timezone_set('America/Mexico_City');
        $currentDate = date('Y-m-d H:i:s');
        if ($row['earring']) {
          $earring1 = strtoupper(substr($row['specie'], 0, 3)) . $row['earring'];
        } else {
          if ($row['grapa']) {
            $earring1 = strtoupper(substr($row['specie'], 0, 3))  . $row['grapa'];
          } else {
            $earring1 = strtoupper(substr($row['specie'], 0, 3) . random_string('alnum', 3));
          }
        }
        $dataAnimal[] = array(
          "specie" => ($row['specie']) ? $row['specie'] : '',
          "race" => ($row['race']) ? $row['race'] : '',
          "gender" => ($row['gender']) ? $row['gender'] : '',
          "birth_date" => ($row['birth_date']) ? $row['birth_date'] : '',
          "birth_weight" => ($row['birth_weight']) ? $row['birth_weight'] : '',
          "earring" => $earring1,
          "mother_earring" => ($row['mother_earring']) ? $row['mother_earring'] : '',
          "father_earring" => ($row['father_earring']) ? $row['father_earring'] : '',
          "id_rodeo" => ($row['id_rodeo']) ? $row['id_rodeo'] : '',
          "category_id" => ($row['category']) ? $row['category'] : '',
          "comments" => ($row['comments']) ? $row['comments'] : '',
          "create_date" => $currentDate,
          "update_date" => $currentDate,
          "created_user" => $row['created_user'],
        );
      }
    }
    $dataResponse = $this->DAO->saveOrUpdateBatchItems('animals', $dataAnimal);
    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, $response['status_code']);
  }

  function animals_edit_post()
  {
    $id = $this->get('id');
    if ($id) {
      $dataExists = $this->DAO->selectEntity('animals', array('id_animals' => $id), TRUE);
      if ($dataExists) {
        if (count($this->post()) > 15) {
          $response = array(
            "status" => "error",
            "status_code" => 409,
            "message" => "Too many data was sent",
            "validations" => array(
              "name" => "Campo opcional.",
              "race" => "Campo requerido.",
              "gender" => "Campo requerido.",
              "birth_date" => "Campo requerido.",
              "birth_weight" => "Campo opcional.",
              "earring" => "Campo requerido para ovinos y unico.",
              "grapa" => "Campo requerido para ovinos y unico.",
              "mother_earring" => "Campo requerido para ovinos.",
              "father_earring" => "Campo requerido para ovinos.",
              "id_rodeo" => "Campo requerido para ovinos y aves.",
              "comments" => "Campo opcional.",
              "category" => "Campo requerido para ovinos.",
            ),
            "data" => null
          );
        } else if (count($this->post()) == 0) {
          $response = array(
            "status" => "error",
            "status_code" => 409,
            "message" => "No data was sent",
            "validations" => array(
              "name" => "Campo opcional.",
              "race" => "Campo requerido.",
              "gender" => "Campo requerido.",
              "birth_date" => "Campo requerido.",
              "birth_weight" => "Campo opcional.",
              "earring" => "Campo requerido para ovinos y unico.",
              "grapa" => "Campo requerido para ovinos y unico.",
              "mother_earring" => "Campo requerido para ovinos.",
              "father_earring" => "Campo requerido para ovinos.",
              "id_rodeo" => "Campo requerido para ovinos y aves.",
              "comments" => "Campo opcional.",
              "category" => "Campo requerido para ovinos.",
            ),
            "data" => null
          );
        } else {

          $this->form_validation->set_data($this->post());
          $this->form_validation->set_rules('race', 'race', 'required');
          $this->form_validation->set_rules('gender', 'gender', 'required|callback_valid_gender');
          $this->form_validation->set_rules('birth_date', 'birth_date', '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 {
            $img = $dataExists['data']->image_animals;
            date_default_timezone_set('America/Mexico_City');
            $currentDate = date('Y-m-d H:i:s');
            $earr = $this->post('earring');
            if ($earr) {
              $earring1 = strtoupper(substr($this->post('specie'), 0, 3)) . $this->post('earring');
            } else {
              if ($this->post('grapa')) {
                $earring1 = strtoupper(substr($this->post('specie'), 0, 3)) . $this->post('grapa');
              } else {
                $earring1 = strtoupper(substr($this->post('specie'), 0, 3) . random_string('alnum', 3));
              }
            }
            $file = $earring1;
            $config['upload_path'] = 'uploads/animals-img';
            $config['allowed_types'] = '*';
            $config['max_size'] = '0';
            $config['overwrite'] = TRUE;
            $config['file_name'] = $file;

            $this->load->library('upload', $config);
            if ($this->upload->do_upload("imagenA")) {
              $doc_data = array('upload_data' => $this->upload->data());
              $imagen = $doc_data['upload_data']['file_name'];
            } else {
              if ($img) {
                $imagen = $img;
              } else {
                $imagen = 1;
              }
            }
            $doc_registro = $dataExists['data']->doc_registro;
            $file = 'REG' . time();
            $config2['upload_path'] = 'uploads/doc_reg';
            $config2['allowed_types'] = '*';
            $config2['max_size'] = '0';
            $config2['overwrite'] = TRUE;
            $config2['file_name'] = $file;
            /* $this->load->library('upload', $config); */
            $this->upload->initialize($config2);
            if ($this->upload->do_upload("doc_reg")) {
              $doc_data = array('upload_data' => $this->upload->data());
              $image_registro = $doc_data['upload_data']['file_name'];
            } else {
              if ($doc_registro) {
                $image_registro = $doc_registro;
              } else {
                $image_registro = '1';
              }
            }
            $animal = array(
              "name" => $this->post('name'),
              "race" => $this->post('race'),
              "gender" => $this->post('gender'),
              "birth_date" => $this->post('birth_date'),
              "birth_weight" => $this->post('birth_weight'),
              "earring" => $earring1,
              "updated_user" => $this->post('created_user'),
              "mother_earring" => $this->post('mother_earring'),
              "father_earring" => $this->post('father_earring'),
              "id_rodeo" => $this->post('id_rodeo'),
              "category_id" => $this->post('category'),
              "code_registro" => $this->post('code_registro'),
              "comments" => $this->post('comments'),
              "doc_registro" => $image_registro,
              "image_animals" => $imagen,
              "update_date" => $currentDate
            );
            $response = $this->DAO->saveOrUpdateItem('animals', $animal, array('id_animals' => $id));
          }
        }
      }
    } else {

      $response = array(
        "status" => "error",
        "status_code" => 409,
        "message" => "Demasiados datos enviados.",
        "validations" => array(
          "id" => "Required",

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

  function animals_delete()
  {
    $id = $this->get('id');
    if ($id) {
      $dataExists = $this->DAO->selectEntity('animals', array('id_animals' => $id), TRUE);
      if ($dataExists['data']) {
        date_default_timezone_set('America/Mexico_City');
        $currentDate = date('Y-m-d H:i:s');
        $births = array(
          'status' => 0,
          'update_date' => $currentDate
        );
        $response = $this->DAO->updateData('animals', $births, array('id_animals' => $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']);
  }

  function activate_animals_put()
  {
    $id = $this->get('id');
    if ($id) {
      $dataExists = $this->DAO->selectEntity('animals', array('id_animals' => $id), TRUE);
      if ($dataExists['data']) {
        date_default_timezone_set('America/Mexico_City');
        $currentDate = date('Y-m-d H:i:s');
        $animals = array(
          'status' => 1,
          'update_date' => $currentDate
        );
        $animalResponse = $this->DAO->updateData('animals', $animals, array('id_animals' => $id));
        if ($animalResponse['status'] == 'success') {
          $response = array(
            'status' => 'success',
            'status_code' => '200',
            'message' => "The animal has been activated successfully",
            'validations' => null,
            'data' => null
          );
        }
      } 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']);
  }


  function animalsDead_delete()
  {
    $id = $this->get('id');
    if ($id) {
      $dataExists = $this->DAO->selectEntity('animals', array('id_animals' => $id), TRUE);
      if ($dataExists['data']) {
        date_default_timezone_set('America/Mexico_City');
        $currentDate = date('Y-m-d H:i:s');
        $births = array(
          'status' => 2,
          'update_date' => $currentDate
        );
        $response = $this->DAO->updateData('animals', $births, array('id_animals' => $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']);
  }

  function animalWeaning_delete()
  {
    $id = $this->get('earring');
    if ($id) {
      $dataExists = $this->DAO->selectEntity('animals', array('earring' => $id), TRUE);
      if ($dataExists['data']) {
        date_default_timezone_set('America/Mexico_City');
        $currentDate = date('Y-m-d H:i:s');
        $births = array(
          'status_weaning' => 2,
        );
        $response = $this->DAO->updateData('animals', $births, array('earring' => $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']);
  }


  function category_exists($str)
  {
    if (strlen($str) >= 1  && strlen($str) <= 45) {
      $animalExists = $this->DAO->selectEntity('animal_category', array('category_id' => $str, 'status' => 1), TRUE);
      if ($animalExists['data']) {
        return TRUE;
      } else {
        $this->form_validation->set_message('category_exists', 'The field {field} does not exists');
        return FALSE;
      }
    }
  }
  function rodeo_exists($str)
  {
    if (strlen($str) >= 1  && strlen($str) <= 45) {
      $animalExists = $this->DAO->selectEntity('rodeos', array('id_rodeos' => $str, 'status' => 1), TRUE);
      if ($animalExists['data']) {
        return TRUE;
      } else {
        $this->form_validation->set_message('rodeo_exists', 'El campo {field} no existe');
        return FALSE;
      }
    }
  }


  function valid_gender($str)
  {
    if (strlen($str) >= 1  && strlen($str) <= 45) {
      if ($str == 'Macho' || $str == 'Hembra') {
        return TRUE;
      } else {
        $this->form_validation->set_message('valid_gender', 'El campo {field} es incorrecto, el genero debe ser  "Hembra" o "Macho"');
        return FALSE;
      }
    }
  }

  function valid_specie($str)
  {
    if (strlen($str) >= 1  && strlen($str) <= 45) {
      if (
        $str == 'Aves' || $str == 'Ovino' || $str == 'Bovino' || $str == 'Porcino' ||
        $str == 'Caprino' || $str == 'Felinos' || $str == 'Caninos' || $str == 'Equino'
      ) {
        return TRUE;
      } else {
        $this->form_validation->set_message('valid_specie', 'El campo {field} es incorrecto, la especie debe ser Aves o Ovino, Bovino, Porcino, Caprino, Felinos, Caninos, Equino');
        return FALSE;
      }
    }
  }
}
