<?php

namespace App\Controllers;

class AttendanceController extends BaseController
{
    public function index(): string
    {
        $data = service('attendance')->getIndexData($this->request->getGet(), auth()->user());

        return view('attendance/index', $data);
    }

    public function new(): string
    {
        $data = service('attendance')->getFormData(auth()->user());

        return view('attendance/form', $data);
    }

    public function create()
    {
        $result = service('attendance')->saveSession($this->request->getPost(), auth()->user());

        if (! $result['success']) {
            if (! empty($result['forbidden'])) {
                return $this->forbidden('Nu poti crea sesiuni pentru aceasta grupa.');
            }

            $data = service('attendance')->getFormData(
                auth()->user(),
                $this->request->getPost(),
                $result['errors'] ?? [],
            );

            return view('attendance/form', $data);
        }

        return redirect()->to(url_to('attendance.show', $result['session_id']))->with('message', 'Sesiunea a fost creata.');
    }

    public function show(int $sessionId)
    {
        $data = service('attendance')->getSessionData($sessionId, auth()->user());

        if ($data === null) {
            return $this->forbidden('Nu ai acces la aceasta sesiune.');
        }

        return view('attendance/show', $data);
    }

    public function saveCheckIn(int $sessionId)
    {
        $result = service('attendance')->saveCheckIn($sessionId, $this->request->getPost(), auth()->user());

        if (! $result['success']) {
            if (! empty($result['forbidden'])) {
                return $this->forbidden('Nu ai acces la aceasta sesiune.');
            }

            return redirect()->to(url_to('attendance.show', $sessionId))->with('error', $result['errors']['general'] ?? 'Check-in-ul nu a putut fi salvat.');
        }

        return redirect()->to(url_to('attendance.show', $sessionId))->with('message', 'Check-in-ul a fost salvat.');
    }
}
