<?php

namespace App\Http\Controllers\Mailgun;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Services\MailgunService;

class MailgunController extends Controller
{
    protected $mailgunService;

    public function __construct()
    {
        $this->mailgunService = app(MailgunService::class); // Resolving through the service container
    }

    public function addDomain($domain)
    {
        
        try{
        
       // $domain = $request->input('domain');
        
        $mailgunDomain = $this->mailgunService->getDomain($domain);
      
        
        if(!$mailgunDomain){
        
        // dd($this->mailgunService->removeDomain($domain));
       
    //   dd($this->verifyDomain($request));
        
        $response = $this->mailgunService->addDomain($domain);
        
        return route('showDomain',$domain)->redirect();
        
        }else{            
             return redirect()->route('showDomain',$domain);
        }
        
        }catch(Exception $e){
            return $e->getMessage();
        }
    }
    
    public function showDomain($domain){
        
        
        $mailgunDomain = $this->mailgunService->getDomain($domain);
        
        if($mailgunDomain){
                  
            return view('domains.verify-domain',[ 'domain' => $mailgunDomain]);
        }else{
            return ("Domain not found");
        }
    }

    public function verifyDomain(Request $request)
    {
        $domain = $request->input('domain');
        $response = $this->mailgunService->verifyDomain($domain);
        
        $state = $response->getDomain()->getState();
        
        if($state == 'unverified'){
            return redirect()->route('showDomain',$domain);
        }elseif($state == 'active'){
            $this->createRoute($request);
            
            return redirect('/dashboard');
        }
        
    }

    public function createRoute(Request $request)
    {
        $domain = $request->input('domain');
        $forwardUrl = "https://kundesone.no/api/save-email";
        $response = $this->mailgunService->createRoute($domain, $forwardUrl);
        return $response;
    }
}


