<?php

namespace App\Observers;

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

class ProductObserver
{
    /**
     * Handle the Product "created" event.
     */
    public function created(Product $product): void
    {
        try {
            $user=Auth::user();
            $userName = $user ? $user->name : 'System';
            $message = "New Product ".$product->product_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 Product "updated" event.
     */
    public function updated(Product $product): void
    {
        try {
            $user=Auth::user();
            $userName = $user ? $user->name : 'System';
            $message = "New Product ".$product->product_name ." updated  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 Product "deleted" event.
     */
    public function deleted(Product $product): void
    {
        try {
            $user=Auth::user();
            $userName = $user ? $user->name : 'System';
            $message = "New Product ".$product->product_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 Product "restored" event.
     */
    public function restored(Product $product): void
    {
        //
    }

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