<?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 births_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('vw_births', array('id_births' => $id, 'status'=>1), TRUE);
            } else {
                $query  = $this->db->query("SELECT * FROM vw_births WHERE status=1 order by date_birth DESC");
                 $response = array(
            "status" => "success",
            "status_code" => 200,
            "message" => "Data loaded, successful",
            "validations" => null,
            "data" => $query->result()
        );
            }
        }
        $this->response($response, $response['status_code']);
    }


    function birthProm_get()
    {
        $query = $this->db->query("SELECT YEAR(date_birth) AS year, specie as specie, SUM(females) as totalFemales, SUM(males) as totalMales, SUM(females+males) as totalBirth FROM vw_births WHERE status=1 AND YEAR(date_birth)= YEAR(curdate()) ");
        $response = array(
            "status" => "success",
            "status_code" => 200,
            "message" => "Data loaded, successful",
            "validations" => null,
            "data" => $query->row()
        );
        $this->response($response, $response['status_code']);
    }
    
    function animalsForbirths_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('animals', array('id_birth' => $id), false); */
                $query = $this->db->query("SELECT * FROM `animals` WHERE  (status!=0) and (id_birth = '$id')");
                $response = array(
                    "status" => "success",
                    "status_code" => 200,
                    "message" => "Data loaded, successful",
                    "validations" => null,
                    "data" => $query->result()
                );
            } else {
                $response = $this->DAO->selectEntity('animals', array('status' => 1));
            }
        }
        $this->response($response, $response['status_code']);
    }




    function birthGeneral_get()
    {
        $query = $this->db->query("SELECT YEAR(date_birth) AS year, specie as specie,
        SUM(CASE WHEN (MONTH(date_birth)=1) THEN 1 else 0 END) as birth_jan,
        SUM(CASE WHEN (MONTH(date_birth)=1) THEN females  else 0 END) as fem_jan,
        SUM(CASE WHEN (MONTH(date_birth)=1) THEN males  else 0 END) as mal_jan,

        SUM(CASE WHEN (MONTH(date_birth)=2) THEN 1 else 0 END) as birth_feb,
        SUM(CASE WHEN (MONTH(date_birth)=2) THEN females  else 0 END) as fem_feb,
        SUM(CASE WHEN (MONTH(date_birth)=2) THEN males  else 0 END) as mal_feb,

        SUM(CASE WHEN (MONTH(date_birth)=3) THEN 1 else 0 END) as birth_mar,
        SUM(CASE WHEN (MONTH(date_birth)=3) THEN females  else 0 END) as fem_mar,
        SUM(CASE WHEN (MONTH(date_birth)=3) THEN males  else 0 END) as mal_mar,

        SUM(CASE WHEN (MONTH(date_birth)=4) THEN 1 else 0 END) as birth_april,
        SUM(CASE WHEN (MONTH(date_birth)=4) THEN females  else 0 END) as fem_april,
        SUM(CASE WHEN (MONTH(date_birth)=4) THEN males  else 0 END) as mal_april,

        SUM(CASE WHEN (MONTH(date_birth)=5) THEN 1 else 0 END) as birth_may,
        SUM(CASE WHEN (MONTH(date_birth)=5) THEN females  else 0 END) as fem_may,
        SUM(CASE WHEN (MONTH(date_birth)=5) THEN males  else 0 END) as mal_may,

        SUM(CASE WHEN (MONTH(date_birth)=6) THEN 1 else 0 END) as birth_june,
        SUM(CASE WHEN (MONTH(date_birth)=6) THEN females  else 0 END) as fem_june,
        SUM(CASE WHEN (MONTH(date_birth)=6) THEN males  else 0 END) as mal_june,

        SUM(CASE WHEN (MONTH(date_birth)=7) THEN 1 else 0 END) as birth_july,
        SUM(CASE WHEN (MONTH(date_birth)=7) THEN females  else 0 END) as fem_july,
        SUM(CASE WHEN (MONTH(date_birth)=7) THEN males  else 0 END) as mal_july,

        SUM(CASE WHEN (MONTH(date_birth)=8) THEN 1 else 0 END) as birth_aug,
        SUM(CASE WHEN (MONTH(date_birth)=8) THEN females  else 0 END) as fem_aug,
        SUM(CASE WHEN (MONTH(date_birth)=8) THEN males  else 0 END) as mal_aug,

        SUM(CASE WHEN (MONTH(date_birth)=9) THEN 1 else 0 END) as birth_sep,
        SUM(CASE WHEN (MONTH(date_birth)=9) THEN females  else 0 END) as fem_sep,
        SUM(CASE WHEN (MONTH(date_birth)=9) THEN males  else 0 END) as mal_sep,

        SUM(CASE WHEN (MONTH(date_birth)=10) THEN 1 else 0 END) as birth_oct,
        SUM(CASE WHEN (MONTH(date_birth)=10) THEN females  else 0 END) as fem_oct,
        SUM(CASE WHEN (MONTH(date_birth)=10) THEN males  else 0 END) as mal_oct,

        SUM(CASE WHEN (MONTH(date_birth)=11) THEN 1 else 0 END) as birth_nov,
        SUM(CASE WHEN (MONTH(date_birth)=11) THEN females  else 0 END) as fem_nov,
        SUM(CASE WHEN (MONTH(date_birth)=111) THEN males  else 0 END) as mal_nov,

        SUM(CASE WHEN (MONTH(date_birth)=12) THEN 1 else 0 END) as birth_dic,
        SUM(CASE WHEN (MONTH(date_birth)=12) THEN females  else 0 END) as fem_dic,
        SUM(CASE WHEN (MONTH(date_birth)=12) THEN males  else 0 END) as mal_dic

        FROM vw_births WHERE status=1 AND YEAR(date_birth)= YEAR(curdate())");
        $response = array(
            "status" => "success",
            "status_code" => 200,
            "message" => "Data loaded, successful",
            "validations" => null,
            "data" => $query->row()
        );
        $this->response($response, $response['status_code']);
    }



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

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

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

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

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



    function births_post()
    {
        $data = $this->post();
        if (count($data) == 0 || count($data) > 30) {
            $response = array(
                "status" => "error",
                "status_code" => 409,
                "message" => count($data) == 0 ? 'No data received' : 'Too many data received',
                "data" => count($data),
                "validations" => array(
                    "date_birth" => "required and unique",
                    "abortions" => "required and unique",
                    "earring" => "required and unique",
                )
            );
        } else {
            $this->form_validation->set_data($data);
            $this->form_validation->set_rules('date_birth', 'date_birth', 'required');
            $this->form_validation->set_rules('abortions', 'abortions', 'required');
            $this->form_validation->set_rules('earring', 'earring', 'required|callback_animal_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 {
                $birth = array(
                    "date_birth" => $this->post('date_birth'),
                    "abortions" => $this->post('abortions'),
                    "earring" => $this->post('earring'),
                    "dead" => $this->post('dead'),
                    "females" => $this->post('females'),
                    "males" => $this->post('males'),
                    "cause" => $this->post('cause'),
                    "created_user" => $this->post('created_user'),
                    "comments" => $this->post('comments'),
                );
                $dataResponse = $this->DAO->saveOrUpdateItem('births', $birth, null, true);
                $id_birth = $dataResponse['key'];
                date_default_timezone_set('America/Mexico_City');
                $currentDate = date('Y-m-d H:i:s');

                if ($dataResponse['key']) {

                    
                    if(@$data['gender']){
                        foreach ($data['gender'] as $i => $val) {
                          

                            $dataBirth = array(
                                'category_id' => 6,
                                'specie' => $this->post('specie'),
                                'id_birth' => $id_birth,
                                'create_date' => $currentDate,
                                'birth_date' => $this->post('date_birth'),
                                'mother_earring' => $this->post('mother_earring'),
                                'id_rodeo' => $this->post('id_rodeo'),
                                'gender' => $data['gender'][$i],
                                "earring" => "OVI" . $data['earring1'][$i],
                                "grapa" => $data['grapa'][$i],
                                "birth_weight" => $data['birth_weight'][$i],

                            );
                            $pvResponse = $this->DAO->saveOrUpdateItem('animals', $dataBirth, null, true);
                        }
                    }
                    if(@$data['deadGender'] and $this->post('dead')>0){
                        foreach ($data['deadGender'] as $i => $val) {
                            $dataBirth1 = array(
                                'category_id' => 6,
                                'specie' => $this->post('specie'),
                                'id_birth' => $id_birth,
                                'create_date' => $currentDate,
                                'birth_date' => $this->post('date_birth'),
                                'mother_earring' => $this->post('mother_earring'),
                                'id_rodeo' => $this->post('id_rodeo'),
                                'gender' => $data['deadGender'][$i],
                                "earring" => "",
                                "status" => "4",
                                "grapa" => "",
                                "birth_weight" => $data['dead_weight'][$i],

                            );
                            $pvResponse = $this->DAO->saveOrUpdateItem('animals', $dataBirth1, 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,200);
        $this->response($response, $response['status_code']);
    }

    function births_put()
    {
        $id = $this->get('id');
        if ($id) {
            $dataExists = $this->DAO->selectEntity('births', array('id_births' => $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_birth" => "required and unique",
                            "abortions" => "required and unique",
                            "earring" => "required and unique",

                            "dead" => "required and unique",
                            "females" => "required and unique",
                            "males" => "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_birth" => "required and unique",
                            "abortions" => "required and unique",
                            "earring" => "required and unique",
                            "dead" => "required and unique",
                            "females" => "required and unique",
                            "males" => "required and unique",

                        ),
                        "data" => null
                    );
                } else {

                    $this->form_validation->set_data($this->put());
                    $this->form_validation->set_rules('date_birth', 'date_birth', 'required');
                    $this->form_validation->set_rules('abortions', 'abortions', 'required');

                    $this->form_validation->set_rules('dead', 'dead', 'required');
                    $this->form_validation->set_rules('females', 'females', 'required');
                    $this->form_validation->set_rules('males', 'males', '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 {
                        $data = array(
                            "date_birth" => $this->put('date_birth'),
                            "abortions" => $this->put('abortions'),
                            "earring" => $this->put('earring'),
                            "updated_user" => $this->put('created_user'),
                            "dead" => $this->put('dead'),
                            "females" => $this->put('females'),
                            "comments" => $this->put('comments'),
                            "cause" => $this->put('cause'),
                            "males" => $this->put('males'),
                        );

                        $response = $this->DAO->saveOrUpdateItem('births', $data, array('id_births' => $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 births_delete()
    {
        $id = $this->get('id');
        if ($id) {
            $dataExists = $this->DAO->selectEntity('births', array('id_births' => $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('births', $births, array('id_births' => $id));
                
                $animals = array(
                    'status' => 0,
                    'update_date' => $currentDate
                );
                $this->DAO->updateData('animals', $animals, array('id_birth' => $id));
            } else {
              
                $response = array(
                    "status" => "error",
                    "status_code" => 409,
                    "message" => "the code of births 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('earring' => $str), TRUE);
            if ($animalExists['data']) {
                return TRUE;
            } else {
                $this->form_validation->set_message('animal_exists', 'The field {field} does not exists');
                return FALSE;
            }
        }
    }
}
