<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;

class jobs extends Model
{
    /**
     * @var string $table
     */
    use HasFactory;

    protected $table = 'job';
    protected $primaryKey = 'jobid';

    /**
     * @var array $fillable
     */
    protected $fillable = [
        'jobtitle',
        'jobtype',
        'location',
        'posted_date',
        'salary',
        'jobdescription',
        'status'
    ];
    public function jobTitle()
    {
        return $this->belongsTo(jobtitles::class, 'jobtitle');
    }
    protected static function boot()
    {
        parent::boot();

        static::created(function ($job) {
            self::logActivity('created', $job);
        });

        static::updated(function ($job) {
            self::logActivity('updated', $job);
        });

        static::deleted(function ($job) {
            self::logActivity('deleted', $job);
        });
    }
    protected static function logActivity($action, $job)
    {
        $log = new LogActivity();
        $log->user_id = Auth::id();
        $log->action = $action;
        $log->url = request()->url();
        $log->ip_address = request()->ip();
        $log->user_agent = request()->userAgent();
        $log->old_values = $job->getOriginal();
        // $log->new_values = $job->getChanges();

        $newValues = $job->getChanges();
        if ($action == 'created') {
            $newValues['jobtitle'] = $job->jobTitle->jobtitle;
            $newValues['jobid'] = $job->jobid;
        }
        if ($action == 'deleted') {
            $newValues['jobtitle'] = $job->jobTitle->jobtitle;
            $newValues['jobid'] = $job->jobid;
        }
        $log->new_values = $newValues;
        
        $log->save();
    }
}
