<?php

namespace App\Exceptions;

use Carbon\Carbon;
use Exception;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Session\TokenMismatchException;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        \Illuminate\Auth\AuthenticationException::class,
        \Illuminate\Auth\Access\AuthorizationException::class,
        \Symfony\Component\HttpKernel\Exception\HttpException::class,
        \Illuminate\Database\Eloquent\ModelNotFoundException::class,
        \Illuminate\Session\TokenMismatchException::class,
        \Illuminate\Validation\ValidationException::class,
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        ErrorReporting::report($exception);
        $this->sendErrorToControlPanel($exception);
        parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        if ($exception instanceof TokenMismatchException){
            //redirect to a form. Here is an example of how I handle mine
            return redirect($request->fullUrl())->withErrors(array('login' => 'Opps! Seems you couldn\'t submit form for a longtime. Please try again'));
        }
        return parent::render($request, $exception);
    }

    /**
     * Convert an authentication exception into an unauthenticated response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Auth\AuthenticationException  $exception
     * @return \Illuminate\Http\Response
     */
    protected function unauthenticated($request, AuthenticationException $exception)
    {
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }

        return redirect()->guest('login');
    }


    /*public function err($request, Exception $e)
    {
        if($e instanceof NotFoundHttpException)
        {
            return response()->view('errors.414', []);
        }
        return parent::render($request, $e);
    }*/

    /**
     * Sends errors to control panel api
     * @param Exception $exception
     */
    private function sendErrorToControlPanel(Exception $exception)
    {
        //error message  to submit
        $requestParam = [
            'message' => '"' . $exception->getMessage() . '" in file "' . $exception->getFile() . '" line ' . $exception->getLine(),
            'current_url' => url()->current(),
            'session' => session()->all()
        ];


        // if we are in local development, do not send error
        // omit this check if testing, ensure support is aware this is just a test.
        if (app()->environment('local')) return;

        //initialize curl
        $curl = curl_init();
        //prepare data to be sent
        $data = [
            'application_id' => 4, // using the api endpoint in the docs, ensure you use the id for this app. if id does not exist, ensure it is created
            'description' => json_encode($requestParam),
            'secret' => 'VZKXKKD8GNJNABSOSRELFTUCBVBUGIXGEHZVJA5NRAFZ7BHGRDYQY5HAUYW9'
        ];

        //attach the client name and email if authenticated.
        if (Auth::user() != null) {
            //use the field in the table for the application ie name, fullname, username etc
            $data['client_name'] = auth()->user()->full_name;
            //if email is available, add this line
            $data['client_email'] = auth()->user()->email;
        }

        //set curl parameters
        curl_setopt_array($curl,
            [
                CURLOPT_URL => "https://controlpanel-api.npontu.com/api/v1/tickets/alert/application",
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => $data
            ]
        );

        //response from the api
        $response = curl_exec($curl);
        curl_close($curl);
    }

}
