<?php

namespace App\Http\Controllers;

use App\Departments;
use App\EmployeeAttendance;
use App\Employees;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;

class EmployeeAttendanceController extends Controller
{
    protected string $module = 'Attendance';

    public function __construct()
    {
        $module = $this->module;

        $this->middleware("permission:$module list")->only(['index']);
    }
    public function index(Request $request)
    {
        $user = Auth::user();
        $today = now()->toDateString();


        $monthYear = $request->input('month_year', now()->format('Y-m'));

        $startOfMonth = Carbon::parse($monthYear)->startOfMonth();
        $endOfMonth   = Carbon::parse($monthYear)->endOfMonth();

        if ($user->hasRole('Super-Admin') || $user->hasRole('admin')) {


            $employees = Employees::with([
                'department',
                'attendances' => function ($q) use ($startOfMonth, $endOfMonth) {
                    $q->whereDate('date', '>=', $startOfMonth)
                        ->whereDate('date', '<=', $endOfMonth)
                        ->orderBy('date', 'asc');
                }
            ])->get();


            $departmentsWithEmployees = $employees->groupBy(function ($emp) {
                return optional($emp->department)->name ?? 'No Department';
            });
            return view('attendance.index', compact('departmentsWithEmployees', 'monthYear', 'today'));
        } else {
            return $this->attendanceDetails(Crypt::encrypt(auth()->user()->employee_id));
        }
    }
    public function attendanceDetails($id)
    {
        $user = Auth::user();
        $today = now()->toDateString();
        $dec_id = Crypt::decrypt($id);



        $employees = collect();

        if ($user->hasRole('Super-Admin') || $user->hasRole('admin')) {

            $employees = Employees::with(['attendances' => function ($q) {
                $q->orderByDesc('date');
            }])->where('id', $dec_id)->get();
        } else {
            $employee = Employees::where('user_id', $user->id)->firstOrFail();
            $employee->attendances = $employee->attendances()->orderByDesc('date')->get();
            $employees = collect([$employee]);
        }

        // Return a Blade partial
        return view('attendance.attendance_details', compact('employees', 'today'));
    }

    public function checkIn()
    {
        $employee = Employees::where('user_id', Auth::id())->firstOrFail();
        $today = now()->toDateString();

        $existing = EmployeeAttendance::where('employee_id', $employee->id)
            ->where('date', $today)
            ->first();

        if ($existing && $existing->check_in) {
            return back()->with('warning', 'You have already checked in today.');
        }

        $now = now();
        $cutoffLate = now()->setTime(11, 30, 0);
        $cutoffHalfDay = now()->setTime(12, 0, 0);

        if ($now->greaterThan($cutoffHalfDay)) {
            $status = 'half-day';
        } elseif ($now->greaterThan($cutoffLate)) {
            $status = 'late';
        } else {
            $status = 'present';
        }

        try {
            DB::transaction(function () use ($employee, $today, $now, $status) {
                EmployeeAttendance::updateOrCreate(
                    ['employee_id' => $employee->id, 'date' => $today],
                    [
                        'check_in' => $now,
                        'status' => $status,
                        'notes' => ucfirst($status) . ' - Checked in at ' . $now->format('h:i A'),
                    ]
                );
            });

            return back()->with('success', 'Checked in successfully (' . ucfirst($status) . ').');
        } catch (\Exception $e) {
            return back()->with('error', 'Error: ' . $e->getMessage());
        }
    }

    public function checkOut()
    {
        $employee = Employees::where('user_id', Auth::id())->firstOrFail();
        $today = now()->toDateString();

        $attendance = EmployeeAttendance::where('employee_id', $employee->id)
            ->where('date', $today)
            ->first();

        if (!$attendance || !$attendance->check_in) {
            return back()->with('warning', 'You need to check in first.');
        }

        if ($attendance->check_out) {
            return back()->with('warning', 'You have already checked out today.');
        }

        try {
            DB::transaction(function () use ($attendance) {
                $attendance->update([
                    'check_out' => now(),
                    'notes' => 'Checked out by employee',
                ]);
            });

            return back()->with('success', 'Checked out successfully at ' . now()->format('h:i A'));
        } catch (\Exception $e) {
            return back()->with('error', 'Error: ' . $e->getMessage());
        }
    }
}
