<?php
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../models/NotificationSchedule.php';
require_once __DIR__ . '/../helpers/NotificationHelper.php';

$database = new Database();
$db = $database->getConnection();

$notificationSchedule = new NotificationSchedule($db);
$pending = $notificationSchedule->getPending();

foreach ($pending as $n) {
    $title = "";
    $message = "";
    $data = [
        "click_action" => "FLUTTER_NOTIFICATION_CLICK",
        "reservation_id" => (string) $n['booking_id'],
        "type" => $n['type']
    ];

    if ($n['type'] === 'ENTRY_REMINDER') {
        $title = "Entrada em breve";
        // Check stay type for message content
        // Note: We'd need stay_type in the query if we wanted to be perfectly precise here, 
        // but for now we follow the general pattern.
        $message = "Faltam 15 min para a sua entrada em " . $n['guesthouse_name'] . ".";
        if (strpos($n['guesthouse_name'], 'Hotel') !== false || strpos($n['guesthouse_name'], 'Lodge') !== false) {
            $message = "A sua entrada em " . $n['guesthouse_name'] . " será possível dentro de 1 hora.";
        }
        $data['deep_link'] = "esquinaki://reservation/" . $n['booking_id'];
    } else {
        $title = "Saída próxima";
        $message = "A sua estadia em " . $n['guesthouse_name'] . " termina em 15 min. Deseja prolongar?";
        if (strpos($n['guesthouse_name'], 'Hotel') !== false || strpos($n['guesthouse_name'], 'Lodge') !== false) {
            $title = "Saída programada";
            $message = "A sua saída de " . $n['guesthouse_name'] . " está prevista para daqui a 3 horas.";
        }
        $data['deep_link'] = "esquinaki://reservation/" . $n['booking_id'] . "/extend";
    }

    echo "Sending notification for booking " . $n['booking_id'] . " to " . $n['user_name'] . "... ";

    $res = NotificationHelper::sendPush($n['fcm_token'], $title, $message, $data);

    if ($res) {
        $notificationSchedule->markAsSent($n['id']);
        echo "Sent.\n";
    } else {
        echo "Failed.\n";
    }
}
