<?php

namespace App\Modules\Office365\Controllers;

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

class Office365CalendarController extends BaseController
{
    protected $calendarService;

    public function __construct(Office365CalendarService $calendarService)
    {
        $this->calendarService = $calendarService;
    }

    /**
     * Get calendar events for a date range
     */
    public function events(Request $request)
    {
        $startDate = $request->get('start_date', date('Y-m-d'));
        $endDate = $request->get('end_date', date('Y-m-d', strtotime('+1 month')));
        
        try {
            $events = $this->calendarService->getCalendarEvents($startDate, $endDate, Auth::id());
            
            return Response::json([
                'success' => true,
                'data' => $events,
                'count' => count($events)
            ]);
        } catch (\Exception $e) {
            return Response::json([
                'success' => false,
                'error' => 'Failed to retrieve calendar events',
                'message' => 'Please ensure you have connected your Office 365 calendar.',
                'data' => []
            ], 500);
        }
    }

    /**
     * Check if calendar is connected
     */
    public function status(Request $request)
    {
        $isAuthenticated = $this->calendarService->isAuthenticated(Auth::id());
        
        return Response::json([
            'connected' => $isAuthenticated,
            'auth_url' => $isAuthenticated ? null : $this->calendarService->getAuthUrl()
        ]);
    }
}