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


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

    function dietHistory_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 treatment, or empty to get all treatments"
                ),
                "data" => null
            );
        } else {
            if ($id) {
                $response = $this->DAO->selectEntity('vw_diet', array('id_rodeo' => $id), false);
            } else {
                $response = $this->DAO->selectEntity('vw_diet', array('status' => '1'));
            }
        }
        $this->response($response, $response['status_code']);
    }

    function gdpRodeo_get()
    {
        $idRodeo = $this->get('idRodeo');
        $dateG = $this->get('date');

        if (count($this->get()) > 2) {
            $response = array(
                "status" => "error",
                "status_code" => 409,
                "message" => "Too many params was sent",
                "validations" => array(
                    "id" => "Send Id (Get) to get specific treatment, or empty to get all treatments"
                ),
                "data" => null
            );
        } else {
            if ($idRodeo) {
                $response = $this->DAO->gdpRodeo($idRodeo, $dateG); //'vw_gdp', array('id_rodeo' => $id), false
            } else {
                $response = $this->DAO->gdpRodeo($idRodeo, $dateG);
            }
        }
        $this->response($response, $response['status_code']);
    }




    function ingredient_get()
    {
        $id = $this->get('id');
        $diet = $this->get('diet');
        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 treatment, or empty to get all treatments"
                ),
                "data" => null
            );
        } else {

            if ($id) {
                $response = $this->DAO->selectEntity('ingredients_diet', array('id_ingredient' => $id), true);
            } else if ($diet) {
                $response = $this->DAO->selectEntity('ingredients_diet', array('id_diet' => $diet, 'status' => '1'), false);
            } else {
                $response = $this->DAO->selectEntity('ingredients_diet', array('status' => '1'));
            }
        }
        $this->response($response, $response['status_code']);
    }

    function rodeoDiet_put()
    {
        $id = $this->get('id');
        if ($id) {
            $dataExists = $this->DAO->selectEntity('rodeos', array('id_rodeos' => $id), TRUE);
            if ($dataExists) {
                if (count($this->put()) > 12) {
                    $response = array(
                        "status" => "error",
                        "status_code" => 409,
                        "message" => "Too many data was sent",
                        "validations" => array(
                            "id_diet" => "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(
                            "id_die" => "required and unique",
                        ),
                        "data" => null
                    );
                } else {
                    $this->form_validation->set_data($this->put());
                    $this->form_validation->set_rules('id_die', 'id_die', '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(
                            "id_diet" => $this->put('id_die'),
                        );

                        $response = $this->DAO->saveOrUpdateItem('rodeos', $data, array('id_rodeos' => $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 diet_post()
    {

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

                foreach ($data['name_ingredient'] as $i => $val) {
                    $subt = $data['subt'][$i];
                    $total1 = $total1 + $subt;
                }

                $diet = array(

                    "name_diet" => $this->post('name_diet'),
                    "description" => $this->post('description'),
                    "kilosTotales" => $this->post('kilosTotales'),
                    "total_diet" => $total1,
                    "created_date" => $currentDate,
                    "updated_date" => $currentDate
                );
                $dietResponse = $this->DAO->saveOrUpdateItem('diet', $diet, null, true);
                if ($dietResponse['key']) {
                    $id_diet = $dietResponse['key'];
                    foreach ($data['name_ingredient'] as $i => $val) {
                        $dataPV = array(
                            'id_diet' => $id_diet,
                            'name_ingredient' => $data['name_ingredient'][$i],
                            "proportion" => $data['proportion'][$i],
                            "price_kilo" => $data['price_proportion'][$i],
                            "subt" => $data['subt'][$i],
                            'created_date' => $currentDate,
                            'updated_date' => $currentDate
                        );
                        $pvResponse = $this->DAO->saveOrUpdateItem('ingredients_diet', $dataPV, null, true);
                    }
                    foreach ($data['id_rodeo'] as $ii => $val) {
                         $rod = $data['id_rodeo'][$ii];
                        $last = $this->DAO->last_diet($rod)['data'];

                        if ($last) {

                            $diet_history = array(
                                'finish_diet' => $currentDate,
                            );
                            $pvResponse = $this->DAO->updateData('diet_history', $diet_history, array('id_dietHistory' => $last->id_dietHistory));
                        }
                       

                        $history = array(
                            'id_diet' => $id_diet,
                            "price_diet" => $total1,
                            'id_rodeo' => $data['id_rodeo'][$ii],
                            'date_displacement' => $data['date_displacement'],
                            'start_diet' => $currentDate,
                            'created_date' => $currentDate,
                        );
                        $pvResponse = $this->DAO->saveOrUpdateItem('diet_history', $history, null, true);

                        $rodeo = array(
                            'id_diet' => $id_diet,
                            'update_date' => $currentDate
                        );
                        $pvResponse = $this->DAO->updateData('rodeos', $rodeo, array('id_rodeos' => $data['id_rodeo'][$ii]));
                    }


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


    function dietHistory_put()
    {
        $id = $this->get('id');
        $data = $this->put();
        if ($id) {
            $dataExists = $this->DAO->selectEntity('diet_history', array('id_dietHistory' => $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(
                            "start_diet" => "Required field",
                            "finish_diet" => "Required field"
                        )
                    );
                } else {

                    $this->form_validation->set_data($data);
                    $this->form_validation->set_rules('finish_diet', 'finish_diet', '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');

                        $history_ = array(
                            'start_diet' => $data['start_diet'],
                            'finish_diet' => $data['finish_diet'],
                            'updated_date' => $currentDate
                        );
                        $response = $this->DAO->saveOrUpdateItem('diet_history', $history_, array('id_dietHistory' => $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 diet_put()
    {
        $id = $this->get('id');
        $data = $this->put();
        if ($id) {
            $dataExists = $this->DAO->selectEntity('diet', array('id_diet' => $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(
                            "name" => "Required field"
                        )
                    );
                } else {

                    $this->form_validation->set_data($data);
                    $this->form_validation->set_rules('name', 'name', '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');

                        $category = array(
                            'name' => $data['name'],
                            'updated_date' => $currentDate
                        );
                        $response = $this->DAO->saveOrUpdateItem('animal_category', $category, array('category_id' => $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 ingredient_delete()
    {
        $id = $this->get('id');
        if ($id) {
            $dataExists = $this->DAO->selectEntity('ingredients_diet', array('id_ingredient' => $id), TRUE);
            if ($dataExists['data']) {
                date_default_timezone_set('America/Mexico_City');
                $currentDate = date('Y-m-d H:i:s');
                $diet = array(
                    'status' => 0,
                    'updated_date' => $currentDate
                );
                $response = $this->DAO->updateData('ingredients_diet', $diet, array('id_ingredient' => $id));
            } else {
                $response = array(
                    "status" => "error",
                    "status_code" => 409,
                    "message" => "the code of the diet 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 diet_delete()
    {
        $id = $this->get('id');
        if ($id) {
            $dataExists = $this->DAO->selectEntity('diet', array('id_diet' => $id), TRUE);
            if ($dataExists['data']) {
                date_default_timezone_set('America/Mexico_City');
                $currentDate = date('Y-m-d H:i:s');
                $diet = array(
                    'status' => 0,
                    'updated_date' => $currentDate
                );
                $response = $this->DAO->updateData('diet', $diet, array('id_diet' => $id));
            } else {
                $response = array(
                    "status" => "error",
                    "status_code" => 409,
                    "message" => "the code of the diet 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 ingredient_put()
    {
        $id = $this->get('id');
        if ($id) {
            $dataExists = $this->DAO->selectEntity('ingredients_diet', array('id_ingredient' => $id), TRUE);
            if ($dataExists) {
                if (count($this->put()) > 12) {
                    $response = array(
                        "status" => "error",
                        "status_code" => 409,
                        "message" => "Too many data was sent",
                        "validations" => array(
                            "name_ingredient" => "required and unique",
                            "proportion" => "required and unique",
                            "price_kilo" => "required and unique",
                            "subt" => "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(
                            "name_ingredient" => "required and unique",
                            "proportion" => "required and unique",
                            "price_kilo" => "required and unique",
                            "subt" => "required and unique",
                        ),
                        "data" => null
                    );
                } else {
                    $this->form_validation->set_data($this->put());
                    $this->form_validation->set_rules('name_ingredient', 'name_ingredient', 'required');
                    $this->form_validation->set_rules('proportion', 'proportion', 'required');
                    $this->form_validation->set_rules('price_kilo', 'price_kilo', 'required');
                    $this->form_validation->set_rules('subt', 'subt', '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(
                            "name_ingredient" => $this->put('name_ingredient'),
                            "proportion" => $this->put('proportion'),
                            "price_kilo" => $this->put('price_kilo'),
                            "subt" => $this->put('subt'),
                        );

                        $response = $this->DAO->saveOrUpdateItem('ingredients_diet', $data, array('id_ingredient' => $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']);
    }
}
