<?php
declare(strict_types=1);

namespace App\Modules\FacilityGrids\Controllers;

use App\Core\Controller;
use App\Core\App;
use App\Core\Request;
use App\Core\Response;
use App\Modules\FacilityGrids\Services\FacilityAttendanceService;

final class FacilityAttendanceController extends Controller
{
    private FacilityAttendanceService $attendanceService;

    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->attendanceService = new FacilityAttendanceService();
    }

    public function index(Request $request, string $gridId): Response
    {
        $this->authorize('facility_grid.manage');

        $date = $request->get('date', date('Y-m-d'));
        $hourSlot = $request->get('hour');

        $records = $this->attendanceService->getForGrid((int) $gridId, $date, $hourSlot);

        $db = App::getInstance()->db();
        $coaches = $db->select(
            "SELECT DISTINCT fzs.coach_id, c.name_ar
             FROM facility_zone_schedules fzs
             INNER JOIN facility_grid_zones fgz ON fgz.id = fzs.zone_id
             INNER JOIN coaches c ON c.id = fzs.coach_id
             WHERE fgz.grid_id = ? AND fzs.is_active = 1",
            [(int) $gridId]
        );

        $trainees = $db->select(
            "SELECT DISTINCT fzt.player_id, p.name_ar
             FROM facility_zone_trainees fzt
             INNER JOIN facility_grid_zones fgz ON fgz.id = fzt.zone_id
             INNER JOIN players p ON p.id = fzt.player_id
             WHERE fgz.grid_id = ? AND fzt.is_active = 1",
            [(int) $gridId]
        );

        return $this->view('FacilityGrids.Views.facility_attendance', [
            'grid_id' => (int) $gridId,
            'date' => $date,
            'hour_slot' => $hourSlot,
            'records' => $records,
            'coaches' => $coaches,
            'trainees' => $trainees,
        ]);
    }

    public function store(Request $request, string $gridId): Response
    {
        $this->authorize('facility_grid.manage');

        $body = $_POST;
        $date = $body['attendance_date'] ?? date('Y-m-d');
        $hourSlot = !empty($body['hour_slot']) ? $body['hour_slot'] : null;
        $records = [];

        foreach ($body['attendance'] ?? [] as $entry) {
            $records[] = [
                'entity_type' => $entry['entity_type'],
                'entity_id' => (int) $entry['entity_id'],
                'entity_name' => $entry['entity_name'] ?? null,
                'status' => $entry['status'] ?? 'present',
                'check_in_time' => $entry['check_in_time'] ?? null,
                'notes' => $entry['notes'] ?? null,
            ];
        }

        $employee = App::getInstance()->currentEmployee();
        $count = $this->attendanceService->recordBatch(
            (int) $gridId,
            $date,
            $hourSlot,
            $records,
            $employee ? (int) $employee->id : null
        );

        return $this->redirect('/facility-grids/' . $gridId . '/attendance?date=' . $date)
            ->withSuccess("تم تسجيل الحضور بنجاح ({$count} سجل)");
    }

    public function report(Request $request, string $gridId): Response
    {
        $this->authorize('facility_grid.view');

        $dateFrom = $request->get('from', date('Y-m-01'));
        $dateTo = $request->get('to', date('Y-m-t'));

        $report = $this->attendanceService->getReport((int) $gridId, $dateFrom, $dateTo);

        return $this->view('FacilityGrids.Views.attendance_report', [
            'grid_id' => (int) $gridId,
            'date_from' => $dateFrom,
            'date_to' => $dateTo,
            'report' => $report,
        ]);
    }

    public function remind(Request $request, string $gridId): Response
    {
        $this->authorize('facility_grid.manage');

        $count = $this->attendanceService->sendPaymentReminders((int) $gridId);

        return $this->redirect('/facility-grids/' . $gridId . '/attendance')
            ->withSuccess("تم إرسال {$count} تذكير بالدفع");
    }
}
