<?php

namespace App\Exceptions;

use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log; // Add logging
use Throwable;
use Symfony\Component\HttpKernel\Exception\HttpException;
class Handler extends ExceptionHandler
{
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    public function register(): void
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }

    public function render($request, Throwable $exception)
    {
        if ($exception instanceof HttpException && $exception->getStatusCode() === 403) {
            // Log the 403 Forbidden error
            $this->logForbiddenRequest($request, $exception);
        }

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

    protected function logForbiddenRequest(Request $request, Throwable $exception)
    {
        
        Log::info('403 Forbidden log function called.'); // Log to check

        $logData = [
            'type' => '403 Forbidden',
            'method' => $request->method(),
            'url' => $request->url(),
            'body' => $request->all(),
            'headers' => $request->headers->all(),
            'error' => $exception->getMessage(),
            'time' => now()->toDateTimeString(),
        ];

        $logDirectory = storage_path('logs/' . date('Y-m-d'));
        if (!File::exists($logDirectory)) {
            File::makeDirectory($logDirectory, 0755, true);
            Log::info('Log directory created: ' . $logDirectory); // Log to check directory creation
        }
        // Log the forbidden request to a date-wise file
        File::append($logDirectory . '/forbidden.log', json_encode($logData) . "\n");
        Log::info('403 Forbidden log data written.'); // Log to check if log is written
    }
}