<?php

namespace App\Exceptions;

use Spatie\Permission\Exceptions\UnauthorizedException; // pastikan ini di-import
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Notification;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Session\TokenMismatchException;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Exception\SuspiciousOperationException; 
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException; 
use Throwable;
use Exception;
use DB;
use Schema;
use App\Notifications\ErrorOccurredNotification;
 
class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array<int, class-string<Throwable>>
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }

    public function render($request, Throwable $exception)
    {
        //handle bila kena exception diarahin ke url sebelumnya dan dikasih notif error sesuai terdeteksi sebagai error apa, misalnya di class UnauthorizedException
        if ($exception instanceof UnauthorizedException) {
            //saat gapunya akses ke permissiion yg dituju
            // return Redirect::route('home.index')->with('info', $exception->getMessage());
            return redirect()->back()->with('error', $exception->getMessage());
            //nanti ditangkep di base_view yg bagian @include('layouts.partials.messages')
        }

        if ($exception instanceof ModelNotFoundException) {
            //saat manggil fungsion findOrFail biasanya
            return redirect()->back()->with('error', 'Data not found !');
        }

        return parent::render($request, $exception);
    }

    public function report(Throwable $exception)
    {
        try {
            // Daftar error yg dianggap "biasa" (tidak usah direport)
            $dontReport = [
                AuthenticationException::class,
                ValidationException::class,
                TokenMismatchException::class,
                SuspiciousOperationException::class,
                NotFoundHttpException::class,
                MethodNotAllowedHttpException::class,
            ];

            foreach ($dontReport as $skip) {
                if ($exception instanceof $skip) {
                    return;
                }
            }

            // Pastikan koneksi database sudah ready sebelum insert
            $inserted = false;
            if (Schema::hasTable('system_errors')) {
                $inserted = \DB::table('system_errors')->insert([
                    'type'    => get_class($exception),
                    'message' => $exception->getMessage(),
                    'file'    => $exception->getFile(),
                    'line'    => $exception->getLine(),
                    'trace'   => $exception->getTraceAsString()
                ]);
            }

            if (!$inserted) {
                // Ambil value dari parameter_globals
                $emailsString = \DB::table('parameter_globals')
                    ->where('key_name', 'error_email_notify')
                    ->value('value'); // langsung ambil kolom value

                if ($emailsString) {
                    // Pisahkan dengan koma & trim spasi
                    $emails = array_map('trim', explode(',', $emailsString));

                    foreach ($emails as $email) {
                        Notification::route('mail', $email)
                            ->notify(new ErrorOccurredNotification($exception));
                    }
                } else {
                    \Log::warning('Email penerima notifikasi tidak ditemukan di parameter_globals');
                }
            }
        } catch (\Exception $e) {
            \Log::error('Gagal insert notifikasi error: ' . $e->getMessage());
        }

        parent::report($exception);
    }
}
