<?php
declare(strict_types=1);

namespace CronJobs;

use App\Core\Database;
use App\Core\EventBus;
use App\Core\Logger;

/**
 * Sends reminders for upcoming facility reservations.
 * Runs daily — reminds for reservations happening tomorrow.
 */
class ReservationReminderJob
{
    private Database $db;
    public function __construct(Database $db) { $this->db = $db; }

    public function shouldRun(): bool
    {
        return true; // Runs daily
    }

    public function run(): array
    {
        $tomorrow = date('Y-m-d', strtotime('+1 day'));
        $notified = 0;

        // Find confirmed reservations for tomorrow
        $reservations = $this->db->select("
            SELECT r.id, r.reservation_number, r.reservation_date, r.start_time, r.end_time,
                   r.booker_name, r.booker_phone, r.player_id, r.member_id,
                   f.name_ar AS facility_name
            FROM reservations r
            JOIN facilities f ON f.id = r.facility_id
            WHERE r.reservation_date = ?
              AND r.status = 'confirmed'
        ", [$tomorrow]);

        foreach ($reservations as $res) {
            // Resolve phone for notification
            $phone = $res['booker_phone'];
            if (!$phone && $res['player_id']) {
                $player = $this->db->selectOne("SELECT phone FROM players WHERE id = ?", [(int) $res['player_id']]);
                $phone = $player['phone'] ?? null;
            }
            if (!$phone && $res['member_id']) {
                $member = $this->db->selectOne("SELECT phone FROM members WHERE id = ?", [(int) $res['member_id']]);
                $phone = $member['phone'] ?? null;
            }

            EventBus::dispatch('reservation.reminder', [
                'reservation_id'     => (int) $res['id'],
                'reservation_number' => $res['reservation_number'],
                'facility_name'      => $res['facility_name'],
                'date'               => $res['reservation_date'],
                'start_time'         => $res['start_time'],
                'end_time'           => $res['end_time'],
                'phone'              => $phone,
            ]);
            $notified++;
        }

        Logger::info("Reservation reminders: {$notified} sent for {$tomorrow}");
        return ['date' => $tomorrow, 'reminders_sent' => $notified];
    }
}
