<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Attendance;
use App\Models\AttendanceBreak;
use App\Models\ActivityLog;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;

class AttendanceController extends Controller
{
    public function index()
    {
        $user = Auth::user();
        $attendances = Attendance::where('user_id', $user->id)
            ->orderBy('date', 'desc')
            ->paginate(15);
            
        return view('attendance.index', compact('attendances'));
    }

    public function checkIn(Request $request)
    {
        $user = Auth::user();
        $today = Carbon::today()->format('Y-m-d');

        $exists = Attendance::where('user_id', $user->id)
            ->where('date', $today)
            ->exists();

        if ($exists) {
            return back()->with('error', 'You have already checked in today.');
        }

        $attendanceService = new \App\Services\AttendanceService();
        $lateStatus = $attendanceService->calculateLateStatus(Carbon::now());

        $attendance = Attendance::create([
            'user_id' => $user->id,
            'date' => $today,
            'check_in' => Carbon::now(),
            'status' => 'present',
            'is_late' => $lateStatus['is_late'],
            'late_minutes' => $lateStatus['late_minutes'],
        ]);

        ActivityLog::create([
            'user_id' => $user->id,
            'action' => 'Check-in',
            'model_type' => 'Attendance',
            'model_id' => $attendance->id,
            'ip_address' => $request->ip(),
            'user_agent' => $request->userAgent(),
        ]);

        return back()->with('success', 'Checked in successfully at ' . Carbon::now()->format('h:i A'));
    }

    public function checkOut(Request $request)
    {
        $user = Auth::user();
        $today = Carbon::today()->format('Y-m-d');

        $attendance = Attendance::where('user_id', $user->id)
            ->where('date', $today)
            ->whereNull('check_out')
            ->first();

        if (!$attendance) {
            return back()->with('error', 'No active session found to check out.');
        }

        $checkOutTime = Carbon::now();
        $totalMinutes = $checkOutTime->diffInMinutes($attendance->check_in);
        
        // Subtract break durations
        $breakMinutes = AttendanceBreak::where('attendance_id', $attendance->id)
            ->sum('duration_minutes');
        
        $attendance->update([
            'check_out' => $checkOutTime,
            'total_work_minutes' => $totalMinutes - $breakMinutes,
            'total_break_minutes' => $breakMinutes,
        ]);

        // Logic for auto-updating status to half_day if worked less than threshold
        $attendanceService = new \App\Services\AttendanceService();
        if ($attendanceService->isHalfDay($attendance)) {
            $attendance->update(['status' => 'half_day']);
        }

        ActivityLog::create([
            'user_id' => $user->id,
            'action' => 'Check-out',
            'model_type' => 'Attendance',
            'model_id' => $attendance->id,
            'ip_address' => $request->ip(),
            'user_agent' => $request->userAgent(),
        ]);

        return back()->with('success', 'Checked out successfully. Day completed!');
    }

    public function toggleBreak(Request $request)
    {
        $user = Auth::user();
        $today = Carbon::today()->format('Y-m-d');

        $attendance = Attendance::where('user_id', $user->id)
            ->where('date', $today)
            ->whereNull('check_out')
            ->first();

        if (!$attendance) {
            return back()->with('error', 'Check in first before taking a break.');
        }

        $activeBreak = AttendanceBreak::where('attendance_id', $attendance->id)
            ->whereNull('break_end')
            ->first();

        if ($activeBreak) {
            // End active break
            $end = Carbon::now();
            $duration = $end->diffInMinutes($activeBreak->break_start);
            $activeBreak->update([
                'break_end' => $end,
                'duration_minutes' => $duration
            ]);
            return back()->with('success', 'Break ended. Welcome back!');
        } else {
            // Start new break
            AttendanceBreak::create([
                'attendance_id' => $attendance->id,
                'break_start' => Carbon::now()
            ]);
            return back()->with('info', 'Break started.');
        }
    }
}
