<?php

namespace App\Classes\General\Traits;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;

trait LogData
{

    public static function boot()
    {
        parent::boot();


        static::updating(function($model)
        {

            $tableName = Str::singular($model->table).'_logs';
            $relationshipColumn = Str::singular($model->table).'_id';

            $originalData = $model->getRawOriginal();

            $originalData[$relationshipColumn] = $originalData['id'];
            unset($originalData['id']);

            // remove pivot columns
            foreach($originalData as $key => $row){
                if(str::startsWith($key, 'pivot_')){
                    unset($originalData[$key]);
                }
            }

            if (!Schema::hasTable($tableName)) {
                DB::statement('CREATE TABLE '.$tableName.' LIKE '.$model->table);

                $indexs = DB::select('SHOW INDEX FROM '.$tableName.';');

                $removedIndexes = [];
                foreach ($indexs as $index){
                    if($index->Column_name === 'id' || in_array($index->Key_name, $removedIndexes)) continue;
                    DB::statement('ALTER TABLE '.$tableName.' drop index '.$index->Key_name);
                    $removedIndexes[] = $index->Key_name;
                }

                DB::statement('ALTER TABLE '.$tableName.' ADD COLUMN `'.$relationshipColumn.'` BIGINT NOT NULL AFTER `id`');
            }

            DB::table($tableName)->insert($originalData);

        });
    }
}
