<?php

namespace App\Controllers;

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

class SmaProducts extends ResourceController
{

    /**
     * Get updated products table's rows.
     *
     * Based on last_sync value (from request), return updated rows from products.
     *
     * 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 SmaProductsModel($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 = [];

            $filter_to_all = ['discontinued' => 0];

            $filter_to_update = null;

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

                $products_list = $this->getAllRows(['id' => 'id_cloud'], $filter_to_all);
            } else if ($this->request->getVar('first_time') == false) {
                $products_list = $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);
            }

            $unit_prices = [];

            if (SmaSettings::getSettingsColumnData('prioridad_precios_producto', $this->dbGroupFromRequest()) == 10) {
                for ($i = 0; $i < count($products_list); $i++) {
                    $items = SmaUnitPrices::getProductUnitPrices($products_list[$i]['id_cloud'],$this->dbGroupFromRequest());
                    array_push($unit_prices, $items);
                }
            }

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

            return $this->respondCreated($response);
        }
    }

    /**
     * Return product details of a given Id if it has promo price active, if not return null
     *
     * @param int $id Product id
     * @return object|null
     */
    public static function getProductPromo($id,$dbGroup)
    {
        $model = new SmaProductsModel($dbGroup);
        $product = $model->select($model->getTableNameInColumns())
            ->where("sma_products.id='$id'  AND DATE(CURDATE()) >=
                                 sma_products.start_date AND DATE(CURDATE()) <= sma_products.end_date")
            ->first();
        if ($product != null && $product['promo_price'] == null) {
            $model->update(
                $id,
                ['start_date' => '0000-00-00', 'end_date' => '0000-00-00']
            );
            $product['start_date'] = '0000-00-00';
            $product['end_date'] = '0000-00-00';
        }
        // now update product to send back

        return $product ?? null;
    }
}
