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



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

class SmaDocumentsTypes extends ResourceController
{
    
    /**
     * Get updated documents_types table's rows.
     *
     * 
     * Based on last_sync value (from request), return updated rows from table.
     *
     * 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 SmaDocumentsTypesModel($this->dbGroupFromRequest()));

        $rules = [
            'last_sync' => 'valid_date',
            // 'first_time'=> ''
        ];
        $this->request;
        $message = [
            'last_sync' => [
                'required' => 'Tipo de dato no valido',
            ],
            // 'first_time' => [
            //     'required' => '',
            // ],
            
        ];

        // echo $this->request->();

        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
            $products_list = [];

            if($this->request->getVar('first_time')==true){

   
                $products_list = $this->getAllRows(['id'=>'id_cloud']);



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

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

            return $this->respondCreated($response);

        }

    }


    /**
     * Generate a new consecutive value for a document type.
     * 
     * Given a documents_types id, returns a valid reference and adjust consecutive to gen a new 
     * reference later
     * 
     * @param integer $documentTypeId
     * @return String
     */
    static public function getReferenceNo($documentTypeId,$dbGroup){
        $docTModel = new SmaDocumentsTypesModel($dbGroup);
        $res = $docTModel->select($docTModel->getColumnsString())
            ->where('id', $documentTypeId)
            ->first();
        // print_r($res);
        $referenceNo = $res['sales_prefix'].'-'.$res['sales_consecutive'];

        // now oupdate the document sales_consecutive
        // for some reason `sales_consecutive'is not working
        $docTModel->update($documentTypeId,['sales_consecutive'=>$res['sales_consecutive']+1]);
        // echo $referenceNo;
        return $referenceNo;
    }


    /**
     * Set sales_consecutive value to sales_consecutive value - 1.
     * 
     * Given a documents_types id, returns a valid reference and adjust consecutive to gen a new 
     * reference later
     * 
     * @param int $documentTypeId
     * @return bool If false, there is an error catched on method.
     */
    static public function undoReferenceNo($documentTypeId,$dbGroup){
        try {
            $docTModel = new SmaDocumentsTypesModel($dbGroup);
            $res = $docTModel->select($docTModel->getColumnsString())
                ->where('id', $documentTypeId)
                ->first();
            // print_r($res);
            // now oupdate the document sales_consecutive
            // for some reason `sales_consecutive'is not working
            $docTModel->update($documentTypeId,['sales_consecutive'=>$res['sales_consecutive']-1]);
            // echo $res['sales_consecutive'];
            return true;
        } catch (\Throwable $th) {
            return false;
        }
    }

}