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

use App\Models\SmaPreferencesCategoriesModel;
use App\Models\SmaPreferencesModel;
use App\Models\SmaProductPreferencesModel;
use CodeIgniter\RESTful\ResourceController;


class SmaPreferencesCategories extends ResourceController
{

    /**
     * Given a preference id, returns it's table info
     *
     * @param integer|array $preference_cat_id
     * @return array|null
     */
    static public function getPreferenceCategoryInfo($preference_cat_id){

        $model = new SmaPreferencesCategoriesModel();
        $res = $model->select($model->getColumnsString())
            ->where(['id'=>$preference_cat_id])
            ->first();
        return $res;
    }


     /**
     * Given a date, ask for products updated and then use that info to
     * get product preferences categories updated, with that take preference_category_id to get preferences
     * categories updated
     *
     * @param string $date
     * @return array|null
     */
    static public function getUpdatedPrefsCats($date,$dbGroup){
        $prod_pref_model = new SmaProductPreferencesModel($dbGroup);
        $pref_cat_model = new SmaPreferencesCategoriesModel($dbGroup);
        $sub_query = $prod_pref_model
                        ->distinct()
                        ->select('preference_category_id')
                        ->join('sma_products',"last_update > '$date'")
                        ->getCompiledSelect();

        $res = $pref_cat_model->select($pref_cat_model->getColumnsString())
            ->where("id IN ($sub_query)")
            ->get()
            ->getResult();
        return $res;
    }


    /**
     * Returns all preferences table info
     *
     * @return array|null
     */
    static public function getAllPreferencesCategoriesInfo($dbGroup){
        $model = new SmaPreferencesCategoriesModel($dbGroup);
        $res = $model->getAllRows();
        return $res;
    }
}