<?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Spatie\Permission\Exceptions\UnauthorizedException; // pastikan ini di-import
use Illuminate\Support\Facades\Redirect;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Notification;
use App\Notifications\ErrorOccurredNotification;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;
use Exception;
use DB;
use Schema;

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 {
            // Skip kalau error adalah NotFoundHttpException (404)
            if ($exception instanceof NotFoundHttpException) {
                return parent::report($exception);
            }

            // 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_INFO_EMAILS')
                    ->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);
    }
}
