<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\DailyAttendance;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use App\Services\AttendanceComputer;

class ReportController extends Controller
{
    public function daily(Request $request, AttendanceComputer $computer)
    {
        [$from, $to, $rows] = $this->computeRange($request, $computer);

        return view('reports.daily', [
            'rows' => $rows,
            'from' => $from,
            'to' => $to,
        ]);
    }

    public function dailyExport(Request $request, AttendanceComputer $computer)
    {
        [$from, $to, $rows] = $this->computeRange($request, $computer);

        $filename = "daily-attendance-{$from}-to-{$to}.csv";

        return response()->streamDownload(function () use ($rows) {
            $out = fopen('php://output', 'w');
            fputcsv($out, ['emp_id', 'name', 'date', 'first_in', 'last_out', 'worked_minutes', 'late', 'early_out', 'status']);

            foreach ($rows as $row) {
                fputcsv($out, [
                    $row->employee->emp_id,
                    $row->employee->name,
                    $row->date->toDateString(),
                    $row->first_in?->format('Y-m-d H:i:s'),
                    $row->last_out?->format('Y-m-d H:i:s'),
                    $row->worked_minutes,
                    $row->late ? 'yes' : 'no',
                    $row->early_out ? 'yes' : 'no',
                    $row->status,
                ]);
            }

            fclose($out);
        }, $filename, ['Content-Type' => 'text/csv']);
    }

    protected function computeRange(Request $request, AttendanceComputer $computer): array
    {
        $from = $request->query('from', Carbon::today()->toDateString());
        $to = $request->query('to', Carbon::today()->toDateString());

        $fromDate = Carbon::parse($from)->startOfDay();
        $toDate = Carbon::parse($to)->startOfDay();

        $cursor = $fromDate->copy();
        while ($cursor->lte($toDate)) {
            $computer->computeForDate($cursor);
            $cursor->addDay();
        }

        $rows = DailyAttendance::with('employee')
            ->whereBetween('date', [$fromDate->toDateString(), $toDate->toDateString()])
            ->orderBy('date')
            ->orderBy('employee_id')
            ->get();

        return [$from, $to, $rows];
    }
}
