<?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 weanings_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 weaning, or empty to get all weanings"
                ),
                "data" => null
            );
        } else {
            if ($id) {
                $response = $this->DAO->selectEntity('weaning', array('id_weaning' => $id), TRUE);
            } else {
                $response = $this->DAO->selectEntity('weaning', array('status' => '1'));
            }
        }
        $this->response($response, $response['status_code']);
    }

    function weaningsForReport_get()
    {
        $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 ($desde) {
                $response = $this->DAO->weaningsForReport($desde, $hasta);
            } else {
                $response = $this->DAO->weaningsForReport();
            }
        }
        $this->response($response, $response['status_code']);
    }

    function weaningCount_get()
    {
        $id = $this->get('rodeo');

        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->weaningCount($id);
            } else {
                $response = $this->DAO->weaningCount();
            }
        }
        $this->response($response, $response['status_code']);
    }


    function weanings_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(
                    /* "animal" => "Required field, previously registered", */
                    "date" => "Required field",
                    "weaning_weight" => "Required field",
                    "weaning_age" => "Required field",
                    // "gdp" => "Required field",
                    "comment" => "Optional field"
                )
            );
        } else {
            $this->form_validation->set_data($data);
            $this->form_validation->set_rules('date', 'date', 'required');
            $this->form_validation->set_rules('weaning_weight', 'weaning_weight', 'required');
            $this->form_validation->set_rules('weaning_age', 'weaning_age', 'required');
            // $this->form_validation->set_rules('gdp', 'gdp', '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');
                /* $animal = $this->DAO->selectEntity('animals', array('id_animals' => $data['animal']), TRUE)['data']; */

                $weaning = array(
                    'earring' => 'OVI' . $data['earring'],
                    /* 'animal_id' => $data['animal'], */
                    'date' => $data['date'],
                    'weaning_weight' => $data['weaning_weight'],
                    'weaning_age' => $data['weaning_age'],
                    // 'gdp' => $data['gdp'],
                    "created_user" => $data['created_user'],
                    'comments' => $data['comment'],
                    'created_date' => $currentDate,
                    'updated_date' => $currentDate
                );

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


    function weanings_put()
    {
        $id = $this->get('id');
        $data = $this->put();
        if ($id) {
            $dataExists = $this->DAO->selectEntity('weaning', array('id_weaning' => $id), TRUE);
            if ($dataExists['data']) {
                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(
                            "animal" => "Required field, previously registered",
                            "date" => "Required field",
                            "weaning_weight" => "Required field",
                            "weaning_age" => "Required field",
                            "gdp" => "Required field",
                            "comment" => "Optional field"
                        )
                    );
                } else {

                    $this->form_validation->set_data($data);
                    // $this->form_validation->set_rules('animal', 'animal', 'required|callback_animal_exists');
                    $this->form_validation->set_rules('date', 'date', 'required');
                    $this->form_validation->set_rules('weaning_weight', 'weaning_weight', 'required');
                    $this->form_validation->set_rules('weaning_age', 'weaning_age', 'required');
                    // $this->form_validation->set_rules('gdp', 'gdp', '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');
                        // $animal = $this->DAO->selectEntity('animals', array('id_animals' => $data['animal']), TRUE)['data'];

                        $weaning = array(
                            'earring' => $data['earring'],
                            // 'animal_id' => $data['animal'],
                            'date' => $data['date'],
                            'weaning_weight' => $data['weaning_weight'],
                            'weaning_age' => $data['weaning_age'],
                            "updated_user" => $data['created_user'],
                            // 'gdp' => $data['gdp'],
                            'comments' => $data['comment'],
                            'updated_date' => $currentDate
                        );
                        $response = $this->DAO->saveOrUpdateItem('weaning', $weaning, array('id_weaning' => $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 weanings_delete()
    {
        $id = $this->get('id');
        if ($id) {
            $dataExists = $this->DAO->selectEntity('weaning', array('id_weaning' => $id), TRUE);
            if ($dataExists['data']) {
                date_default_timezone_set('America/Mexico_City');
                $currentDate = date('Y-m-d H:i:s');
                $treatment = array(
                    'status' => 0,
                    'updated_date' => $currentDate
                );
                $response = $this->DAO->updateData('weaning', $treatment, array('id_weaning' => $id));
            } else {
                $response = array(
                    "status" => "error",
                    "status_code" => 409,
                    "message" => "the code of the weaning 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 animal_exists($str)
    {
        if (strlen($str) >= 1  && strlen($str) <= 45) {
            $animalExists = $this->DAO->selectEntity('animals', array('id_animals' => $str), TRUE);
            if ($animalExists['data']) {
                return TRUE;
            } else {
                $this->form_validation->set_message('animal_exists', 'The field {field} does not exists');
                return FALSE;
            }
        }
    }
}
