<?php

namespace App\Models\Web;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\Login\AccountInfo;
use DB;

class AntihackLogControl extends Model
{
    protected $connection = "WEB";
    protected $table = "AntihackLogControl";
    protected $primaryKey = "ID";
    protected $dates = ["Updated_At"];
    protected $fillable = ["ID", "UUID", "AccountDBID","Motivo","Filename","Updated_At"];

    public $timestamps = false;

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

    public static function Create($params)
    {
        // Inicia as transactions
        $account_tran = DB::connection('Login');
        $account_tran->beginTransaction();

        $web_tran = DB::connection('WEB');
        $web_tran->beginTransaction();

        try {

            $UUID = explode(":", $params['UUID']);
            if(isset($UUID[1])){

                $AccountInfo = AccountInfo::where('UUID', $UUID[1])->first();
                if($AccountInfo->IsBlocked == 1)
                    return 0;

                $AntiHack = new AntihackLogControl();
                $AntiHack->UUID = $UUID[1];
                $AntiHack->AccountDBID = $AccountInfo->AccountDBID;
                $AntiHack->Motivo = $params['Motivo'];
                $AntiHack->Filename = $params['Filename'];
                $AntiHack->Updated_At = now();
                $AntiHack->save();

                $AccountInfo->IsBlocked = 1;
                $AccountInfo->IsActivated = 1;
                $AccountInfo->save();
            }

            // COMMIT TRAN
            $account_tran->commit();
            $web_tran->commit();

            return 0;

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