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

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


class SmaPreferences extends ResourceController
{
    /**
     * Given a preference id, returns it's table info
     *
     * @param integer|array $preference_id
     * @return array|null
     */
    static public function getPreferenceInfo($preference_id,$dbGroup){
        $model = new SmaPreferencesModel($dbGroup);
        $res = $model->select($model->getColumnsString())
            ->where(['id'=>$preference_id])
            ->first();
        return $res;
    }


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

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


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