<?php
/**
 * brand table's controller
 *
 * Used to perfom operations on brands table.
 *
 * @author Mario Vallejo <wappsi.desarrollomovil01@gmail.com>
*/

namespace App\Controllers;



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

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

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

        $rules = [
            'last_sync' => 'valid_date',
            // 'first_time'=> ''
        ];
        $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
            $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);

        }

    }

}