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

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

class SmaUnitPrices extends ResourceController
{

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

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

        ];

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

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

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

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

            return $this->respondCreated($response);

        }

    }

    /**
     * Return first unit_price for the given params.
     *
     * @param int $productId
     * @param int $priceGroupId
     * @param int $unitId
     * @return array|null
     */
    public static function getUnitPrices($productId, $priceGroupId, $unitId,$dbGroup)
    {
        $db = db_connect($dbGroup);
        if(isset($priceGroupId)){
            $sql = "SELECT u.id,u.name,
            u.code,u.operator,u.base_unit,u.operation_value,up.valor_unitario,u.unit_value
            FROM sma_unit_prices up INNER JOIN sma_units u ON u.id = up.unit_id WHERE
            up.unit_id='$unitId' AND up.price_group_id= '$priceGroupId' AND up.id_product='$productId'";
        }else{
            $sql = "SELECT u.id,u.name,
            u.code,u.operator,u.base_unit,u.operation_value,up.valor_unitario,u.unit_value
            FROM sma_unit_prices up INNER JOIN sma_units u ON u.id = up.unit_id WHERE
            up.unit_id='$unitId' AND up.id_product='$productId'";
        }
        
        // print_r($sql);
        $uPrice = $db->query($sql)
            ->getFirstRow('array');
    
        return $uPrice ?? null;
    }
    /**
     * Returns product's default unit_price.
     *
     * @param int $productId
     * @param int $unitId
     * @return array|null
     */
    public static function getDefaultUnitPrices($productId, $unitId,$dbGroup)
    {
        $db = db_connect($dbGroup);
        $sql = " SELECT u.id,u.name,u.code,'' as operator,u.base_unit,1 as operation_value,
        p.price as valor_unitario,p.price as unit_value FROM sma_products p INNER JOIN sma_units u ON
        (u.id= p.sale_unit AND u.id='$unitId') WHERE p.id='$productId'";
        $uPrice = $db->query($sql)->getFirstRow('array');

        return $uPrice ?? null;
    }


    /**
     * Returns all unit prices for a given product_id.
     *
     * @param int $productId
     * @return array
     */
    public static function getProductUnitPrices($productId,$dbGroup)
    {
        $model = new SmaUnitPricesModel($dbGroup);
        // $result = $model->where('id_product',$productId)->findAll();
        $result = $model->getSelectedRows(['id_product'=>$productId]);

        return $result ?? [];
    }

}
