<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use \App\Models\traits\SetConnection;

class RelationPriceHistory extends Model
{
    use SetConnection;

    protected $fillable = [
        'company_id', 'article_id', 'price', 'regist_date'
    ];

    const CREATED_AT = null;
    const UPDATED_AT = null;

    public static function getPriceDownId() {
        $result = [];
        $id_list = RelationPriceHistory::select('article_id')->groupBy('article_id')->havingRaw('count(*) > 1')->get();

        foreach($id_list as $info) {
            $res = RelationPriceHistory::where('article_id', '=', $info->article_id)->orderBy('regist_date', 'DESC')->limit(2)->get();
            if($res[0]->price < $res[1]->price) {
                $result[] = $res[0]->article_id;
            }
        }
        return $result;
    }

    public static function getHistoryById($id) {
//        $res = RelationPriceHistory::where('article_id', '=', $id)->orderBy('regist_date', "DESC")->get();
        $res = RelationPriceHistory::where('article_id', '=', $id)->orderBy('regist_date', "DESC")->orderBy('id', "DESC")->get();
        foreach ($res as $key => $value) {
            if (isset($res[$key+1])) {
                if ($res[$key]->price == $res[$key+1]->price) {
                    unset($res[$key]);
                }
            }
        }
        return $res;
    }
}
