<?php
declare(strict_types=1);

namespace App\Modules\PlaygroundAdmin\Controllers;

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

final class PlaygroundAttendanceController extends Controller
{
    public function __construct(Request $request)
    {
        parent::__construct($request);
    }

    public function index(Request $request, string $id): Response
    {
        $this->authorize('playground.attendance');
        $db = App::getInstance()->db();

        $playground = $db->selectOne("SELECT * FROM playground_configurations WHERE id = ?", [(int) $id]);
        if (!$playground) {
            return $this->redirect('/playgrounds')->withError('الملعب غير موجود');
        }

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

        $slots = $db->select(
            "SELECT pss.*, c.name_ar as coach_name
             FROM playground_schedule_slots pss
             INNER JOIN playground_monthly_schedules pms ON pms.id = pss.schedule_id
             LEFT JOIN coaches c ON c.id = pss.coach_id
             WHERE pms.playground_id = ? AND pss.slot_date = ? AND pms.status = 'active'
             ORDER BY pss.slot_hour, pss.row_number",
            [(int) $id, $date]
        );

        $attendance = [];
        if ($playground['grid_id']) {
            $service = new FacilityAttendanceService();
            $attendance = $service->getForGrid((int) $playground['grid_id'], $date);
        }

        return $this->view('PlaygroundAdmin.Views.attendance', [
            'playground' => $playground,
            'date' => $date,
            'slots' => $slots,
            'attendance' => $attendance,
        ]);
    }

    public function store(Request $request, string $id): Response
    {
        $this->authorize('playground.attendance');
        $db = App::getInstance()->db();

        $playground = $db->selectOne("SELECT * FROM playground_configurations WHERE id = ?", [(int) $id]);
        if (!$playground || empty($playground['grid_id'])) {
            return $this->redirect('/playgrounds/' . $id . '/attendance')->withError('لا يوجد شبكة مرتبطة بالملعب');
        }

        $data = $request->all();
        $date = $data['attendance_date'] ?? date('Y-m-d');
        $records = [];

        foreach ($data['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',
                'notes' => $entry['notes'] ?? null,
            ];
        }

        $employee = App::getInstance()->currentEmployee();
        $service = new FacilityAttendanceService();
        $count = $service->recordBatch(
            (int) $playground['grid_id'],
            $date,
            null,
            $records,
            $employee ? (int) $employee->id : null
        );

        return $this->redirect('/playgrounds/' . $id . '/attendance?date=' . $date)
            ->withSuccess("تم تسجيل {$count} حضور");
    }

    public function remind(Request $request, string $id): Response
    {
        $this->authorize('playground.attendance');
        $db = App::getInstance()->db();

        $playground = $db->selectOne("SELECT * FROM playground_configurations WHERE id = ?", [(int) $id]);

        $activeSched = $db->selectOne(
            "SELECT id FROM playground_monthly_schedules WHERE playground_id = ? AND status = 'active' LIMIT 1",
            [(int) $id]
        );

        if (!$activeSched) {
            return $this->redirect('/playgrounds/' . $id . '/attendance')->withError('لا يوجد جدول نشط');
        }

        $players = $db->select(
            "SELECT DISTINCT pss.coach_id, c.name_ar, c.phone
             FROM playground_schedule_slots pss
             INNER JOIN coaches c ON c.id = pss.coach_id
             WHERE pss.schedule_id = ? AND pss.coach_id IS NOT NULL",
            [(int) $activeSched['id']]
        );

        $count = 0;
        foreach ($players as $coach) {
            EventBus::dispatch('facility.payment_reminder', [
                'entity_type' => 'coach',
                'entity_id' => (int) $coach['coach_id'],
                'name' => $coach['name_ar'],
                'phone' => $coach['phone'],
            ]);
            $count++;
        }

        return $this->redirect('/playgrounds/' . $id . '/attendance')
            ->withSuccess("تم إرسال {$count} تذكير");
    }
}
