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


use App\Models\SmaSalesModel;
use App\Validation\SmaSalesValidation;
use CodeIgniter\RESTful\ResourceController;

class SmaSales extends ResourceController
{


    /**
     * Get updated sale table's rows on last month.
     *
     * 
     * Based on last_sync value (from request), return updated rows from sales.
     *
     * 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 SmaSalesModel($this->dbGroupFromRequest()));

        $rules = SmaSalesValidation::getSyncRules();

        $message = SmaSalesValidation::getSyncMessages();
        if (!$this->validate($rules, $message)) {
            $response = [
                'status' => 400,
                'error' => true,
                'message' => $this->validator->getErrors(),
                'data' => [],
                'date' => $this->request->getVar('last_sync'),
            ];

            return $this->respondCreated($response);
        }else{
            // validate
            $sales  = [];
            $sale_items = [];
            $sale_payments = [];

            $authHeader = $this->request->getServer('HTTP_AUTHORIZATION');
            helper('jwt');
            $token = getJWTFromRequest($authHeader);
            $view_right = viewRightFromJWT($token);
            
            $first_day = date('Y-m-01 00:00:00');

            // to get current month sales only
            // to get only POS sales
            $filter_to_all = ['last_update >'=>"$first_day","pos"=>1];
            // print_r($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) {

                $sales = $this->getAllRows(['id' => 'id_cloud'], $filter_to_all);

            } else if (($this->request->getVar('first_time') ?? false) == false) {

                $sales = $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($sales); $i++) { 
                $items = SmaSaleItems::getSaleItems($sales[$i]['id_cloud'],$this->dbGroupFromRequest());
                $payments = SmaPayments::getSalePayment($sales[$i]['id_cloud'],$this->dbGroupFromRequest());
                array_push($sale_items,$items);
                array_push($sale_payments,$payments);
            }

            

            $response = [
                'status' => 200,
                'error' => false,
                'message' => 'Exito',
                'server_date_time'=> $this->getServerDateTime(),
                'data' => [
                    'sma_sales'=>$sales,
                    'sma_sale_items'=>$sale_items,
                    'sma_payments'=>$sale_payments

                ]
            ];

            return $this->respondCreated($response);

        }

    }
    

    /**
     * Returns order Sales data for given user_id via post
     *
     * @return HttpResponse
     */
    public function syncAllSales(){



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


        $sales = $this->getAllRows(['id'=>'id_cloud']);
        $sale_items = [];
        $sale_payments = [];

        // now get orderItems
        for ($i=0; $i < count($sales); $i++) { 
            $items = SmaSaleItems::getSaleItems($sales[$i]['id_cloud'],$this->dbGroupFromRequest());
            $payments = SmaPayments::getSalePayment($sales[$i]['id_cloud'],$this->dbGroupFromRequest());
            array_push($sale_items,$items);
            array_push($sale_payments,$payments);
        }

        

        $response = [
            'status' => 200,
            'error' => false,
            'message' => 'Exito',
            'server_date_time'=> $this->getServerDateTime(),
            'data' => [
                'sma_sales'=>$sales,
                'sma_sale_items'=>$sale_items,
                'sma_payments'=>$sale_payments

            ]
        ];

        return $this->respondCreated($response);

        

    }


    
}
