<?php

namespace App\Modules\Office365\Controllers;

use App\Http\Controllers\BaseController;
use App\Modules\Office365\Services\Office365AuthService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class Office365SettingsController extends BaseController
{
    protected $authService;

    public function __construct(Office365AuthService $authService)
    {
        $this->authService = $authService;
    }

    /**
     * Show Office 365 settings page
     */
    public function index(Request $request)
    {
        $isAuthenticated = $this->authService->isAuthenticated(Auth::id());
        $authUrl = $isAuthenticated ? null : $this->authService->getAuthorizationUrl();

        $settings = [
            'authenticated' => $isAuthenticated,
            'auth_url' => $authUrl,
            'client_id' => env('OFFICE365_CLIENT_ID') ? 'Configured' : 'Not Configured',
            'redirect_uri' => env('OFFICE365_REDIRECT_URI', url('/admin/settings/office365/callback'))
        ];

        return view('office365.admin.settings', [
            'settings' => $settings,
            'success' => session('success'),
            'error' => session('error')
        ]);
    }

    /**
     * Get settings via API
     */
    public function getSettings(Request $request)
    {
        $isAuthenticated = $this->authService->isAuthenticated(Auth::id());
        
        return response()->json([
            'authenticated' => $isAuthenticated,
            'auth_url' => $isAuthenticated ? null : $this->authService->getAuthorizationUrl(),
            'configured' => !empty(env('OFFICE365_CLIENT_ID')) && !empty(env('OFFICE365_CLIENT_SECRET'))
        ]);
    }
}