<?php
/**
 * Used to perform operations on table addresses
 *
 *
 * @author Mario Vallejo <wappsi.desarrollomovil01@gmail.com>
*/

namespace App\Controllers;



use App\Models\SmaAddressesModel;
use App\Validation\SmaAddressesValidation;
use CodeIgniter\RESTful\ResourceController;

class SmaAddresses extends ResourceController
{
    




    /**
     * Create an address given adress data and returns its id
     *
     * Given address data on array, try to create a new address on addresses table,
     * if fails return
     * 
     * @param array  $address   Array with adress data to insert on addresses table
     *
     * @return  int If returns 0, there is an error catched on method
     * 
     * @author Mario Vallejo <wappsi.desarrollomovil01@gmail.com>
    */
    static public function createAddressFromArray($address,String $dbGroup){
        $addresses = new SmaAddressesModel($dbGroup);
        try {
            $address_id = $addresses->insert($address, true);
            return $address_id;
        } catch (\Throwable $th) {
            // throw($th);
            return 0;
        }
    }

    /**
     * Creates a new customer address given address data from an http.post.
     * Validation rules and messages are taken from SmaAddresses validation file.
     * 
     * @filesource App\Validation\SmaAddressesValidation
     *
     * @return HttpResponse
     */
    public function addAddress(){
       
        $rules = SmaAddressesValidation::addAddressRules();
        // $this->request;
        $message = SmaAddressesValidation::addAddressMessages();

        // echo $this->request->();
        $response = [];

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

            // if validation fails

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

            
            
        } else {
            $this->setModel(new SmaAddressesModel($this->dbGroupFromRequest()));

            // converting data into array
            $adddress_info = $this->request->getJSON();
            $adddress_info = json_encode($adddress_info);
            $adddress_info = json_decode($adddress_info, true);
        
            // if(isset($adddress_info["image"])){
            //     $file = $adddress_info["image"];
            //     // print_r($file);
            //     unset($adddress_info['image']);
            //     $fileName = uniqid();
            //     helper('images');
 
            //     $result = base64_to_selected_format($file,"../"."erp/"."assets/images/".$fileName);

            //     if($result!=false){
            //         $adddress_info['customer_profile_photo'] =  $fileName.$result;
            //     }

            //     // print_r($result?1:0);
            // }

           
            try {

                $address_id = $this->createAddressFromArray($adddress_info,$this->dbGroupFromRequest(),);

                if(isset($address_id)&&$address_id!=0){
                    $response = [
                        'status' => 200,
                        'error' => false,
                        'address_id' => $address_id,
                        'message' => 'Sucursal creada exitosamente',
                        'server_date_time'=> $this->getServerDateTime(),
                    ];
        
                }
            } catch (\Throwable $th) {
                $response = [
                    'status' => 400,
                    'error' => true,
                    'message' => $th,
                    'server_date_time'=> $this->getServerDateTime(),
                ];  
            }
  
        }
        return $this->respondCreated($response);

    }

    /**
     * Get updated Addresses on addresses table
     * 
     * Returns changes in sma_addresses based on last_sync date sended on http.post body.
     * 
     * If request contains first_time = true, it returns all data in addresses table.
     * 
     * Validation rules and messages are taken from SmaAddressesValidation file.
     * 
     * @filesource App\Validation\SmaAddressesValidation
     * @return HttpResponse
     */
    public function sync(){


        $rules = SmaAddressesValidation::getSyncRules();
        $message = SmaAddressesValidation::getSyncMessages();

        // 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 {
            $this->setModel(new SmaAddressesModel($this->dbGroupFromRequest()));

            // validate
            $item_list = [];
            

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

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



            }else if($this->request->getVar('first_time')==false){
                $item_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' => $item_list
            ];

            return $this->respondCreated($response);

        }

    }


    /**
     * Return Address data form addresses table
     * 
     * Returns selected data in sma_companies, $column field is a string for select
     * who determines wich column return
     *
     * @param int $id Adrress id
     * @param string $column    Adrress column name of interest
     * @return mixed|null
     */
    static public function getAddressesData($id, $column,String $dbGroup)
    {
        $model = new SmaAddressesModel($dbGroup);
        $res = $model->getColumnsData('id', $id, $column);
        return $res->{$column} ?? null;
    }


    /**
     * Add location and subzone data to address.
     * 
     * Given an address_id, zone_code and subzone_code on request
     * 
     * @filesource App\Validation\SmaAddressesValidation
     *
     * @return HttpResponse
     */
    public function addAddressZoneSZone(){
       
        $rules = SmaAddressesValidation::addAddressZSzRules();
        // $this->request;
        $message = SmaAddressesValidation::addAddressZsZMessages();

        // echo $this->request->();
        $response = [];

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

            // if validation fails

            $response = [
                'status' => 400,
                'error' => true,
                'message' => $this->validator->getErrors(),
                'data' => []
            ];
            
        } else {
            $this->setModel(new SmaAddressesModel($this->dbGroupFromRequest()));

            // converting data into array
            $adddress_id = $this->request->getVar('address_id');
            $data = [
                "location"=> $this->request->getVar('zone_id'),
                "subzone"=> $this->request->getVar('subzone_id'),
                "last_update"=> $this->getServerDateTime()
            ];
            try {
                $address_id = $this->model->update($adddress_id, $data);

                if(isset($address_id)&&$address_id!=0){
                    $response = [
                        'status' => 200,
                        'error' => false,
                        'address_id' => $address_id,
                        'message' => 'Zona y subzona modificada',
                        'server_date_time'=> $this->getServerDateTime(),
                    ];
                }
            } catch (\Throwable $th) {
                $response = [
                    'status' => 400,
                    'error' => true,
                    'message' => $th,
                    'server_date_time'=> $this->getServerDateTime(),
                ];  
            }
  
        }
        return $this->respondCreated($response);

    }

}