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


use App\Models\SmaQuotesModel;
use CodeIgniter\RESTful\ResourceController;

class SmaQuotes extends ResourceController
{

    /**
     * Get updated quotes table's rows.
     *
     * 
     * Based on last_sync value (from request), return updated rows from quotes.
     *
     * Request should contain last_sync value (date) to get updated rows based on
     * that date.
     *
     * If request contains first_time = true, it returns all data in table.
     *
     *
     * @return HttpResponse 
    */
    public function sync(){

        $this->setModel(new SmaQuotesModel($this->dbGroupFromRequest()));
        $rules = [
            'last_sync' => 'valid_date',
        ];
        $this->request;
        $message = [
            'last_sync' => [
                'required' => 'Tipo de dato no valido',
            ],
            
        ];
        if (!$this->validate($rules, $message)) {

            // if validation fails

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

            return $this->respondCreated($response);
            
        } else {

            // validate
            $quote  = [];
            $quoteItems = [];

            $authHeader = $this->request->getServer('HTTP_AUTHORIZATION');
            $token = getJWTFromRequest($authHeader);
            $view_right = viewRightFromJWT($token);
            
            $filter_to_all = [];
            $filter_to_update = null;
            
            if($view_right==0){
                $uId = userIdFromJWT($authHeader);
                $filter_to_all['created_by']=$uId;
                $filter_to_update = ['created_by'=>$uId];
                // print_r($filter_to_all);
            }

            if(($this->request->getVar('first_time')??false)==true){
            
                $quote = $this->getAllRows(['id'=>'id_cloud'],$filter_to_all);

            }else if(($this->request->getVar('first_time')??false)==false){
    
                $quote = $this->getUpdatedRows(['id'=>'id_cloud'],$filter_to_update);
            }else{
                $response = [
                    'status' => 400,
                    'error' => true,
                    'message' => 'EL campo "first_time" no es valido',
                    'data' => []
                ];
    
                return $this->respondCreated($response);
            }

            // now get orderItems
            for ($i=0; $i < count($quote); $i++) { 
                $items = SmaQuoteItems::getQuouteItems($quote[$i]['id_cloud'],$this->dbGroupFromRequest());
                array_push($quoteItems,$items);
            }

            $response = [
                'status' => 200,
                'error' => false,
                'message' => 'Exito',
                'server_date_time'=> $this->getServerDateTime(),
                'data' => [
                    'sma_quotes'=>$quote,
                    'sma_quote_items'=>$quoteItems

                ]
            ];
            return $this->respondCreated($response);
        }
    }

    /**
     * Create a new quote.
     *
     * Given quote and quote_items from request, create a new quote and it's items.
     * 
     * @todo Create quote and quote_items data validation.
     *
     * @return  
    */
    public function new(){
        $rules = [
            // for some reason it doesnt detect it
            'quote' => 'required',
            'quote_items' => 'required',
        ];
        $message = [
            'quote' => [
                'required' => 'Es necesaria la información de la cotización para su creación',
            ],
            'quote_items' => [
                'required' => 'Es necesaria la información de los productos de la cotización para su creación',
            ],
            
        ];

    
        if (!$this->validate($rules, $message)) {
    
            // if validation fails
    
            $response = [
                'status' => 400,
                'error' => true,
                'message' => $this->validator->getErrors(),
                'data' => []
            ];
    
            return $this->respondCreated($response);
            
        } else {
            $quoteData  = ($this->request->getJsonVar("quote",true)??null); 
            // validate if quote info is in request
            
            $response = [];

            if($quoteData!=null){
                // get order items data
                $quoteItemsData  = ($this->request->getJsonVar("quote_items",true)); 

                //insert order data into quote model
                
                $this->setModel(new SmaQuotesModel($this->dbGroupFromRequest()));

                $refNo = null;

                try {
                    
                    $refNo = SmaDocumentsTypes::getReferenceNo($quoteData['document_type_id'],$this->dbGroupFromRequest());
                    // $refNo=0;
                    if(isset($refNo)){
                        $quoteData['reference_no']=$refNo;
                    }
                    
                    // print_r($quoteItemsData);
                    
                    $quoteId = $this->model->insert($quoteData,true);

                    if($quoteId??false){
                        // switch to OrderSaleItemModel
                        

                        $result = SmaQuoteItems::insertQuoteItems($quoteItemsData,$quoteId,$this->dbGroupFromRequest());
                        // check everythings goes nice
                        if($result!=false&&$result==count($quoteItemsData)){
                            // send email to notify new order
                            // EmailController::sendOrderEmail($quoteData,$quoteItemsData);
                            $response = [
                                'status' => 201,
                                'error' => false,
                                'message' => "Cotización registrada",
                                'data' => [
                                    'quote_id'=>$quoteId,
                                    'reference_no'=>$refNo,
                                    'server_date'=>$this->getServerDateTime()
                                ]
                            ];
                        }else{
                            //if neeeded we can undo document consecutive
                            // if(isset($refNo)){
                            //     SmaDocumentsTypes::undoReferenceNo($quoteData['document_type_id']);
                            // }

                            // set orderSale status to error
                            // $this->disableQuote($quoteId);

                            
                            $response = [
                                'status' => 400,
                                'error' => true,
                                'message' => "Eror al registrar items de cotización",
                                'data' => []
                            ];
                        }
                    }

                } catch (\Throwable $th) {
  

                    // // if orderSales was inserted to db, then set status to error
                    // if($quoteId??false){
                    //     $this->disableQuote($quoteId);
                    // }

                    $response = [
                        'status' => 400,
                        'error' => true,
                        'message' => "Eror al registrar la cotización",
                        'error_message'=> "$th",
                        'data' => []
                    ];
                }

            }else{
                $response = [
                    'status' => 400,
                    'error' => true,
                    'message' => "El campo quote es necesario",
                    'data' => []
                ];
            }
            
           

            return $this->respondCreated($response);
        }
    }

    // /**
    //  * When Quote is need to be disable
    //  *
    //  * @param integer $quoteId
    //  * @return bool
    //  */
    // static public function disableQuote($quoteId){
    //     try {
    //         $orderSModel = new SmaQuotesModel();
    //         // echo $quoteId;
    //         $result = $orderSModel->update($quoteId,['sale_status'=>'error']);
    //         // echo $result?1:0;
    //         return $result;
    //     } catch (\Throwable $th) {
    //         // echo "$th";
    //         return false;
    //     }
    // }

    
}
