<?php

namespace App\Models\Goliath;

use App\Models\Organisation;
use App\Notifications\SlackNotification;
use Illuminate\Database\Eloquent\Model;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Notification;

use App\Traits\Owned;

class GoliathOrganisationSpecial extends Model
{

    use Owned;

    public $table = 'goliath_organisation_special';

    protected $fillable = [
        'special',
        'organisation_id'
    ];

    private $changeLog = [];

    protected static function booted()
    {

        $change = function ($_m) {

            try {
                $new = $_m->getDirty();
                $old = $_m->getOriginal();
        
                $user = Auth::user();
                $organisation = Organisation::find(Auth::user()->organisation_id);

                $_m->changeLog = [
                    'User' => "$user->name",
                    'Organisation' => "$organisation->name",
                    'Special' => [
                        'Old' => $old === [] ? 'N/A' : ($old['special'] != 1 ? 'False' : 'True'),
                        'New' => $new === [] ? 'N/A' : ($new['special'] != 1 ? 'False' : 'True')
                    ]
                ];
            }
            catch(\Exception $ex) {
                \Log::error($ex);
            }

        };

        static::creating($change);
        static::updating($change);
        static::deleting($change);

        $done = function ($_m) {

            try {

                $notification = "Goliath Special Status Updated\n"
                    . 'User: ' . $_m->changeLog['User'] . "\n"
                    . 'Organisation: ' . $_m->changeLog['Organisation'] . "\n"
                    . 'Special: ' . $_m->changeLog['Special']['Old'] . ' -> ' . $_m->changeLog['Special']['New'] . "\n";


                (new GoliathHistory([
                    'type'              => GoliathHistoryType::Default,
                    'history'           => json_encode($_m->changeLog),
                    'organisation_id'   => Auth::user()->organisation_id,
                    'user_id'           => Auth::user()->id
                ]))->save();

                Notification::route('slack', config('creatia.webhook.goliath'))->notify(new SlackNotification($notification));
            }
            catch(\Exception $ex) {
                \Log::error($ex);

                try { \Log::info($notification); } catch (\Exception $i) {}
            }
        };

        static::created($done);
        static::updated($done);
        static::deleted($done);

    }
}
