<?php

namespace App\Models\Web;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use DB;

class HistoryShopBuyedItem extends Model
{
    protected $connection = "WEB";
    protected $table = "HistoryShopBuyedItem";
    protected $primaryKey = "ID";
    protected $dates = ["Created_At"];
    protected $fillable = ["ID","AccountDBID","LinkItemID","Count","Price","Created_At"];

    public $timestamps = false;

    public function accountinfo(){
        return $this->belongsTo('App\Models\Login\AccountInfo', 'AccountDBID');
    }

    public static function SaveHistory($AccountDBID, $LinkItemID, $Count, $Price)
    {
        // Inicia as transactions
        $history_tran = DB::connection('WEB');
        $history_tran->beginTransaction();

        try {

            $hitory = new HistoryShopBuyedItem;
            $hitory->AccountDBID = $AccountDBID;
            $hitory->LinkItemID = $LinkItemID;
            $hitory->Count = $Count;
            $hitory->Price = $Price;
            $hitory->Created_At = now();
            $hitory->save();

            // COMMIT TRAN
            $history_tran->commit();

        } catch (\Exception $e){
            // ROLLBACK
            $history_tran->rollback();
            throw new \Exception($e);
        }
    }
}
