<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use Illuminate\Http\Request;

class DiaryController extends Controller
{
    public function diaryCalendar(Request $request)
    {
        $month = $request->get('month', now()->month);
        $year = $request->get('year', now()->year);

        // Create Carbon instances for the requested month
        $startOfMonth = Carbon::create($year, $month, 1);
        $endOfMonth = $startOfMonth->copy()->endOfMonth();

        // Get all diary entries for the month
        $diaryEntries = \App\Models\Diary::whereBetween('date_time', [
            $startOfMonth->startOfDay(),
            $endOfMonth->endOfDay()
        ])->orderBy('date_time', 'asc')->get();

        // Group entries by date for easier calendar display
        $entriesByDate = $diaryEntries->groupBy(function($entry) {
            return $entry->date_time->format('Y-m-d');
        });

        // Get calendar data
        $calendarDays = [];
        $currentDate = $startOfMonth->copy()->startOfWeek();

        // Generate 6 weeks of calendar
        for ($week = 0; $week < 6; $week++) {
            $weekDays = [];
            for ($day = 0; $day < 7; $day++) {
                $dateKey = $currentDate->format('Y-m-d');
                $weekDays[] = [
                    'date' => $currentDate->copy(),
                    'isCurrentMonth' => $currentDate->month == $month,
                    'isToday' => $currentDate->isToday(),
                    'entries' => $entriesByDate->get($dateKey, collect())
                ];
                $currentDate->addDay();
            }
            $calendarDays[] = $weekDays;
        }

        // Get previous and next month for navigation
        $previousMonth = $startOfMonth->copy()->subMonth();
        $nextMonth = $startOfMonth->copy()->addMonth();

        return view('modules.processing.diary-calendar', compact(
            'calendarDays',
            'startOfMonth',
            'entriesByDate',
            'previousMonth',
            'nextMonth',
            'diaryEntries'
        ));
    }

    public function diaryList(Request $request)
    {
        $query = \App\Models\Diary::query();

        // Apply filters
        if ($request->has('status') && $request->status) {
            $query->where('status', $request->status);
        }

        if ($request->has('priority') && $request->priority) {
            $query->where('priority', $request->priority);
        }

        if ($request->has('task_type') && $request->task_type) {
            $query->where('task_type', $request->task_type);
        }

        if ($request->has('start_date') && $request->start_date) {
            $query->whereDate('date_time', '>=', $request->start_date);
        }

        if ($request->has('end_date') && $request->end_date) {
            $query->whereDate('date_time', '<=', $request->end_date);
        }

        $diaryEntries = $query->orderBy('date_time', 'asc')->paginate(15);

        return view('modules.processing.diary-list', compact('diaryEntries'));
    }

    public function diaryAdd()
    {
        return view('modules.processing.add-diary');
    }

    public function diaryStore(Request $request)
    {
        $validated = $request->validate([
            'date_time' => 'required|date',
            'task_title' => 'required|string|max:255',
            'client_case' => 'nullable|string|max:255',
            'task_type' => 'required|string|max:50',
            'priority' => 'required|in:low,medium,high',
            'location' => 'nullable|string|max:255',
            'duration' => 'nullable|string|max:50',
            'status' => 'required|in:pending,in-progress,completed,cancelled',
            'notes' => 'nullable|string',
        ]);

        // Combine date and time if time is provided separately
        if ($request->has('time') && $request->time) {
            $date = Carbon::parse($request->input('date_time'));
            $validated['date_time'] = $date->format('Y-m-d') . ' ' . $request->time;
        }

        \App\Models\Diary::create($validated);

        return redirect()->route('modules.processing.diary.list')->with('success', 'Diary entry created successfully.');
    }

    public function diaryShow($id)
    {
        $diaryEntry = \App\Models\Diary::findOrFail($id);
        return view('modules.processing.diary-show', compact('diaryEntry'));
    }

    public function diaryEdit($id)
    {
        $diaryEntry = \App\Models\Diary::findOrFail($id);
        return view('modules.processing.edit-diary', compact('diaryEntry'));
    }

    public function diaryUpdate(Request $request, $id)
    {
        $diaryEntry = \App\Models\Diary::findOrFail($id);

        $validated = $request->validate([
            'date_time' => 'required|date',
            'task_title' => 'required|string|max:255',
            'client_case' => 'nullable|string|max:255',
            'task_type' => 'required|string|max:50',
            'priority' => 'required|in:low,medium,high',
            'location' => 'nullable|string|max:255',
            'duration' => 'nullable|string|max:50',
            'status' => 'required|in:pending,in-progress,completed,cancelled',
            'notes' => 'nullable|string',
        ]);

        // Combine date and time if time is provided separately
        if ($request->has('time') && $request->time) {
            $date = Carbon::parse($request->input('date_time'));
            $validated['date_time'] = $date->format('Y-m-d') . ' ' . $request->time;
        }

        $diaryEntry->update($validated);

        return redirect()->route('modules.processing.diary.list')->with('success', 'Diary entry updated successfully.');
    }

    public function diaryDelete($id)
    {
        $diaryEntry = \App\Models\Diary::findOrFail($id);
        $diaryEntry->delete();

        return redirect()->route('modules.processing.diary.list')->with('success', 'Diary entry deleted successfully.');
    }
}
