<?php

namespace App\Http\Controllers;

use App\Models\CalendarEvent;
use App\Models\Job;
use App\Models\User;
use App\Models\ActivityLog;
use Carbon\Carbon;
use Illuminate\Http\Request;

class CalendarController extends Controller
{
    public function index(Request $request)
    {
        $query = CalendarEvent::with(['job', 'assignedTo'])->orderBy('start_at');

        if ($request->type) {
            $query->where('type', $request->type);
        }

        if ($request->month) {
            $month = Carbon::parse($request->month);
            $query->whereYear('start_at', $month->year)->whereMonth('start_at', $month->month);
        }

        $events = $query->get();

        $upcomingEvents = CalendarEvent::with(['job', 'assignedTo'])
            ->where('start_at', '>=', Carbon::now())
            ->orderBy('start_at')
            ->take(10)
            ->get();

        $jobs = Job::with('contact')->latest()->take(50)->get();
        $users = User::where('is_active', true)->orderBy('name')->get();

        return view('calendar.index', compact('events', 'upcomingEvents', 'jobs', 'users'));
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'title'       => 'required|string|max:255',
            'type'        => 'required|in:check_measure,delivery,installation,consultation,follow_up,processing,contracts_admin,other',
            'start_at'    => 'required|date',
            'end_at'      => 'nullable|date|after_or_equal:start_at',
            'job_id'      => 'nullable|exists:crm_jobs,id',
            'assigned_to' => 'nullable|exists:users,id',
            'location'    => 'nullable|string|max:255',
            'notes'       => 'nullable|string',
            'all_day'     => 'boolean',
        ]);

        $data['created_by'] = auth()->id();
        $data['all_day'] = $request->boolean('all_day');
        if (empty($data['end_at'])) {
            $data['end_at'] = \Carbon\Carbon::parse($data['start_at'])->addHours(2)->toDateTimeString();
        }

        $event = CalendarEvent::create($data);

        ActivityLog::create([
            'user_id' => auth()->id(), 'loggable_type' => 'CalendarEvent', 'loggable_id' => $event->id,
            'action' => 'Event Created', 'description' => "Calendar event '{$event->title}' on ".$event->start_at->format('d M Y'),
        ]);

        if ($request->expectsJson()) {
            return response()->json(['success' => true, 'event' => $event]);
        }

        return redirect()->route('calendar.index')->with('success', 'Event created.');
    }

    public function update(Request $request, CalendarEvent $event)
    {
        $data = $request->validate([
            'title'       => 'required|string|max:255',
            'type'        => 'required|in:check_measure,delivery,installation,consultation,follow_up,processing,contracts_admin,other',
            'start_at'    => 'required|date',
            'end_at'      => 'nullable|date',
            'job_id'      => 'nullable|exists:crm_jobs,id',
            'assigned_to' => 'nullable|exists:users,id',
            'location'    => 'nullable|string|max:255',
            'notes'       => 'nullable|string',
        ]);

        $event->update($data);
        return back()->with('success', 'Event updated.');
    }

    public function destroy(CalendarEvent $event)
    {
        $event->delete();
        return back()->with('success', 'Event deleted.');
    }
}
