<?php
namespace App\Services;

use Mailgun\Mailgun;

class MailgunService
{
    protected $mailgun;

    public function __construct()
    {
        $this->mailgun = Mailgun::create(config('services.mailgun.secret'));
    }

    public function addDomain($domain)
    {
        return $this->mailgun->domains()->create($domain);
    }

    public function verifyDomain($domain)
    {
        return $this->mailgun->domains()->verify($domain);
    }

    public function createRoute($domain, $forwardUrl)
    {
        // Prepare the match expression
        $expression = "match_recipient('@" . $domain . "')";
        // Prepare actions
        $actions = ["forward('" . $forwardUrl . "')", "stop()"];
        // Description
        $description = "Route for " . $domain;
    
        // Create the route using the Mailgun API
        try {
            $route = $this->mailgun->routes()->create($expression, $actions, $description);
            return $route; // You might want to return the route ID or confirmation
        } catch (\Exception $e) {
            // Handle exceptions accordingly
            return 'Error: ' . $e->getMessage();
        }
    }

    
    public function getDomain($domainName)
    {
        try {
            $response = $this->mailgun->domains()->show($domainName);

            return $response;
            
        } catch (\Mailgun\Exception\HttpClientException $e) {
            if ($e->getResponse()->getStatusCode() == 404) {
                return false;
            }
            throw $e;
        }
    }
    
    public function removeDomain($domainName)
    {
        try {
            $response = $this->mailgun->domains()->delete($domainName);
            return $response->getMessage();
        } catch (\Mailgun\Exception\HttpClientException $e) {
            // Handling errors like unauthorized access or domain not found
            return $e->getMessage();
        }
    }
}
