<?php

namespace App\Http\Controllers\Manager;

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

class ManagerEmployeeDailyReportController 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('manager.employee.employeedailyreport', compact('reports'));
    // }
    public function index(Request $request)
    {
        $reports = \App\Models\EmployeeDailyReport::all(); // or whatever your model is
        // dd($reports); // Optional: check the output
        return view('manager.employee.employeedailyreport', compact('reports'));
    }


    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()
    {
        $employees = EmployeeDetails::all();
        return view('manager.employee.employeecalendar', compact('employees'));
    }
    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.');
        }
    }
}
