<?php

namespace App\Modules\Dashboard\Controllers;

use App\Core\BaseApiController;
use App\Modules\Auth\Services\AuthService;
use App\Modules\Dashboard\Services\DashboardScheduleService;
use CodeIgniter\HTTP\ResponseInterface;

/**
 * Dashboard Schedule Controller
 *
 * API for today's schedules (role-filtered).
 */
class DashboardScheduleController extends BaseApiController
{
    protected DashboardScheduleService $scheduleService;
    protected AuthService $authService;

    public function __construct()
    {
        $this->scheduleService = new DashboardScheduleService();
        $this->authService    = new AuthService();
    }

    /**
     * GET /api/dashboard/schedules/today
     *
     * Returns today's schedules (day_of_week from Asia/Jakarta) filtered by current user role.
     *
     * @return ResponseInterface
     */
    public function today(): ResponseInterface
    {
        $userContext = $this->authService->currentUser();
        $schedules   = $this->scheduleService->getSchedulesToday($userContext);

        return $this->successResponse($schedules, 'Today\'s schedules');
    }

    /**
     * GET /api/dashboard/schedules/by-date?date=YYYY-MM-DD
     *
     * Schedules for the given date (day_of_week from date in Asia/Jakarta). Role-filtered.
     *
     * @return ResponseInterface
     */
    public function byDate(): ResponseInterface
    {
        $date = $this->request->getGet('date');
        if ($date === null || $date === '') {
            return $this->errorResponse('Query parameter date is required (Y-m-d)', null, null, 422);
        }
        $dt = \DateTimeImmutable::createFromFormat('Y-m-d', $date);
        if ($dt === false || $dt->format('Y-m-d') !== $date) {
            return $this->errorResponse('Invalid date format. Use Y-m-d.', null, null, 422);
        }
        $userContext = $this->authService->currentUser();
        $schedules   = $this->scheduleService->getSchedulesByDate($date, $userContext);
        return $this->successResponse($schedules, 'Schedules for date');
    }

    /**
     * GET /api/dashboard/schedules/current
     *
     * Current lesson (active now) or next upcoming today. Asia/Jakarta. Role-filtered.
     *
     * @return ResponseInterface
     */
    public function current(): ResponseInterface
    {
        $userContext = $this->authService->currentUser();
        $data       = $this->scheduleService->getCurrentSchedule($userContext);

        return $this->successResponse($data, 'Current schedule');
    }
}
