<?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 reproductive_management_get()
    {
        $page = $this->get('page');
        $limit = $this->get('limit');
        $id = $this->get('id');
        if (count($this->get()) > 3) {
            $response = array(
                "status" => "error",
                "status_code" => 409,
                "message" => "Too many params was sent",
                "validations" => array(
                    "id" => "Send Id (Get) to get specific record, or empty to get all records"
                ),
                "data" => null
            );
        } else {
            if ($id) {
                $response = $this->DAO->selectEntity('vw_reproductiveManagement', array('id_reproductive' => $id), TRUE);
            } else {
                $response = $this->DAO->getReproductionRecords($page, $limit);
            }
        }
        $this->response($response, $response['status_code']);
    }

    function reproductive_managementFemales_get()
    {
        $id = $this->get('id');
        $idEdit = $this->get('idEdit');
        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 record, or empty to get all records"
                ),
                "data" => null
            );
        } else {

            if ($idEdit) {
                $response = $this->DAO->selectEntity('reproductive_females', array('id_reproductiveF' => $idEdit), true);
            } else if ($id) {
                $response = $this->DAO->selectEntity('reproductive_females', array('id_reporductiveManagement' => $id, 'status' => '1'), false);
            } else {
                $response = $this->DAO->selectEntity('reproductive_females', array('status' => '1'));
            }
        }
        $this->response($response, $response['status_code']);
    }





    function reproductive_management_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(
                    "female_sheep" => "Required field, previously registered",
                    "stud_sheep" => "Required field, previously registered",
                    "start_date" => "Required field",
                    "end_date" => "Required field",
                    "observations" => "Optional field"
                )
            );
        } else {
            $this->form_validation->set_data($data);
            $this->form_validation->set_rules('female_sheep', 'female_sheep', 'required|callback_animal_exists');
            $this->form_validation->set_rules('stud_sheep', 'stud_sheep', 'required|callback_animal_exists');
            $this->form_validation->set_rules('start_date', 'start_date', 'required');
            $this->form_validation->set_rules('end_date', 'end_date', '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');
                $stud_sheep = $this->DAO->selectEntity('animals', array('id_animals' => $data['stud_sheep']), TRUE)['data'];
                $female_sheep = $this->DAO->selectEntity('animals', array('id_animals' => $data['female_sheep']), TRUE)['data'];
                $reproductiveManagement = array(
                    'start_date' => $data['start_date'],
                    'end_date' => $data['end_date'],
                    'earring_female' => $female_sheep->earring,
                    'female_sheep' => $data['female_sheep'],
                    'stud_earring' => $stud_sheep->earring,
                    'stud_sheep' => $data['stud_sheep'],
                    'observations' => $data['observations'],
                    'created_date' => $currentDate,
                    'updated_date' => $currentDate
                );

                $dataResponse = $this->DAO->saveOrUpdateItem('reproductive_management', $reproductiveManagement, 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, $response['status_code']);
    }


    function reproductive_excel_post()
    {
        $data = $this->post();
        $datareproductive = [];

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

        $management_reproductive = array(
            "date_reproductive" => $data['reproductive_management']['date_reproductive'],
            "rodeo_id" => $data['reproductive_management']['rodeo_id'],
            "lot_reproductive" => $data['reproductive_management']['lot_reproductive'],
            "earring_stallion" => $data['reproductive_management']['earring_stallion'],
            "fenotipo" => $data['reproductive_management']['fenotipoSemental'],
            "date_start" => $data['reproductive_management']['date_start'],
            "date_end" => $data['reproductive_management']['date_end'],
            "dateDx" => $data['reproductive_management']['dateDx'],
            "Fertility" => $data['reproductive_management']['Fertility'],
            "created_date" => $currentDate,
            "updated_date" => $currentDate
        );
        $managementResponse = $this->DAO->saveOrUpdateItem('reproductive_management1', $management_reproductive, null, true);
        if ($managementResponse['key']) {
            $id_management = $managementResponse['key'];
            foreach ($data['reproductive_females'] as $row) {
                date_default_timezone_set('America/Mexico_City');
                $currentDate = date('Y-m-d H:i:s');
                $datareproductive[] = array(
                    'id_reporductiveManagement' => $id_management,
                    "earring_female" => ($row['earring_female']) ? $row['earring_female'] : '',
                    "fenotipo" => ($row['fenotipo']) ? $row['fenotipo'] : '',
                    "number_empadre" => ($row['number_empadre']) ? $row['number_empadre'] : '',
                    "result_dx" => ($row['result_dx']) ? $row['result_dx'] : '',
                    "comment" => ($row['comment']) ? $row['comment'] : '',
                    "created_date" => $currentDate,
                    "updated_date" => $currentDate
                );
            }
            $response = $this->DAO->saveOrUpdateBatchItems('reproductive_females', $datareproductive);
        } else {
            $response = array(
                "status" => "error",
                "status_code" => 409,
                "message" =>  $managementResponse['message'],
                "data" => null,
            );
        }
        $this->response($managementResponse, $managementResponse['status_code']);
    }

    function reproductive21_post()
    {

        $data = $this->post();
        if (count($data) == 0 || count($data) > 20) {
            $response = array(
                "status" => "error",
                "status_code" => 409,
                "message" => count($data) == 0 ? 'No se recibieron datos' : 'Se recibieron demasiados datos',
                "data" => count($data),
                "validations" => array(
                    "date_reproductive" => "Campo requerido.",
                    "rodeo_id" => "Campo requerido.",
                    "earring_stallion" => "Campo requerido."
                )
            );
        } else {
            $this->form_validation->set_data($data);
            $this->form_validation->set_rules('date_reproductive', 'date_reproductive', 'required');
            $this->form_validation->set_rules('rodeo_id', 'rodeo_id', 'required');
            $this->form_validation->set_rules('earring_stallion', 'earring_stallion', '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');

                $diet = array(
                    "date_reproductive" => $this->post('date_reproductive'),
                    "rodeo_id" => $this->post('rodeo_id'),
                    "lot_reproductive" => $this->post('lot_reproductive'),
                    "earring_stallion" => $this->post('earring_stallion'),
                    "fenotipo" => $this->post('fenotipoSemental'),
                    "date_start" => $this->post('date_start'),
                    "date_end" => $this->post('date_end'),
                    "dateDx" => $this->post('dateDx'),
                    "Fertility" => $this->post('Fertility'),
                    "created_date" => $currentDate,
                    "updated_date" => $currentDate
                );
                $managementResponse = $this->DAO->saveOrUpdateItem('reproductive_management1', $diet, null, true);
                if ($managementResponse['key']) {
                    $id_management = $managementResponse['key'];
                    foreach ($data['earring_female'] as $i => $val) {
                        $dataFemales = array(
                            'id_reporductiveManagement' => $id_management,
                            'earring_female' => $data['earring_female'][$i],
                            "fenotipo" => $data['fenotipo'][$i],
                            "number_empadre" => $data['number_empadre'][$i],
                            "result_dx" => $data['result_dx'][$i],
                            "comment" => $data['comment'][$i],
                            'created_date' => $currentDate,
                            'updated_date' => $currentDate
                        );
                        $pvResponse = $this->DAO->saveOrUpdateItem('reproductive_females', $dataFemales, null, true);
                    }

                    if ($pvResponse['status'] == 'success') {
                        $response = array(
                            "status" => "success",
                            "status_code" => 200,
                            "message" =>  "Registro creado exitosamente",
                            "data" => $data,
                        );
                    } else {
                        $response = array(
                            "status" => "error",
                            "status_code" => 409,
                            "message" => "No registrado",
                            "data" => null,
                        );
                    }
                } else {
                    $response = array(
                        "status" => "error",
                        "status_code" => 409,
                        "message" => "No registrado",
                        "data" => null,
                    );
                }
            }
            $this->response($response, $response['status_code']);
        }
    }



    function reproductive21_put()
    {
        $id = $this->get('id');
        if ($id) {
            $dataExists = $this->DAO->selectEntity('reproductive_management1', array('id_reproductive' => $id), TRUE);
            if ($dataExists) {
                if (count($this->put()) > 12) {
                    $response = array(
                        "status" => "error",
                        "status_code" => 409,
                        "message" => "Too many data was sent",
                        "validations" => array(
                            "date_reproductive" => "required and unique",
                            "rodeo_id" => "required and unique",
                            "earring_stallion" => "required and unique",
                            "fenotipo" => "required and unique",
                            "date_start" => "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(
                            "date_reproductive" => "required and unique",
                            "rodeo_id" => "required and unique",
                            "earring_stallion" => "required and unique",
                            "fenotipoSemental" => "required and unique",
                            "date_start" => "required and unique",
                        ),
                        "data" => null
                    );
                } else {
                    $this->form_validation->set_data($this->put());
                    $this->form_validation->set_rules('date_reproductive', 'date_reproductive', 'required');
                    $this->form_validation->set_rules('rodeo_id', 'rodeo_id', 'required');

                    $this->form_validation->set_rules('earring_stallion', 'earring_stallion', 'required');
                    $this->form_validation->set_rules('fenotipoSemental', 'fenotipoSemental', 'required');
                    $this->form_validation->set_rules('date_start', 'date_start', '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(
                            "date_reproductive" => $this->put('date_reproductive'),
                            "rodeo_id" => $this->put('rodeo_id'),
                            "lot_reproductive" => $this->put('lot_reproductive'),
                            "earring_stallion" => $this->put('earring_stallion'),
                            "fenotipo" => $this->put('fenotipoSemental'),
                            "date_start" => $this->put('date_start'),
                            "date_end" => $this->put('date_end'),
                            "dateDx" => $this->put('dateDx'),
                            "Fertility" => $this->put('Fertility'),
                            "updated_user" => $this->put('created_user'),
                            "updated_date" => $currentDate,
                        );

                        $response = $this->DAO->saveOrUpdateItem('reproductive_management1', $data, array('id_reproductive' => $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 reproductiveFemales_put()
    {
        $id = $this->get('id');
        if ($id) {
            $dataExists = $this->DAO->selectEntity('reproductive_females', array('id_reproductiveF' => $id), TRUE);
            if ($dataExists) {
                if (count($this->put()) > 12) {
                    $response = array(
                        "status" => "error",
                        "status_code" => 409,
                        "message" => "Too many data was sent",
                        "validations" => array(

                            "earring_female1" => "Required field, previously registered",
                            "fenotipo" => "Required field",
                            "number_empadre" => "Required field",

                        ),
                        "data" => null
                    );
                } else if (count($this->put()) == 0) {
                    $response = array(
                        "status" => "error",
                        "status_code" => 409,
                        "message" => "No data was sent",
                        "validations" => array(

                            "earring_female1" => "Required field",
                            "fenotipo1" => "Required field",
                            "number_empadre1" => "Required field",

                        ),
                        "data" => null
                    );
                } else {
                    $this->form_validation->set_data($this->put());

                    $this->form_validation->set_rules('earring_female1', 'earring_female1', 'required');
                    $this->form_validation->set_rules('fenotipo1', 'fenotipo1', 'required');
                    $this->form_validation->set_rules('number_empadre1', 'number_empadre1', '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(

                            "earring_female" => $this->put('earring_female1'),
                            "fenotipo" => $this->put('fenotipo1'),
                            "number_empadre" => $this->put('number_empadre1'),
                            "result_dx" => $this->put('result_dx1'),
                            "comment" => $this->put('comment1'),
                            "updated_user" => $this->put('created_user'),
                            "updated_date" => $currentDate,
                        );

                        $response = $this->DAO->saveOrUpdateItem('reproductive_females', $data, array('id_reproductiveF' => $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 v()
    {
        $id = $this->get('id');
        $data = $this->put();
        if ($id) {
            $dataExists = $this->DAO->selectEntity('reproductive_females', array('id_reproductiveF' => $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(
                            "id_reporductiveManagement" => "Required field, previously registered",
                            "earring_female" => "Required field, previously registered",
                            "fenotipo" => "Required field",
                            "number_empadre" => "Required field",
                            "result_dx" => "Optional field",
                            "comment" => "Required field",
                        )
                    );
                } else {

                    $this->form_validation->set_data($data);
                    $this->form_validation->set_rules('id_reporductiveManagement', 'id_reporductiveManagement', 'required');
                    $this->form_validation->set_rules('earring_female', 'earring_female', 'required');
                    $this->form_validation->set_rules('fenotipo', 'fenotipo', 'required');
                    $this->form_validation->set_rules('number_empadre', 'number_empadre', 'required');
                    $this->form_validation->set_rules('result_dx', 'result_dx', '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');

                        $reproductiveManagement = array(
                            "id_reporductiveManagement" => $this->put('id_reporductiveManagement'),
                            "earring_female" => $this->put('earring_female'),
                            "fenotipo" => $this->put('fenotipo'),
                            "number_empadre" => $this->put('number_empadre'),
                            "result_dx" => $this->put('result_dx'),
                            "comment" => $this->put('comment'),
                            "updated_user" => $this->put('created_user'),
                            "updated_date" => $currentDate,
                        );
                        $response = $this->DAO->saveOrUpdateItem('reproductive_females', $reproductiveManagement, array('id_reproductiveF' => $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 reproductive_management_delete()
    {
        $id = $this->get('id');
        if ($id) {
            $dataExists = $this->DAO->selectEntity('reproductive_management1', array('id_reproductive' => $id), TRUE);
            if ($dataExists['data']) {
                date_default_timezone_set('America/Mexico_City');
                $currentDate = date('Y-m-d H:i:s');
                $reproductive_management = array(
                    'status' => 0,
                    'updated_date' => $currentDate
                );
                $response = $this->DAO->updateData('reproductive_management1', $reproductive_management, array('id_reproductive' => $id));
            } else {
                $response = array(
                    "status" => "error",
                    "status_code" => 409,
                    "message" => "the code of the reproductive record 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 dataFemales_delete()
    {
        $id = $this->get('id');
        if ($id) {
            $dataExists = $this->DAO->selectEntity('reproductive_females', array('id_reproductiveF' => $id), TRUE);
            if ($dataExists['data']) {
                date_default_timezone_set('America/Mexico_City');
                $currentDate = date('Y-m-d H:i:s');
                $reproductive_management = array(
                    'status' => 0,
                    'updated_date' => $currentDate
                );
                $response = $this->DAO->updateData('reproductive_females', $reproductive_management, array('id_reproductiveF' => $id));
            } else {
                $response = array(
                    "status" => "error",
                    "status_code" => 409,
                    "message" => "the code of the reproductive record 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;
            }
        }
    }
}
