<?php
/**
 * wishlist table's controller.
 *
 * Used to perform operations on wishlist table.
 *
 * @author Mario Vallejo <wappsi.desarrollomovil01@gmail.com>
*/          
namespace App\Controllers;

use App\Models\SmaUsersModel;
use App\Models\SmaWishlistModel;
use CodeIgniter\RESTful\ResourceController;
use Exception;

class SmaWishlist extends ResourceController
{
    
    /**
     * Return all wishlist table's rows.
     *
     * 
     *
     * @return HttpResponse
    */
    public function getAll(){

        $this->setModel(new SmaWishlistModel($this->dbGroupFromRequest()));

        

        
            // validate
            $list = $this->model->getAllRows();

            $response = [
                'status' => 200,
                'error' => false,
                'message' => 'Exito',
                'server_date_time'=> $this->getServerDateTime(),
                'data' => $list
            ];

            return $this->respondCreated($response);

        

    }


    /**
     * Returns wishlist for a given user_id.
     *
     * 
     *
     * @return HttpResponse 
    */
    public function getUserFavorites(){

        $rules = [
            'user_id' => 'required'
        ];

        $message = [
            'user_id' => [
                'required' => 'El id del usuario es requerido',
            ]
        ];

        if(!$this->validate($rules, $message)){


            $response = [
                'status' => 400,
                'error' => true,
                'message' => $this->validator->getErrors(),
                'data' => []
            ];

            return $this->respondCreated($response);
        }else{
            $this->setModel(new SmaWishlistModel($this->dbGroupFromRequest()));
            $response = [];
            try {
                // code
                $list =$this->getUserFavoritesById($this->request->getVar('user_id'));
         
                $response = [
                    'status' => 200,
                    'error' => false,
                    'message' => 'Exito',
                    'server_date_time'=> $this->getServerDateTime(),
                    'data' => $list
                ];
            } catch (Exception $e) {
                $response = [
                    'status' => 500,
                    'error' => true,
                    'message' => $e->getMessage(),
                    'server_date_time'=> $this->getServerDateTime(),
                    'data' => []
                ];
                // $e->getMessage() contains the error message
            }

            // validate
            
            
            

            return $this->respondCreated($response);

        }

    }


    /**
     * Get user wishlist.
     *
     * Given user_id, return all it's wishlist.
     * 
     * 
     * @param int  $user_id   User id
     *
     *
     * @return array 
    */
    private function getUserFavoritesById($user_id){
        $this->setModel(new SmaWishlistModel($this->dbGroupFromRequest()));
            // validate
        $temp = $this->model->getSelectedRows(["user_id"=>$user_id]);
        $list = $this->renameKey($temp,'id','id_cloud');
        
        return $list;
            
    }


    /**
     * Get company favorites.
     *
     * Only for those who have a created user.
     * 
     * Given a company_id from request, return all it's user wishlist.
     *
     * @return HttpResponse 
    */
    public function getCompanyFavorites(){

        $rules = [
            'company_id' => 'required'
        ];

        $message = [
            'company_id' => [
                'required' => 'El id del tercero es requerido',
            ]
        ];

        if(!$this->validate($rules, $message)){
            
            $response = [
                'status' => 400,
                'error' => true,
                'message' => $this->validator->getErrors(),
                'data' => []
            ];
            
            return $this->respondCreated($response);
        }else{
            $this->setModel(new SmaWishlistModel($this->dbGroupFromRequest()));
            
            $response = [];
            try {
                $users_model = new SmaUsersModel($this->dbGroupFromRequest());

                $user_id = $users_model->select('id')
                                  ->where(["company_id"=>$this->request->getVar('company_id')])->first();
             
                if(!empty($user_id)){
                    $list = $this->getUserFavoritesById($user_id['id']);
                    $response = [
                        'status' => 200,
                        'error' => false,
                        'message' => $list!=[]?'Exito':'El cliente no cuenta con productos favoritos',
                        'server_date_time'=> $this->getServerDateTime(),
                        'data' => $list
                    ];
                }else{
                    
                    $response = [
                        'status' => 200,
                        'error' => false,
                        'message' => 'El cliente no cuenta con un usuario asignado, por tanto no tiene una lista de favoritos',
                        'server_date_time'=> $this->getServerDateTime(),
                        'data' => []
                    ];
                    
                }
                
                
            } catch (Exception $e) {
                $response = [
                    'status' => 500,
                    'error' => true,
                    'message' => $e->getMessage(),
                    'server_date_time'=> $this->getServerDateTime(),
                    'data' => []
                ];
                // $e->getMessage() contains the error message
            }
            return $this->respondCreated($response);

        }

    }

    /**
     * Delete company user selected wishlist.
     *
     * Given company_id and favorites (list of wishlist ids) from request, delete 
     * favorites on the user wishlist.
     * 
     * @todo Create validation rules and messages for favorites on request.
     *
     * @return  HttpResponse
    */
    public function deleteCompanyFavorites(){

        $rules = [
            'company_id' => 'required',
            'favorites'=>'required'
        ];

        $message = [
            'company_id' => [
                'required' => 'El id del tercero es requerido',
            ],
            'favorites' => [
                'required' => 'Debe suministrar una lista de favoritos para borrar',
            ]
        ];

        if(!$this->validate($rules, $message)){
            
            $response = [
                'status' => 400,
                'error' => true,
                'message' => $this->validator->getErrors(),
                'data' => []
            ];
            
            return $this->respondCreated($response);
        }else{
            $this->setModel(new SmaWishlistModel($this->dbGroupFromRequest()));
            
            $response = [];
            try {
                $users_model = new SmaUsersModel($this->dbGroupFromRequest());

                $user_id = $users_model->select('id')
                                  ->where(["company_id"=>$this->request->getVar('company_id')])->first();
             
                if(!empty($user_id)){
                    
                    $result = $this->model->delete($this->request->getVar('favorites'));
                    
                    if($result){
                        $response = [
                            'status' => 200,
                            'error' => false,
                            'message' => 'Favoritos eliminados',
                            'server_date_time'=> $this->getServerDateTime(),
                            'data' => []
                        ];
                    }else{
                        $response = [
                            'status' => 400,
                            'error' => true,
                            'message' => 'Error al borrar favoritos',
                            'server_date_time'=> $this->getServerDateTime(),
                            'data' => []
                        ];
                    }
                    
                }else{
                    
                    $response = [
                        'status' => 200,
                        'error' => false,
                        'message' => 'El cliente no cuenta con un usuario asignado, por tanto no tiene una lista de favoritos',
                        'server_date_time'=> $this->getServerDateTime(),
                        'data' => []
                    ];
                    
                }
                
                
            } catch (Exception $e) {
                $response = [
                    'status' => 500,
                    'error' => true,
                    'message' => $e->getMessage(),
                    'server_date_time'=> $this->getServerDateTime(),
                    'data' => []
                ];
                // $e->getMessage() contains the error message
            }
            return $this->respondCreated($response);

        }

    }

    /**
     * Add wishlist to company user.
     * 
     * Given a company_id and a favorites list, create favorites for company user, if not it could receive an aditional
     * paran user_data wich should contain the required info to create a new user
     * @return HttpResponse
     */
    public function addCompanyFavorites(){

        $rules = [
            'company_id' => 'required',
            'favorites'=>'required'
        ];

        $message = [
            'company_id' => [
                'required' => 'El id del tercero es requerido',
            ],
            'favorites' => [
                'required' => 'Debe suministrar una lista de favoritos para borrar',
            ]
        ];

        if(!$this->validate($rules, $message)){
            
            $response = [
                'status' => 400,
                'error' => true,
                'message' => $this->validator->getErrors(),
                'data' => []
            ];
            
            return $this->respondCreated($response);
        }else{
            $this->setModel(new SmaWishlistModel($this->dbGroupFromRequest()));
            
            $response = [];
            try {
                $users_model = new SmaUsersModel($this->dbGroupFromRequest());

                
                try {
                    $user_id = $users_model->select('id')
                    ->where(["company_id"=>$this->request->getVar('company_id')])->first();
                } catch (\Throwable $th) {
                    //throw $th;
                    $user_id = false;
                }
             
                if($user_id==false){
            
                    
                    $user_data = json_encode($this->request->getVar('user_data'));
                    $user_data = json_decode($user_data,true);
                    $user_id = SmaUsers::createUser($user_data,$this->dbGroupFromRequest());
                    if($user_id==false){
                        $response = [
                            'status' => 400,
                            'error' => true,
                            'message' => 'Error al crear un usuario',
                            'server_date_time'=> $this->getServerDateTime(),
                            'data' => []
                        ];
                    }
                    
                }

                if($user_id!=false){
                    $set = $this->insertFavBatchData($this->request->getVar('favorites'),$user_id);

                    $result = $this->model->insertBatch($set);
                    
                    if($result){
                        $response = [
                            'status' => 200,
                            'error' => false,
                            'message' => 'Favoritos añadidos',
                            'server_date_time'=> $this->getServerDateTime(),
                            'data' => []
                        ];
                    }else{
                        $response = [
                            'status' => 400,
                            'error' => true,
                            'message' => 'Error al añadir favoritos',
                            'server_date_time'=> $this->getServerDateTime(),
                            'data' => []
                        ];
                    }
                }
                
                
            } catch (Exception $e) {
                $response = [
                    'status' => 500,
                    'error' => true,
                    'message' => $e->getMessage(),
                    'server_date_time'=> $this->getServerDateTime(),
                    'data' => []
                ];
                // $e->getMessage() contains the error message
            }
            return $this->respondCreated($response);

        }

    }
    /**
     * Given a list of products ids and an user_id, returns an array like 
     * [["user_id"=>$user_id,"product_id"=>$favorites[i]],]
     *
     * @param array $favorites
     * @param string $user_id
     * @return array
     */
    static public function insertFavBatchData($favorites,$user_id){
        $insBatch = [];
        foreach($favorites as $fav){
            array_push($insBatch,["user_id"=>$user_id,"product_id"=>$fav]);
        }
        
        return $insBatch;
    }


    /**
     * Instert a batch of favorites data on wishlist.
     *
     * 
     * @param array  $favorites   wishlist data array.
     *
     *
     * @return  integer|bool
    */
    static public function addFavorites($favorites,$dbGroup){
        
        $wishlistModel = new SmaWishlistModel($dbGroup);
        // echo 'here';
        $result = $wishlistModel->insertBatch($favorites);
        return $result;
    }


    /**
     * Add favorites to wishlist table.
     *
     * Given favorites form request, (wich should contain all data required to insert
     * new rows on wishlist table ), insert them on wishlist.
     * 
     * @todo Create favorites data validation.
     * 
     * @return  HttpResponse
    */
    public function addUserFavorites(){
        $rules = [
            'favorites' => 'required'
        ];

        $message = [
            'favorites' => [
                'required' => 'Debe suministrar una lista de favoritos con su respectivo usuario',
            ]
        ];

        if(!$this->validate($rules, $message)){
            
            $response = [
                'status' => 400,
                'error' => true,
                'message' => $this->validator->getErrors(),
                'data' => []
            ];
            
            return $this->respondCreated($response);
        }else{
            $res = $this->addFavorites($this->request->getVar('favorites'),$this->dbGroupFromRequest());

            $response = [];
            if($res!=false){
                $response = [
                    'status' => 200,
                    'error' => false,
                    'message' => "Favoritos agregados exitosamente",
                    'data' => []
                ];
                
            }else{
                $response = [
                    'status' => 401,
                    'error' => true,
                    'message' => 'Error al agregar favoritos',
                    'data' => []
                ];
            }
            return $this->respondCreated($response);
        }
    }

}