<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use GuzzleHttp\Client;

class OutlookController extends Controller
{
    public function redirectToOutlook()
    {
        $query = http_build_query([
            'client_id' => config('services.outlook.client_id'),
            'response_type' => 'code',
            'redirect_uri' => config('services.outlook.redirect'),
            'response_mode' => 'query',
            'scope' => 'offline_access Mail.ReadWrite Mail.Send',
        ]);

        return redirect("https://login.microsoftonline.com/" . config('services.outlook.tenant_id') . "/oauth2/v2.0/authorize?$query");
    }

    public function handleCallback(Request $request)
    {
        if ($request->has('error')) {
            exit('error2');
            return redirect()->route('dashboard')->with('error', 'Outlook authentication failed: ' . $request->error);
        }

        if (!$request->has('code')) {
            exit('error');
            return redirect()->route('dashboard')->with('error', 'Authorization code not received.');
        }

        $user = Auth::user();
        $http = new Client();

        try {
            // Exchange authorization code for access & refresh tokens
            $response = $http->post('https://login.microsoftonline.com/' . config('services.outlook.tenant_id') . '/oauth2/v2.0/token', [
                'form_params' => [
                    'client_id' => config('services.outlook.client_id'),
                    'client_secret' => config('services.outlook.client_secret'),
                    'code' => $request->code,
                    'redirect_uri' => config('services.outlook.redirect'),
                    'grant_type' => 'authorization_code',
                ],
            ]);

            $tokens = json_decode((string) $response->getBody(), true);

            // ✅ Store the tokens in the database
            $user->update([
                'outlook_access_token' => $tokens['access_token'],
                
                'outlook_refresh_token' => $tokens['refresh_token'],
                'outlook_token_expiry' => now()->addSeconds($tokens['expires_in']),
            ]);

            return redirect()->route('dashboard')->with('success', 'Outlook connected successfully!');
        } catch (\Exception $e) {
            dd($e);
            return redirect()->route('dashboard')->with('error', 'Failed to connect to Outlook: ' . $e->getMessage());
        }
    }

    /**
     * Refresh the access token if it has expired.
     */
    public function refreshAccessToken()
    {
        $user = Auth::user();

        if (!$user->outlook_refresh_token) {
            return false;
        }

        if ($user->outlook_token_expiry && now()->lt($user->outlook_token_expiry)) {
            return $user->outlook_access_token;
        }

        $http = new Client();

        try {
            $response = $http->post('https://login.microsoftonline.com/' . config('services.outlook.tenant_id') . '/oauth2/v2.0/token', [
                'form_params' => [
                    'client_id' => config('services.outlook.client_id'),
                    'client_secret' => config('services.outlook.client_secret'),
                    'refresh_token' => $user->outlook_refresh_token,
                    'grant_type' => 'refresh_token',
                    'scope' => 'offline_access Mail.ReadWrite Mail.Send',
                ],
            ]);

            $tokens = json_decode((string) $response->getBody(), true);

            // ✅ Update user with new token
            $user->update([
                'outlook_access_token' => $tokens['access_token'],
                'outlook_refresh_token' => $tokens['refresh_token'],
                'outlook_token_expiry' => now()->addSeconds($tokens['expires_in']),
            ]);

            return $tokens['access_token'];
        } catch (\Exception $e) {
            
            return false;
        }
    }
}
