<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Exception;

class MicrosoftMailService
{
    /**
     * Authenticates with Microsoft and returns the access token.
     */
    private function getAccessToken()
    {
        $tenantId = env('MS_GRAPH_TENANT_ID');
        $clientId = env('MS_GRAPH_CLIENT_ID');
        $clientSecret = env('MS_GRAPH_CLIENT_SECRET');
        $response = Http::asForm()->post("https://login.microsoftonline.com/{$tenantId}/oauth2/v2.0/token", [
            'client_id'     => $clientId,
            'client_secret' => $clientSecret,
            'scope'         => 'https://graph.microsoft.com/.default',
            'grant_type'    => 'client_credentials',
        ]);

        if ($response->failed()) {
            throw new Exception('Failed to get Microsoft Graph token: ' . $response->body());
        }
        // dd($response);
        return $response->json('access_token');
    }

    /**
     * Sends an email using the Microsoft Graph API.
     */
    public function sendEmail($toEmail, $subject, $body)
    {
        $accessToken = $this->getAccessToken();
        $sender = env('MS_GRAPH_SENDER_EMAIL');

        $response = Http::withToken($accessToken)
            ->post("https://graph.microsoft.com/v1.0/users/{$sender}/sendMail", [
                'message' => [
                    'subject' => $subject,
                    'body' => [
                        'contentType' => 'HTML', // Or 'Text'
                        'content' => $body
                    ],
                    'toRecipients' => [
                        [
                            'emailAddress' => [
                                'address' => $toEmail
                            ]
                        ]
                    ]
                ],
                'saveToSentItems' => 'true'
            ]);

        if ($response->failed()) {
            throw new Exception('Failed to send email: ' . $response->body());
        }

        return true;
    }
}