<?php

namespace App\Http\Controllers\Manager;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use App\Models\Department;
use App\Models\Employee;
use App\Models\Attendance;
use Carbon\Carbon;
use App\Models\Holiday;
use App\Models\Setting;

class AttendanceController extends Controller
{



    public function index(Request $request)
    {
        $query = Attendance::with('employee')
        ->selectRaw('date, 
                     SUM(CASE WHEN status = "present" THEN 1 ELSE 0 END) as total_present, 
                     SUM(CASE WHEN status = "absent" THEN 1 ELSE 0 END) as total_absences, 
                     SUM(CASE WHEN status = "late" THEN 1 ELSE 0 END) as total_late, 
                     SUM(CASE WHEN status = "remote" THEN 1 ELSE 0 END) as total_remote')
        ->groupBy('date');

        if ($request->filled('year')) {
            $query->whereYear('date', $request->year);
        }

        if ($request->filled('month')) {
            $query->whereMonth('date', $request->month);
        }

        if ($request->filled('day')) {
            $query->whereDay('date', $request->day);
        }

        $attendances = $query->get();
        $settings = Setting::first();

    return view('manager.attendance.index', compact('attendances' , 'settings'));
    }


    public function addpage()
    {
        $departments = Department::all(); 
        $employees = Employee::with('todayAttendance')->get(); 
        return view('manager.attendance.add', compact('departments', 'employees'));
    }

    

    public function submitAttendance(Request $request)
{
    // Check if 'attendances' key exists in the request
    if ($request->has('attendances') && !is_null($request->attendances)) {
        $attendances = $request->attendances;
        $date = $request->input('attendance_date', date('Y-m-d')); // Get the selected date, default to today's date

        // Iterate through each attendance data and handle it
        foreach ($attendances as $attendanceData) {
            $employeeId = $attendanceData['employee_id'];
            $status = $attendanceData['status'];
            $reason = $attendanceData['reason'];
            $presentTime = $attendanceData['present_time'] ?? '00:00:00';
            $outTime = $attendanceData['out_time'] ?? '00:00:00';

            // Check if an attendance record already exists for the selected date
            $attendance = Attendance::where('employee_id', $employeeId)
                                    ->whereDate('created_at', $date)
                                    ->first();

            // Update or create the attendance record
            if ($attendance) {
                $attendance->update([
                    'status' => $status,
                    'reason' => $reason,
                    'present_time' => $presentTime,
                    'out_time' => $outTime,
                    'date' => $date, // Use the selected date

                ]);
                $message = 'Attendance updated successfully for employee ID ' . $employeeId;
            } else {
                Attendance::create([
                    'employee_id' => $employeeId,
                    'status' => $status,
                    'reason' => $reason,
                    'present_time' => $presentTime,
                    'out_time' => $outTime,
                    'date' => $date, // Use the selected date
                ]);

                $message = 'Attendance added successfully for employee ID ' . $employeeId;
            }

            \Log::info($message);
        }

        return redirect()->route('attendance.add')->with('success', 'Attendances processed successfully');
    } else {
        return response()->json(['error' => 'No attendance data provided'], 400);
    }
}

    
    
    public function filterEmployees(Request $request)
    {
        $departments = Department::all(); // Retrieve all departments
        $departmentName = $request->input('department');
        $currentDate = date('Y-m-d'); // Get the current date
    
        if ($departmentName) {
            $employees = Employee::where('department', $departmentName)->with(['todayAttendance' => function($query) use ($currentDate) {
                $query->whereDate('created_at', $currentDate);
            }])->get();
        } else {
            $employees = Employee::with(['todayAttendance' => function($query) use ($currentDate) {
                $query->whereDate('created_at', $currentDate);
            }])->get();
        }
    
        $attendanceAlreadyAdded = $employees->every(function ($employee) {
            return $employee->todayAttendance !== null;
        });
    
        return view('manager.attendance.add', compact('departments', 'employees', 'attendanceAlreadyAdded'));
    }
    
    


  public function edit($date)
    {
        $departments = Department::all();
        
        // Fetch attendance records for the specified date
        $attendances = Attendance::whereDate('created_at', $date)->get();

        return view('manager.attendance.edit', compact('departments', 'attendances', 'date'));
    }

    
    
    public function update(Request $request)
    {
        $request->validate([
            'attendances.*.status' => 'required|string|max:10',
            'attendances.*.reason' => 'nullable|string',
            'attendances.*.present_time' => 'nullable|date_format:H:i',
            'attendances.*.out_time' => 'nullable|date_format:H:i',
        ]);
    
        $attendances = $request->input('attendances', []);
        foreach ($attendances as $attendanceId => $attendanceData) {
            $attendance = Attendance::find($attendanceId);
    
            if ($attendance) {
                $attendance->status = $attendanceData['status'] ?? '';
                $attendance->reason = $attendanceData['reason'] ?? null;
                $attendance->present_time = !empty($attendanceData['present_time']) ? $attendanceData['present_time'] : '00:00:00';
                $attendance->out_time = !empty($attendanceData['out_time']) ? $attendanceData['out_time'] : '00:00:00';
                $attendance->save();
            }
        }
    
        return redirect()->route('attendance.edit', ['date' => $request->input('date')])
            ->with('success', 'Attendance updated successfully');
    }
    
    
    


    public function date($date)
    {
        $departments = Department::all();
        
        // Fetch attendance records for the specified date
        $attendances = Attendance::whereDate('created_at', $date)->get();

        return view('manager.attendance.date', compact('departments', 'attendances', 'date'));
    }


    public function query(Request $request)
    {
        $departments = Department::all();
        $employees = Employee::all();

        $showMessage = false;
        $attendances = collect();
        $holidays = collect();
        $dates = collect();
        $totalPresent = 0;
        $totalAbsent = 0;
        $totalRemote = 0;
        $totalLate = 0;
        $totalHolidays = 0;
        $selectedDepartment = null;
        $selectedEmployee = null;

        if ($request->filled('year') && $request->filled('month') && $request->filled('employee')) {
            $query = Attendance::with('employee');

            $query->whereYear('date', $request->year);
            $query->whereMonth('date', $request->month);
            $query->where('employee_id', $request->employee);

            $attendances = $query->get();

            $startOfMonth = Carbon::create($request->year, $request->month, 1);
            $endOfMonth = $startOfMonth->copy()->endOfMonth();

            $dates = $this->generateDates($startOfMonth, $endOfMonth);
            $holidays = Holiday::whereBetween('holiday_date', [$startOfMonth, $endOfMonth])->get();

            $totalPresent = $attendances->where('status', 'present')->count();
            $totalAbsent = $attendances->where('status', 'absent')->count();
            $totalRemote = $attendances->where('status', 'remote')->count();
            $totalLate = $attendances->where('status', 'late')->count();
            $totalHolidays = $holidays->count();

            $selectedDepartment = Department::where('name', $request->department)->first();
            $selectedEmployee = Employee::find($request->employee);
        } else {
            $showMessage = true;
        }

        $settings = Setting::first();

        return view('manager.attendance.query', compact(
            'departments', 'employees', 'attendances', 'holidays', 'dates', 
            'showMessage', 'totalPresent', 'totalAbsent', 'totalRemote', 
            'totalLate', 'totalHolidays', 'selectedDepartment', 'selectedEmployee' , 'settings'
        ));
    }

    private function generateDates($start, $end)
    {
        $dates = [];
        for ($date = $start->copy(); $date->lte($end); $date->addDay()) {
            $dates[] = $date->format('Y-m-d');
        }
        return $dates;
    }

    public function filterEmployees2(Request $request)
    {
        $departmentName = $request->input('department');
        $employees = Employee::where('department', $departmentName)->get();
        return response()->json(['employees' => $employees]);
    }


}
