<?php

namespace App\Observers;

use App\Models\Area;
use App\Models\Systemlog;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class AreaObserver
{
    /**
     * Handle the Area "created" event.
     */
    public function created(Area $area): void
    {
        try {
            $user=Auth::user();
            $userName = $user ? $user->name : 'System';
            $message = "New Area ".$area->area_name ." added  by ".$userName." at ".now()->toDateTimeString();
            Systemlog::create([
                'message' => $message,
            ]); 
        } catch (\Exception $e) {
            Systemlog::create([
                'message' => $e->getMessage(),
            ]);
            // Handle the exception here, for example, log the error message
            Log::error('Error in observer: ' . $e->getMessage());
        }
    }

    /**
     * Handle the Area "updated" event.
     */
    public function updated(Area $area): void
    {
        //
    }

    /**
     * Handle the Area "deleted" event.
     */
    public function deleted(Area $area): void
    {
        try {
            $user=Auth::user();
            $userName = $user ? $user->name : 'System';
            $message = " Area ".$area->area_name ." deleted  by ".$userName." at ".now()->toDateTimeString();
            Systemlog::create([
                'message' => $message,
            ]); 
        } catch (\Exception $e) {
            Systemlog::create([
                'message' => $e->getMessage(),
            ]);
            // Handle the exception here, for example, log the error message
            Log::error('Error in observer: ' . $e->getMessage());
        }
    }

    /**
     * Handle the Area "restored" event.
     */
    public function restored(Area $area): void
    {
        //
    }

    /**
     * Handle the Area "force deleted" event.
     */
    public function forceDeleted(Area $area): void
    {
        //
    }
}
