<?php

namespace apexl\Io\modules\product\entities\operators;

use apexl\Io\operators\entityDatabaseOperator;

class productOperator extends entityDatabaseOperator{

    public function __construct($table, $primaryKey = 'id')
    {
        parent::__construct($table, $primaryKey);
    }

    public function loadByName($productName){
        $entity = $this->vault->select($this->dbTable)->fields()->where('product_name', $productName)->execute()->fetchAssoc();
        return ['updateEntityData' => true, 'data' => $entity];
    }

    public function loadByFrontendId($frontendId){
        $entity = $this->vault
            ->select($this->dbTable)
            ->fields()
            ->where('(code', $frontendId)
            ->where('frontend_id', $frontendId, '=', 'OR', ')')
            ->execute()
            ->fetchAssoc();

        return ['updateEntityData' => true, 'data' => $entity];
    }

    public function getByIdOrCode($id)
    {
        $entity = $this->vault->select($this->dbTable)->fields('*')->where('id', $id)->execute()->fetchAssoc();
        if (!$entity) {
            $entity = $this->vault->select($this->dbTable)->fields('*')->where('code', $id)->execute()->fetchAssoc();
        }

        return $entity;
    }

    public function fetchAllByPrice($price)
    {
        return $this->vault->select($this->dbTable)->fields('*')->where('price', $price)->execute()->fetchAll();
    }

    public function getProductNameCache($index='id'){
        $rows = $this->vault
            ->select($this->dbTable)
            ->fields($this->dbTable.'.*')
            ->execute()
            ->fetchAll();

        $productNames = [];
        foreach ($rows as $row) {
            $productNames[$row->$index] = $row->product_name;
        }

        return $productNames;
    }

    public function getProductCacheByWPID(){
        $rows = $this->vault
            ->select($this->dbTable)
            ->fields($this->dbTable.'.*')
            ->execute()
            ->fetchAll();

        $cache = [];
        foreach ($rows as $row) {
            $cache[$row->code] = $row;
        }

        return $cache;
    }

    public function getAll(){
        return $this->vault
            ->select($this->dbTable)
            ->fields($this->dbTable.'.*')
            ->execute()
            ->fetchAll();
    }

}