<?php

namespace App\Http\Controllers\api\v1;

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

use App\Modules\Bookings\Onsite;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;

class CalendarControllerRESTv1 extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $start_raw = request()->get('start_date');
        $end_raw = request()->get('end_date');
        $start_ts = is_numeric($start_raw) ? (int)$start_raw : strtotime($start_raw);
        $end_ts = is_numeric($end_raw) ? (int)$end_raw : strtotime($end_raw);
        $start_date = $start_ts ? date('Y-m-d H:i:s', $start_ts) : date('Y-m-d H:i:s');
        $end_date = $end_ts ? date('Y-m-d H:i:s', $end_ts) : date('Y-m-d H:i:s', strtotime('+1 day'));

        $results = [];
        $office365Events = [];
        
        // Use Office 365 calendar service
        try {
            // Manually include Office365 classes to avoid autoloader issues
            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();
            $office365Service = new \App\Modules\Office365\Services\Office365CalendarService($authService);
            
            // Use system-wide Office 365 integration - check if admin user (user_id: 1) is authenticated
            $adminUserId = 1; // Admin user ID for system-wide integration
            $isSystemAuthenticated = $office365Service->isAuthenticated($adminUserId);
            
            Log::info('Office365 system-wide authentication check', [
                'admin_user_id' => $adminUserId,
                'current_user_id' => Auth::id(),
                'is_system_authenticated' => $isSystemAuthenticated
            ]);
            
            if ($isSystemAuthenticated) {
                // Get selected calendars from settings
                $selectedCalendars = \App\Models\Setting::get('integrations.office365.selected_calendars', '');
                $selectedCalendarsArray = $selectedCalendars ? explode(',', $selectedCalendars) : [];
                
                // Debug: Log what we're trying to fetch
                Log::info('Office365 calendar fetch attempt', [
                    'selected_calendars_setting' => $selectedCalendars,
                    'selected_calendars_array' => $selectedCalendarsArray,
                    'admin_user_id' => $adminUserId,
                    'current_user_id' => Auth::id(),
                    'start_date' => $start_date,
                    'end_date' => $end_date
                ]);
                
                // If no calendars selected, try to get events from primary calendar using admin token
                if (empty($selectedCalendarsArray)) {
                    Log::info('No calendars selected, trying primary calendar with admin token');
                    $office365Events = $office365Service->getCalendarEvents($start_date, $end_date, $adminUserId);
                } else {
                    $office365Events = $office365Service->getCalendarEventsFromSelected($start_date, $end_date, $selectedCalendarsArray, $adminUserId);
                }
                
                Log::info('Office365 calendar events retrieved', ['events_count' => count($office365Events), 'selected_calendars' => $selectedCalendarsArray]);
            } else {
                Log::warning('Office365 system authentication not available', [
                    'admin_user_id' => $adminUserId,
                    'current_user_id' => Auth::id()
                ]);
                
                return Response::json([
                    'error' => 'Calendar system authentication required',
                    'message' => 'Office 365 calendar integration is not configured. Please contact an administrator.',
                    'data' => [],
                    'setup_required' => true,
                    'setup_url' => url('/admin/settings/integrations')
                ], 401);
            }
        } catch (\Exception $e) {
            Log::error('Office365 calendar service error', [
                'error' => $e->getMessage(),
                'user_id' => Auth::id(),
                'start_date' => $start_date,
                'end_date' => $end_date
            ]);
            
            return Response::json([
                'error' => 'Calendar service error',
                'message' => 'Failed to retrieve calendar events. Please check your Office 365 connection.',
                'data' => []
            ], 500);
        }

        // Get onsite bookings
        $onsite = Onsite::onsite()->where('onsite_start', '>=', $start_date)->where('onsite_end', '<=', $end_date)->limit(100)->get();

        $colors = [
            ['background' => '#35792B', 'text' => '#FFF'], // Office365 events
            ['background' => '#E4636A', 'text' => '#FFF'], // All-day events  
            ['background' => '#F49454', 'text' => '#FFF'], // Onsite events
        ];

        // Process Office365 events
        foreach ($office365Events as $event) {
            $allDay = $event['allDay'] ?? false;
            $color = $allDay ? $colors[1] : $colors[0]; // Red for all-day, green for regular

            $results[] = [
                'id' => $event['id'] ?? '',
                'title' => $event['title'] ?? 'No Subject',
                'start' => $event['start'],
                'end' => $event['end'],
                'allDay' => $allDay,
                'color' => $color['background'],
                'textColor' => $color['text'],
                'description' => $event['description'] ?? '',
                'location' => $event['location'] ?? '',
                'source' => 'office365'
            ];
        }

        // Add remaining onsite bookings
        foreach ($onsite as $o) {
            $allDay = (strtotime($o->onsite_end) - strtotime($o->onsite_start) >= 60 * 60 * 20) ? true : false;

            $results[] = [
                'id' => 'onsite_' . $o->id,
                'title' => $o->title,
                'start' => $o->onsite_start,
                'end' => date('Y-m-d H:i:s', $allDay ? strtotime($o->onsite_end) - 10 : strtotime($o->onsite_end)),
                'allDay' => $allDay,
                'color' => $colors[2]['background'],
                'textColor' => $colors[2]['text'],
                'source' => 'onsite'
            ];
        }

        return Response::json($results);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store()
    {
        $data = request()->all();
        
        $task = DB::table('tasks')->insert([
            'name' => $data['name'],
            'description' => $data['description'] ?? '',
            'assigned_to' => $data['assigned_to'] ?? auth()->id(),
            'client_id' => $data['client_id'] ?? null,
            'type' => $data['type'] ?? 'task',
            'status_id' => $data['status_id'] ?? 1,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return Response::json(['success' => true, 'message' => 'Task created']);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        $task = DB::table('tasks')
            ->select('tasks.*', 'users.first_name', 'users.last_name', 'clients.name as client_name')
            ->leftJoin('users', 'users.id', '=', 'tasks.assigned_to')
            ->leftJoin('clients', 'clients.id', '=', 'tasks.client_id')
            ->where('tasks.id', $id)
            ->first();

        if (!$task) {
            return Response::json(['error' => 'Task not found'], 404);
        }

        return Response::json($task);
    }
}
