<?php

namespace App\Http\Traits;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Spatie\Activitylog\Traits\LogsActivity;

// use Spatie\Activitylog\Traits\DetectsChanges;

trait LogsActivityCustom
{
    use LogsActivity;

    public static function bootLogsActivityCustom()
    {


        static::updating(function (Model $model) {
            $origan = $model->getRawOriginal();
            $dirty = $model->getDirty();
            $attrs = $model->attributesToBeLogged();
            foreach ($attrs as  $attr) {
                $key = $attr;

                if (array_key_exists($key, $dirty)) {
                    $value = $dirty[$key];
                    // "Token EUR value updated from 1 to 2"
                    $columnKey = $model->logsColumn[$key] ?? $key;
                    if (defined('self::replaceData') && in_array($key, array_keys(self::replaceData))) {
                        $val = self::replaceData[$key] ?? null;
                        $name = $origan[$model->colName];
                         $val = $val[$value];
                        $description = "$model->pageName $name has been $val";
                        $attr = [
                            'attributes' => [
                                $key => $value,
                            ],
                            'old' => [
                                $key => $origan[$key],
                            ],
                        ];
                        $description = str_replace('_', ' ', $description);
                        $logName = 'restored';
                        if ($val == 'Archived') {
                            $logName = 'archive';
                        }
                        saveLog($description, $model, $attr, $logName);
                        continue;
                    } else if (defined('self::replaceValue') && in_array($key, array_keys(self::replaceValue))) {
                        $val = self::replaceValue[$key][$value] ?? null;
                        $val2 = self::replaceValue[$key][$dirty[$key]] ?? null;
                        $description = "$model->pageName $columnKey updated from $val to  {$val2}";
                    } else if (defined('self::replaceRelation') && in_array($key, array_keys(self::replaceRelation))) {
                        $table = self::replaceRelation[$key]['table'] ?? null;
                        $relationKey = self::replaceRelation[$key]['key'] ?? null;
                        $relationValue = self::replaceRelation[$key]['value'] ?? null;
                        if ($table && $relationKey && $relationValue) {
                            $temp = DB::table($table)->select($relationValue)->where($relationKey, $origan[$key])->first();
                            $temp2 = DB::table($table)->select($relationValue)->where($relationKey, $value)->first();
                            $val = $temp->$relationValue ?? null;
                            $val2 = $temp2->$relationValue ?? null;
                            if ($val && $val2) {
                                if ($columnKey == "category") {

                                    $old_parent_id = DB::table($table)->where($relationKey, $value)->value('parent_id');
                                    $old_category_value = DB::table($table)->select($relationValue)->where($relationKey, $old_parent_id)->value('name');

                                    $new_parent_id = DB::table($table)->where($relationKey, $dirty[$key])->value('parent_id');

                                    $new_category_value = DB::table($table)->select($relationValue)->where($relationKey, $new_parent_id)->value('name');
                                    if ($old_category_value != $new_category_value) {
                                        $description = "$model->pageName $columnKey updated from $old_category_value to {$new_category_value}";

                                        $attr = [
                                            'attributes' => [
                                                $key => $value,
                                            ],
                                            'old' => [
                                                $key => $origan[$key],
                                            ],
                                        ];

                                        saveLog($description, $model, $attr, "updated");
                                    }

                                    $columnKey = "Sub Category";
                                    $description = "$model->pageName $columnKey updated from $val to {$val2}";
                                } else {
                                    $description = "$model->pageName $columnKey updated from $val to {$val2}";
                                }
                            } else if ($val) {
                                $description = "$model->pageName $columnKey updated from $val to none";
                            } else {
                                $description = "$model->pageName $columnKey updated from none to {$val2}";
                            }
                        } else {
                            $description = "$model->pageName $columnKey updated";
                        }
                    } else {
                        $dirtValue = $dirty[$key] == null ? 'NULL' : $dirty[$key];
                        $orgVal  = $origan[$key] ?? null;
                        if ($orgVal) {

                            $description = "$model->pageName $columnKey updated from $orgVal to  {$dirtValue}";
                        } else {
                            $val = $orgVal === null ? "NULL" : $orgVal;

                            $description = "$model->pageName $columnKey updated from {$val} to {$dirtValue}";

                        }
                    }

                    $attr = [
                        'attributes' => [
                            $key => $value,
                        ],
                        'old' => [
                            $key => $origan[$key] ?? null,
                        ],
                    ];
                    $description = str_replace('_', ' ', $description);

                    saveLog($description, $model, $attr, "updated");
                }
            }
            return true;
        });

    }

    public static function cleanJSON($str)
    {
        return trim(str_replace(['[', '{', '"', '}', ']'], ' ', $str));
    }

    public static function isJson($string)
    {
        $json = json_decode($string, true);
        if (json_last_error() === JSON_ERROR_NONE) {
            return $json;
        }
        return false;
    }
}
