<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AttendanceSession;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;

class ReportController extends Controller
{
    public function monthlyAttendance(Request $request): View
    {
        $month = $request->get('month', date('n'));
        $year = $request->get('year', date('Y'));
        
        $startDate = Carbon::createFromDate($year, $month, 1)->startOfMonth();
        $endDate = $startDate->copy()->endOfMonth();
        
        if ($endDate->isFuture()) {
            $endDate = Carbon::now('Asia/Dhaka')->endOfDay();
        }

        $allDaysInMonth = [];
        for ($date = $startDate->copy(); $date->lte($endDate); $date->addDay()) {
            $allDaysInMonth[] = $date->copy();
        }

        // Calculate total working days (excluding Friday)
        $workingDaysCount = 0;
        foreach ($allDaysInMonth as $date) {
            if ($date->dayOfWeek !== Carbon::FRIDAY) {
                $workingDaysCount++;
            }
        }

        $staffMembers = User::where('role', 'staff')->get();
        $reports = [];
        
        foreach ($staffMembers as $staff) {
            $sessions = AttendanceSession::with('lunchBreaks')
                ->where('user_id', $staff->id)
                ->whereMonth('attendance_date', $month)
                ->whereYear('attendance_date', $year)
                ->get();
            
            $presentDays = 0;
            $absentDays = 0;
            $lunchMinutes = 0;
            $sessionsKeyed = $sessions->keyBy(fn ($s) => Carbon::parse($s->attendance_date)->format('Y-m-d'));
            $dailyDetails = [];
            
            foreach ($allDaysInMonth as $date) {
                if ($date->dayOfWeek === Carbon::FRIDAY) {
                    continue; // Skip Fridays for absence/presence counting if fully off
                }
                
                $dateStr = $date->format('Y-m-d');
                $session = $sessionsKeyed->get($dateStr);
                
                if ($session && (!$session->is_absent || $session->manual_present)) {
                    $presentDays++;
                    $lunchMinutes += $session->lunch_minutes;
                    $dailyDetails[$dateStr] = ['status' => 'present', 'session' => $session];
                } else {
                    $absentDays++;
                    $dailyDetails[$dateStr] = ['status' => 'absent', 'session' => $session];
                }
            }
            
            $reports[] = [
                'staff' => $staff,
                'present_days' => $presentDays,
                'absent_days' => $absentDays,
                'lunch_minutes' => $lunchMinutes,
                'daily_details' => $dailyDetails,
            ];
        }

        return view('admin.reports.monthly', compact('reports', 'month', 'year', 'workingDaysCount', 'allDaysInMonth'));
    }

    public function markPresent(Request $request): RedirectResponse
    {
        $payload = $request->validate([
            'user_id' => ['required', 'exists:users,id'],
            'date' => ['required', 'date'],
        ]);
        
        AttendanceSession::updateOrCreate(
            ['user_id' => $payload['user_id'], 'attendance_date' => $payload['date']],
            [
                'is_absent' => false, 
                'manual_present' => true, 
                'status' => 'completed',
                'start_time' => Carbon::parse($payload['date'] . ' 10:00:00'),
                'stop_time' => Carbon::parse($payload['date'] . ' 18:00:00'),
                'total_work_minutes' => 480,
                'net_work_minutes' => 480,
            ]
        );
        
        return back()->with('success', 'Successfully marked staff as present for ' . $payload['date'] . '.');
    }
}
