<?php

namespace App\Http\Controllers;

use App\Models\AgentProfile;
use App\Models\Attendance;
use Illuminate\Http\Request;

class AttendanceController extends Controller
{
    public function index(Request $request)
    {
        $date = $request->input('date', date('Y-m-d'));
        
        // Get all active agents
        $agents = AgentProfile::where('status', 'Active')->with('user')->get();
        
        // Get today's attendance
        $attendances = Attendance::where('date', $date)->get()->keyBy('agent_profile_id');
        
        return view('attendances.index', compact('agents', 'attendances', 'date'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'date' => 'required|date',
            'attendances' => 'required|array',
            'attendances.*.status' => 'required|in:Present,Absent,Half Day,Leave',
            'attendances.*.check_in' => 'nullable|date_format:H:i',
            'attendances.*.check_out' => 'nullable|date_format:H:i',
        ]);

        $date = $request->date;

        foreach ($request->attendances as $agentId => $data) {
            Attendance::updateOrCreate(
                ['agent_profile_id' => $agentId, 'date' => $date],
                [
                    'status' => $data['status'],
                    'check_in' => $data['check_in'] ?? null,
                    'check_out' => $data['check_out'] ?? null,
                ]
            );
        }

        return redirect()->route('attendance.index', ['date' => $date])
                         ->with('success', 'Attendance marked successfully.');
    }

    public function selfLog(Request $request)
    {
        $user = auth()->user();
        $agent = AgentProfile::where('user_id', $user->id)->first();
        
        if (!$agent) {
            return back()->with('error', 'You do not have an Agent Profile associated with your account to mark attendance.');
        }

        $date = date('Y-m-d');
        $attendance = Attendance::where('agent_profile_id', $agent->id)->where('date', $date)->first();

        if (!$attendance) {
            // Check in
            Attendance::create([
                'agent_profile_id' => $agent->id,
                'date' => $date,
                'status' => 'Present',
                'check_in' => date('H:i')
            ]);
            return back()->with('success', 'Checked In successfully at ' . date('h:i A'));
        } elseif (!$attendance->check_out) {
            // Check out
            $attendance->update([
                'check_out' => date('H:i')
            ]);
            return back()->with('success', 'Checked Out successfully at ' . date('h:i A'));
        }

        return back()->with('error', 'You have already checked out for today.');
    }
}
