<?php
/**
 * Send birthday messages automatically (run daily via cron).
 * Usage: php cron/birthday-messages.php
 * Or via HTTP (optional): GET /nazareth/cron/birthday-messages.php?key=YOUR_SECRET
 * Set BIRTHDAY_CRON_KEY in config or leave empty to allow CLI-only.
 */

// Run from CLI or with secret key via HTTP
$isCli = php_sapi_name() === 'cli';
if (!$isCli) {
    $key = $_GET['key'] ?? '';
    $expected = defined('BIRTHDAY_CRON_KEY') ? BIRTHDAY_CRON_KEY : '';
    if ($expected !== '' && $key !== $expected) {
        http_response_code(403);
        exit('Forbidden');
    }
}

$base = dirname(__DIR__);
require_once $base . '/config/app.php';
require_once $base . '/config/database.php';
require_once $base . '/includes/settings.php';
require_once $base . '/includes/birthdays.php';
require_once $base . '/includes/mail.php';
require_once $base . '/includes/sms.php';

$birthdaySms = getSetting('birthday_sms', '1') === '1';
$birthdayEmail = getSetting('birthday_email', '1') === '1';
$birthdayTemplate = [
    'sun' => getSetting('birthday_message_template_sun', ''),
    'mon' => getSetting('birthday_message_template_mon', ''),
    'tue' => getSetting('birthday_message_template_tue', ''),
    'wed' => getSetting('birthday_message_template_wed', ''),
    'thu' => getSetting('birthday_message_template_thu', ''),
    'fri' => getSetting('birthday_message_template_fri', ''),
    'sat' => getSetting('birthday_message_template_sat', ''),
    'fallback' => getSetting('birthday_message_template', ''),
];
$smsCfg = $birthdaySms ? getSmsConfig() : ['enabled' => false];
$emailCfg = $birthdayEmail ? getSmtpConfig() : ['enabled' => false];

$todayMonth = (int) date('n');
$todayDay = (int) date('j');
$members = getMembersWithBirthdayOn($pdo, $todayMonth, $todayDay);

$sent = 0;
foreach ($members as $m) {
    $r = sendBirthdayWishes($pdo, $m, $smsCfg, $emailCfg, $birthdayTemplate);
    if (($r['sms'] && $r['sms']['sent']) || ($r['email'] && $r['email']['sent'])) {
        $sent++;
    }
}

if ($isCli) {
    echo date('Y-m-d H:i:s') . " Birthday messages: $sent sent to " . count($members) . " member(s).\n";
} else {
    header('Content-Type: application/json');
    echo json_encode(['sent' => $sent, 'members' => count($members)]);
}
