<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\EmployeeDailyReport;
use App\Models\EmployeeDetails;
use App\Models\EmployeeAttendance;
use App\Models\EmployeeLeave;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use Illuminate\Support\Facades\DB;

class SuperAdminEmployeeDailyReportController extends Controller
{
    // public function index(Request $request)
    // {
    //     $reports = EmployeeDailyReport::when($request->date, function ($query) use ($request) {
    //         return $query->where('date', $request->date);
    //     })->orderBy('date', 'desc')->get();

    //     return view('superadmin.employee.employeedailyreport', compact('reports'));
    // }
    public function index(Request $request)
    {
       // Get filter values (defaults to today)
    $date = $request->input('date', date('Y-m-d'));
    $department = $request->input('department');
    $employeeId = $request->input('employee_id');

    // Employees list for filter and table
    $employeesQuery = EmployeeDetails::query();
    if ($department) {
        $employeesQuery->where('department', $department);
    }
    if ($employeeId) {
        $employeesQuery->where('id', $employeeId);
    }
    $employees = $employeesQuery->orderBy('employee_id')->get();

    // For dropdown filter
    $departments = EmployeeDetails::distinct()->pluck('department')->filter()->values();
    
    // Attendance for selected date
    $attendanceData = EmployeeAttendance::whereDate('date', $date)
        ->when($department, fn($q) => $q->where('department', $department))
        ->when($employeeId, fn($q) => $q->where('employee_id', $employees->first()?->employee_id))
        ->get();

    // Leave for selected date (for range leaves, checks if date is inside the leave range)
    $leaveData = EmployeeLeave::whereDate('leave_from', '<=', $date)
        ->whereDate('leave_to', '>=', $date)
        ->when($department, function ($q) use ($department) {
            $q->where('department', $department);
        })
        ->when($employeeId, function ($q) use ($employeeId) {
            $emp = EmployeeDetails::find($employeeId);
            if ($emp) $q->where('employee_id', $emp->id);
        })
        ->get();

    return view('superadmin.employee.employeedailyreport', [
        'attendanceData' => $attendanceData,
        'leaveData'      => $leaveData,
        'employees'      => $employees,
        'departments'    => $departments,
    ]);
       
    }


    public function store(Request $request)
    {
        $data = $request->all();
        EmployeeDailyReport::create($data);
        return response()->json(['status' => 'success']);
    }

    public function update(Request $request, $id)
    {
        $data = $request->all();
        EmployeeDailyReport::findOrFail($id)->update($data);
        return response()->json(['status' => 'updated']);
    }
    public function edit($id)
    {
        $report = EmployeeDailyReport::findOrFail($id);
        return response()->json($report);
    }
   
public function calendarView(Request $request)
{
    $employees = \App\Models\EmployeeDetails::orderBy('employee_id')->get();
    $employeeId = $request->input('employee_id');
    $month = $request->input('month', date('Y-m'));
    $attendanceMap = [];
    $attendanceDetails = [];
    $otHours = 0;
    $shortageHours = 0;
    $attendanceData = collect();
    $holidayMap = [];

    if ($employeeId) {
        $employee = $employees->where('employee_id', $employeeId)->first();
        if ($employee) {
            $start = \Carbon\Carbon::parse($month . '-01');
            $end = $start->copy()->endOfMonth();

            // Key attendance by exact string date (Y-m-d)
            $attendance = \App\Models\EmployeeAttendance::where('employee_id', $employeeId)
                ->whereBetween('date', [$start->toDateString(), $end->toDateString()])
                ->get()
                ->keyBy(function($row) {
                    return \Carbon\Carbon::parse($row->date)->format('Y-m-d');
                });

            $attendanceData = $attendance->values(); // For summary

            // Build attendance details for calendar display
            foreach ($attendance as $date => $record) {
                $attendanceDetails[$date] = [
                    'check_in' => $record->check_in ? \Carbon\Carbon::parse($record->check_in)->format('H:i') : null,
                    'check_out' => $record->check_out ? \Carbon\Carbon::parse($record->check_out)->format('H:i') : null,
                    'break_out' => $record->break_out ? \Carbon\Carbon::parse($record->break_out)->format('H:i') : null,
                    'break_in' => $record->break_in ? \Carbon\Carbon::parse($record->break_in)->format('H:i') : null,
                    'working_hours' => $record->working_hours,
                    'ot_hours' => $record->ot_hours,
                    'shortage_hours' => $record->shortage_hours,
                    'shift' => $record->shift,
                    'first_half' => $record->first_half,
                    'second_half' => $record->second_half,
                    'late_in' => $record->late_in,
                    'early_out' => $record->early_out,
                ];
            }

            // Get holidays for the month
            $holidays = \App\Models\Holiday::whereBetween('date', [$start->toDateString(), $end->toDateString()])
                ->get()
                ->keyBy(function($row) {
                    return \Carbon\Carbon::parse($row->date)->format('Y-m-d');
                });

            // Build holiday map for view
            foreach ($holidays as $date => $holiday) {
                $holidayMap[$date] = $holiday->name;
            }

            // Leaves
            $leaves = \App\Models\EmployeeLeave::where('employee_id', $employee->id)
                ->where('status', 'Approved')
                ->where(function($q) use ($start, $end) {
                    $q->whereBetween('leave_from', [$start, $end])
                      ->orWhereBetween('leave_to', [$start, $end])
                      ->orWhere(function ($q2) use ($start, $end) {
                          $q2->where('leave_from', '<', $start)
                             ->where('leave_to', '>', $end);
                      });
                })
                ->get();

            $leaveDates = [];
            foreach ($leaves as $leave) {
                $leaveFrom = \Carbon\Carbon::parse($leave->leave_from);
                $leaveTo = \Carbon\Carbon::parse($leave->leave_to);
                for ($ld = $leaveFrom->copy(); $ld->lte($leaveTo); $ld->addDay()) {
                    $leaveDates[$ld->format('Y-m-d')] = [
                        'type' => strtoupper($leave->leave_type),
                        'duration' => $leave->duration_type ?? 'Full Day',
                        'half_type' => $leave->half_type ?? null,
                    ];
                }
            }

            /**
             * PRIORITY ORDER (highest to lowest):
             * 1. ATTENDANCE (check_in + check_out exists) - actual work happened
             * 2. HOLIDAY (public holiday) - only if no attendance
             * 3. LEAVE (approved leave) - only if no attendance and not a holiday
             * 4. SUNDAY (weekly off) - only if none of the above
             * 5. ABSENT (working day with no attendance/leave)
             */
            for ($d = $start->copy(); $d->lte($end); $d->addDay()) {
                $date = $d->toDateString();
                $isSunday = $d->dayOfWeek === 0; // 0 = Sunday
                $isHoliday = isset($holidays[$date]);
                $hasAttendance = isset($attendance[$date]) && $attendance[$date]->check_in && $attendance[$date]->check_out;
                $hasLeave = isset($leaveDates[$date]);

                // Default status
                $status = 'Absent';

                // Priority 1: Attendance takes highest priority - actual work happened
                if ($hasAttendance) {
                    $status = 'Present';
                }
                // Priority 2: Holiday (only if no attendance)
                elseif ($isHoliday) {
                    $status = 'Holiday';
                }
                // Priority 3: Leave (only if no attendance and not holiday)
                elseif ($hasLeave) {
                    $leaveType = $leaveDates[$date]['type'];
                    $status = $leaveType === 'LOP' ? 'LOP' : $leaveType;
                }
                // Priority 4: Sunday (only if no attendance, no holiday, no leave)
                elseif ($isSunday) {
                    $status = 'Sunday';
                }
                // Priority 5: Absent (working day with no attendance/leave/holiday)
                // else $status remains 'Absent'

                $attendanceMap[$date] = $status;
            }

            // OT & Shortage Hours
            $otHours = round($attendanceData->sum('ot_hours'), 2);
            $shortageHours = round($attendanceData->sum('shortage_hours'), 2);
        }
    }

    return view('superadmin.employee.employeecalendar', compact(
        'employees', 'attendanceMap', 'attendanceDetails', 'month', 'employeeId', 'otHours', 'shortageHours', 'attendanceData', 'holidayMap'
    ));
}


    
    public function calendar($employeeId, $month)
{
    $date = \Carbon\Carbon::parse($month . '-01');

    // 1. Fetch daily report records for calendar events
    $dailyRecords = DB::table('employee_daily_reports')
        ->where('employee_id', $employeeId)
        ->whereMonth('date', $date->month)
        ->whereYear('date', $date->year)
        ->get();

    $days = $dailyRecords->map(function ($item) {
        $status = 'Absent';
        if ($item->first_half === 'Present' || $item->second_half === 'Present') {
            $status = 'Present';
        } elseif ($item->hourly_paid_leave || $item->hourly_unpaid_leave) {
            $status = 'Leave';
        }

        return [
            'date' => $item->date,
            'status' => $status,
        ];
    });

    // 2. Fetch summary data from attendance table
    $summaryRecords = DB::table('employee_attendances')
        ->where('employee_id', $employeeId)
        ->whereMonth('month_year', $date->month)
        ->whereYear('month_year', $date->year)
        ->get();

    $summary = [
        'days_worked' => $summaryRecords->sum('days_worked'),
        'sundays_eligible' => $summaryRecords->sum('sundays_eligible'),
        'holiday_count' => $summaryRecords->sum('holidays'),
        'earned_leave' => 0,
        'enjoy_leave_count' => $summaryRecords->sum('leave_enjoyed'),
        'balance_leave_count' => 0,
        'total_paid_days' => $summaryRecords->sum('total_paid_days'),
        'absent_count' => $summaryRecords->sum('absent'),
        'first_shift_count' => $summaryRecords->sum('first_shifts'),
        'night_shift_count' => $summaryRecords->sum('night_shifts'),
        'ot_hours' => $summaryRecords->sum('ot_hours'),
        'shortage_hours' => $summaryRecords->sum('shortage_hours'),
    ];

    return response()->json([
        'days' => $days,
        'summary' => $summary,
    ]);
}



    public function destroy($id)
    {
        EmployeeDailyReport::findOrFail($id)->delete();
        return response()->json(['status' => 'deleted']);
    }

    public function import(Request $request)
    {
        if (!$request->hasFile('import_file')) {
            return back()->with('error', 'No file uploaded.');
        }

        $file = $request->file('import_file');

        try {
            $spreadsheet = IOFactory::load($file->getPathname());
            $sheet = $spreadsheet->getActiveSheet();
            $rows = $sheet->toArray();

            foreach ($rows as $index => $row) {
                if ($index === 0) continue; // Skip header row

                // Ensure row has 19 columns
                if (count($row) < 19) continue;

                EmployeeDailyReport::create([
                    'date' => $row[0],
                    'employee_id' => $row[1],
                    'shift' => $row[2],
                    'in_spfid_1' => $row[3],
                    'out_spfid_1' => $row[4],
                    'in_spfid_2' => $row[5],
                    'out_spfid_2' => $row[6],
                    'first_half' => $row[7],
                    'second_half' => $row[8],
                    'late_in' => $row[9],
                    'early_out' => $row[10],
                    'hourly_paid_leave' => $row[11],
                    'hourly_unpaid_leave' => $row[12],
                    'over_time' => $row[13],
                    'auth_ot' => $row[14],
                    'auth_coff' => $row[15],
                    'work_hours' => $row[16],
                    'man_entry' => $row[17],
                    'reason' => $row[18],
                ]);
            }

            return back()->with('success', 'Imported successfully');
        } catch (\Exception $e) {
            Log::error('Import error: ' . $e->getMessage());
            return back()->with('error', 'Failed to import file.');
        }
    }
}
