<?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');
         $this->load->model('Mortality');
    }

    function mortality_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 insemination, or empty to get all inseminations"
                ),
                "data" => null
            );
        } else {
            if ($id) {
                $response = $this->DAO->selectEntity('vw_mortality', array('id_mortality' => $id), TRUE);
            } else {
                $response = $this->DAO->selectEntity('vw_mortality', array('status' => '1'));
            }
        }
        $this->response($response, $response['status_code']);
    }


    function mortalityDayCount_get()
    {
        $day = $this->get('day');
        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 insemination, or empty to get all inseminations"
                ),
                "data" => null
            );
        } else {
            if ($day) {
                $response = $this->DAO->mortalityDayCount($day);
            } else {
                $response = $this->DAO->mortalityDayCount();
            }
        }
        $this->response($response, $response['status_code']);
    }
    
    
    
     function mortalityCause_get()
    {
        $cause = $this->get('cause');
        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 insemination, or empty to get all inseminations"
                ),
                "data" => null
            );
        } else {
            if ($cause) {
                $response = $this->Mortality->mortalityCause($cause);
            } else {
                $response = $this->Mortality->mortalityCause();
            }
        }
        $this->response($response, $response['status_code']);
    }
    
    
    
        function mortalityGeneral_get()
    {
        $query = $this->db->query("SELECT YEAR(date_mortality) AS year, specie as specie,
        SUM(CASE WHEN (MONTH(date_mortality)=1) THEN 1 else 0 END) as mortality_jan,
        SUM(CASE WHEN (MONTH(date_mortality)=2) THEN 1 else 0 END) as mortality_feb,
        SUM(CASE WHEN (MONTH(date_mortality)=3) THEN 1 else 0 END) as mortality_mar,
        SUM(CASE WHEN (MONTH(date_mortality)=4) THEN 1 else 0 END) as mortality_april,
        SUM(CASE WHEN (MONTH(date_mortality)=5) THEN 1 else 0 END) as mortality_may,
        SUM(CASE WHEN (MONTH(date_mortality)=6) THEN 1 else 0 END) as mortality_june,
        SUM(CASE WHEN (MONTH(date_mortality)=7) THEN 1 else 0 END) as mortality_july,
        SUM(CASE WHEN (MONTH(date_mortality)=8) THEN 1 else 0 END) as mortality_aug,
        SUM(CASE WHEN (MONTH(date_mortality)=9) THEN 1 else 0 END) as mortality_sep,
        SUM(CASE WHEN (MONTH(date_mortality)=10) THEN 1 else 0 END) as mortality_oct,
        SUM(CASE WHEN (MONTH(date_mortality)=11) THEN 1 else 0 END) as mortality_nov,
        SUM(CASE WHEN (MONTH(date_mortality)=12) THEN 1 else 0 END) as mortality_dic
        FROM vw_mortality WHERE status=1 AND YEAR(date_mortality)= YEAR(curdate()) GROUP BY specie ");
        $response = array(
            "status" => "success",
            "status_code" => 200,
            "message" => "Data loaded, successful",
            "validations" => null,
            "data" => $query->result()
        );
        $this->response($response, $response['status_code']);
    }



    /* function mortalityWeekCount_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 insemination, or empty to get all inseminations"
                ),
                "data" => null
            );
        } else {
            if ($id) {
                $response = $this->DAO->mortalityWeekCount($id);
            } else {
                $response = $this->DAO->mortalityWeekCount();
            }
        }
        $this->response($response, $response['status_code']);
    } */



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

    function mortalityLastWeekCount_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->mortalityLastWeekCount($id);
            } else {
                $response = $this->DAO->mortalityLastWeekCount();
            }
        }
        $this->response($response, $response['status_code']);
    }
    /*     $animalExists = $this->DAO->selectEntity('animals', array('earring' => $row['earring']), TRUE);
            if ($animalExists['data']) {
                $animal = array(
                    'status' => 2,
                    'update_date' => $currentDate
                );
                $this->DAO->updateData('animals', $animal, array('earring' => $row['earring']));
            } else {
                $animalExists = $this->DAO->selectEntity('animals', array('grapa' => $row['earring']), TRUE);
                if ($animalExists['data']) {
                    $animal = array(
                        'status' => 2,
                        'update_date' => $currentDate
                    );
                    $this->DAO->updateData('animals', $animal, array('grapa' => $data['earring']));
                }
            } */
    function mortality_excel_post()
    {
        $data = $this->post();
        $dataMortality = [];
        foreach ($data as $row) {
            date_default_timezone_set('America/Mexico_City');
            $currentDate = date('Y-m-d H:i:s');
            $dataMortality[] = array(
                "earring" => $row['earring'],
                "date_mortality" => $row['date_mortality'],
                "cause" => $row['cause'],
                "created_user" => $row['created_user'],
                "comments" => $row['comments'],
                "gender" => $row['gender'],
                "specie" => $row['specie'],
                "create_date" => $currentDate
            );
        }
        $dataResponse = $this->DAO->saveOrUpdateBatchItems('mortality', $dataMortality);
        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 mortality_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(
                    "earring" => "Field required, previously registered",
                    "date_mortality" => "Field required",
                )
            );
        } else {
            $this->form_validation->set_data($data);
            $this->form_validation->set_rules('earring', 'earring', 'required');
            $this->form_validation->set_rules('date_mortality', 'date_mortality', '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');
                $earring = strtoupper(substr($this->post('specie'), 0, 3)) . $this->post('earring');
                $mortality = array(
                    "earring" => $earring,
                    "date_mortality" => $this->post('date_mortality'),
                    "cause" => $this->post('cause'),
                    "created_user" => $this->post('created_user'),
                    "comments" => $this->post('comments'),
                    "create_date" => $currentDate
                );
                $dataResponse = $this->DAO->saveOrUpdateItem('mortality', $mortality, null, true);
                if ($dataResponse['status'] == "success") {
                    $animalExists = $this->DAO->selectEntity('animals', array('earring' => $earring), TRUE);
                    if ($animalExists['data']) {
                        $animal = array(
                            'status' => 2,
                            'update_date' => $currentDate
                        );
                        $response = $this->DAO->updateData('animals', $animal, array('earring' => $earring));
                    } else {
                        $animalExists = $this->DAO->selectEntity('animals', array('grapa' => $earring), TRUE);
                        if ($animalExists['data']) {
                            $animal = array(
                                'status' => 2,
                                'update_date' => $currentDate
                            );
                            $response = $this->DAO->updateData('animals', $animal, array('grapa' => $earring));
                        }
                    }
                    $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 mortality_put()
    {
        $id = $this->get('id');
        if ($id) {
            $dataExists = $this->DAO->selectEntity('mortality', array('id_mortality' => $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" => "Field required, previously registered",
                            "date_mortality" => "Field required",
                            /* "cause" => "Field required", */

                        ),
                        "data" => null
                    );
                } else if (count($this->put()) == 0) {
                    $response = array(
                        "status" => "error",
                        "status_code" => 409,
                        "message" => "No data was sent",
                        "validations" => array(
                            "name_rodeo" => "required and unique",
                            "earring" => "Field required, previously registered",
                            "date_mortality" => "Field required",
                            /* "cause" => "Field required", */

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

                    $this->form_validation->set_data($this->put());
                    $this->form_validation->set_rules('earring', 'earring', 'required');
                    $this->form_validation->set_rules('date_mortality', 'date_mortality', 'required');
                    /*  $this->form_validation->set_rules('cause', 'cause', '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" => $this->put('earring'),
                            "date_mortality" => $this->put('date_mortality'),
                            "cause" => $this->put('cause'),
                            "comments" => $this->put('comments'),
                            "update_date" => $currentDate,
                            "updated_user" => $this->put('updated_user'),
                        );

                        $response = $this->DAO->saveOrUpdateItem('mortality', $data, array('id_mortality' => $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 mortality_delete()
    {
        $id = $this->get('id');
        if ($id) {
            $dataExists = $this->DAO->selectEntity('mortality', array('id_mortality' => $id), TRUE);
            if ($dataExists['data']) {
                date_default_timezone_set('America/Mexico_City');
                $currentDate = date('Y-m-d H:i:s');
                $mortality = array(
                    'status' => 0,
                    'update_date' => $currentDate
                );
                $response = $this->DAO->updateData('mortality', $mortality, array('id_mortality' => $id));
            } else {
                $response = array(
                    "status" => "error",
                    "status_code" => 409,
                    "message" => "the code of mortality 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 mortalityReport_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->mortalityReport($specie, $desde, $hasta);
            } else {
                $response = $this->DAO->mortalityReport();
            }
        }
        $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;
            }
        }
    }
}
