<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Setting;
use App\Models\User;
use Illuminate\Support\Facades\Log;

class Office365CalendarSync extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'office365:sync 
                            {--user= : Sync calendars for specific user ID}
                            {--days=7 : Number of days to sync ahead}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Sync Office 365 calendar events for all authenticated users';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('Starting Office 365 calendar sync...');
        
        // Check if Office 365 integration is enabled
        if (!Setting::get('integrations.office365.enabled', false)) {
            $this->warn('Office 365 integration is disabled. Skipping sync.');
            return 0;
        }

        $userId = $this->option('user');
        $days = (int) $this->option('days');
        
        $startDate = now()->format('Y-m-d H:i:s');
        $endDate = now()->addDays($days)->format('Y-m-d H:i:s');

        try {
            // Load Office365 classes
            require_once app_path('Modules/Office365/services/Office365ServiceInterface.php');
            require_once app_path('Modules/Office365/models/Office365Token.php');
            require_once app_path('Modules/Office365/services/Office365AuthService.php');
            require_once app_path('Modules/Office365/services/Office365CalendarService.php');

            $authService = new \App\Modules\Office365\Services\Office365AuthService();
            $calendarService = new \App\Modules\Office365\Services\Office365CalendarService($authService);

            // Get users to sync
            if ($userId) {
                $users = User::where('id', $userId)->get();
                if ($users->isEmpty()) {
                    $this->error("User with ID {$userId} not found.");
                    return 1;
                }
            } else {
                // Get all users with Office365 tokens
                $users = User::whereHas('office365Token')->get();
            }

            $syncedUsers = 0;
            $totalEvents = 0;

            foreach ($users as $user) {
                $this->info("Syncing calendar for user: {$user->first_name} {$user->last_name} (ID: {$user->id})");
                
                if (!$calendarService->isAuthenticated($user->id)) {
                    $this->warn("  - User not authenticated with Office 365. Skipping.");
                    continue;
                }

                // Get selected calendars for this user
                $selectedCalendars = Setting::get('integrations.office365.selected_calendars', '');
                $selectedCalendarsArray = $selectedCalendars ? explode(',', $selectedCalendars) : [];

                // Fetch events
                $events = $calendarService->getCalendarEventsFromSelected(
                    $startDate, 
                    $endDate, 
                    $selectedCalendarsArray, 
                    $user->id
                );

                $eventCount = count($events);
                $totalEvents += $eventCount;
                $syncedUsers++;

                $this->info("  - Synced {$eventCount} events");
                
                Log::info('Office365 calendar sync completed for user', [
                    'user_id' => $user->id,
                    'events_count' => $eventCount,
                    'calendars' => $selectedCalendarsArray,
                    'date_range' => "{$startDate} to {$endDate}"
                ]);
            }

            $this->info("Calendar sync completed!");
            $this->info("- Users synced: {$syncedUsers}");
            $this->info("- Total events: {$totalEvents}");
            $this->info("- Date range: {$startDate} to {$endDate}");

            return 0;

        } catch (\Exception $e) {
            $this->error("Calendar sync failed: " . $e->getMessage());
            Log::error('Office365 calendar sync failed', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            return 1;
        }
    }
}
