<?php

namespace App\Http\Controllers\Tenant;

use App\Enums\Weekday;
use App\Http\Controllers\Controller;
use App\Models\Employee;
use App\Models\Schedule;
use App\Support\Tenant;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ScheduleController extends Controller
{
    public function index(Request $request): View
    {
        $employees  = Employee::active()->orderBy('first_name')->get();
        $employeeId = (int) ($request->query('employee') ?? $employees->first()?->id);
        $employee   = $employees->firstWhere('id', $employeeId) ?? $employees->first();

        $schedules = [];
        if ($employee) {
            $rows = Schedule::where('employee_id', $employee->id)
                ->orderBy('weekday')
                ->orderBy('start_time')
                ->get()
                ->groupBy(fn($s) => $s->weekday->value);

            foreach (Weekday::cases() as $day) {
                $schedules[$day->value] = ($rows[$day->value] ?? collect())->map(fn($s) => [
                    'start'  => substr($s->start_time, 0, 5),
                    'end'    => substr($s->end_time,   0, 5),
                    'active' => $s->is_active,
                ])->values()->all();
            }
        }

        return view('tenant.schedules.index', compact('employees', 'employee', 'schedules'));
    }

    public function store(Request $request): RedirectResponse
    {
        $employeeId = (int) $request->input('employee_id');
        $employee   = Employee::findOrFail($employeeId);
        $companyId  = Tenant::id();

        Schedule::where('employee_id', $employeeId)->delete();

        $days    = $request->input('days', []);
        $branchId = $employee->branch_id;

        foreach ($days as $weekday => $rows) {
            foreach ((array) $rows as $row) {
                $start = trim($row['start'] ?? '');
                $end   = trim($row['end']   ?? '');
                if ($start === '' || $end === '') continue;

                Schedule::create([
                    'company_id'  => $companyId,
                    'branch_id'   => $branchId,
                    'employee_id' => $employeeId,
                    'weekday'     => (int) $weekday,
                    'start_time'  => $start,
                    'end_time'    => $end,
                    'is_active'   => isset($row['active']),
                ]);
            }
        }

        return redirect()->route('tenant.schedules.index', ['employee' => $employeeId])
            ->with('success', 'Horarios guardados correctamente.');
    }
}
