#!/usr/bin/env php
<?php
/**
 * Scheduled birthday wishes – run daily via cron
 * Sends SMS/email to all members with a birthday today, using Settings → Birthday messages.
 *
 * Usage: php cron/birthday-wishes.php
 * Cron example: 0 8 * * * cd /path/to/nazareth && php cron/birthday-wishes.php
 */

if (php_sapi_name() !== 'cli') {
    die('This script can only be run from the command line.');
}

$baseDir = dirname(__DIR__);
chdir($baseDir);

require_once $baseDir . '/config/app.php';
require_once $baseDir . '/config/database.php';
require_once $baseDir . '/includes/settings.php';
require_once $baseDir . '/includes/mail.php';
require_once $baseDir . '/includes/sms.php';
require_once $baseDir . '/includes/birthdays.php';
require_once $baseDir . '/includes/notifications.php';

$log = function ($message) {
    $line = date('Y-m-d H:i:s') . ' ' . $message . PHP_EOL;
    fwrite(STDERR, $line);
    $logDir = dirname(__DIR__) . '/logs';
    if (is_dir($logDir) && is_writable($logDir)) {
        @file_put_contents($logDir . '/birthday-wishes.log', $line, FILE_APPEND | LOCK_EX);
    }
};

$log('Birthday wishes cron started.');
$runId = logNotificationRunStart('birthday_wishes');

$todayMonth = (int) date('n');
$todayDay = (int) date('j');

try {
    $members = getMembersWithBirthdayOn($pdo, $todayMonth, $todayDay);
} catch (Exception $e) {
    $log('Error fetching birthdays: ' . $e->getMessage());
    exit(1);
}

if (empty($members)) {
    $log('No birthdays today. Done.');
    exit(0);
}

$log(count($members) . ' member(s) with birthday today.');

$sendSms = getSetting('birthday_sms', '1') === '1';
$sendEmail = getSetting('birthday_email', '1') === '1';
$template = [
    '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', ''),
];

$smsConfig = getSmsConfig();
$smsConfig['enabled'] = $sendSms;
$emailConfig = getSmtpConfig();
$emailConfig['enabled'] = $sendEmail;

$sent = 0;
$errors = [];

foreach ($members as $member) {
    $name = trim(($member['first_name'] ?? '') . ' ' . ($member['last_name'] ?? ''));
    if ($name === '') {
        $name = 'Member #' . (int) $member['id'];
    }
    try {
        $result = sendBirthdayWishes($pdo, $member, $smsConfig, $emailConfig, $template);
        $ok = false;
        if (!empty($result['sms']) && $result['sms']['sent']) {
            $ok = true;
            $log("  SMS sent to $name");
            logNotificationDelivery([
                'run_id' => $runId,
                'kind' => 'birthday_wishes',
                'channel' => 'sms',
                'context_key' => 'birthday:' . date('Y-m-d'),
                'recipient_member_id' => (int) $member['id'],
                'recipient_phone' => $member['phone'] ?? null,
                'recipient_name' => $name,
                'provider' => ($smsConfig['provider'] ?? null),
                'status' => 'sent',
                'error_message' => null,
            ]);
        } elseif (!empty($result['sms']) && !empty($result['sms']['error'])) {
            $errors[] = "SMS $name: " . $result['sms']['error'];
            logNotificationDelivery([
                'run_id' => $runId,
                'kind' => 'birthday_wishes',
                'channel' => 'sms',
                'context_key' => 'birthday:' . date('Y-m-d'),
                'recipient_member_id' => (int) $member['id'],
                'recipient_phone' => $member['phone'] ?? null,
                'recipient_name' => $name,
                'provider' => ($smsConfig['provider'] ?? null),
                'status' => 'failed',
                'error_message' => $result['sms']['error'],
            ]);
        }
        if (!empty($result['email']) && $result['email']['sent']) {
            $ok = true;
            $log("  Email sent to $name");
            logNotificationDelivery([
                'run_id' => $runId,
                'kind' => 'birthday_wishes',
                'channel' => 'email',
                'context_key' => 'birthday:' . date('Y-m-d'),
                'recipient_member_id' => (int) $member['id'],
                'recipient_email' => $member['email'] ?? null,
                'recipient_name' => $name,
                'provider' => 'smtp',
                'status' => 'sent',
                'error_message' => null,
            ]);
        } elseif (!empty($result['email']) && !empty($result['email']['error'])) {
            $errors[] = "Email $name: " . $result['email']['error'];
            logNotificationDelivery([
                'run_id' => $runId,
                'kind' => 'birthday_wishes',
                'channel' => 'email',
                'context_key' => 'birthday:' . date('Y-m-d'),
                'recipient_member_id' => (int) $member['id'],
                'recipient_email' => $member['email'] ?? null,
                'recipient_name' => $name,
                'provider' => 'smtp',
                'status' => 'failed',
                'error_message' => $result['email']['error'],
            ]);
        }
        if ($ok) {
            $sent++;
        }
    } catch (Exception $e) {
        $errors[] = "$name: " . $e->getMessage();
        $log("  Error for $name: " . $e->getMessage());
        logNotificationDelivery([
            'run_id' => $runId,
            'kind' => 'birthday_wishes',
            'channel' => 'sms',
            'context_key' => 'birthday:' . date('Y-m-d'),
            'recipient_member_id' => (int) $member['id'],
            'recipient_phone' => $member['phone'] ?? null,
            'recipient_name' => $name,
            'provider' => ($smsConfig['provider'] ?? null),
            'status' => 'failed',
            'error_message' => $e->getMessage(),
        ]);
    }
}

foreach ($errors as $err) {
    $log('  ' . $err);
}

$log("Birthday wishes cron finished. Sent to $sent of " . count($members) . " member(s).");
logNotificationRunFinish($runId ?? 0, 'ok', "Sent to $sent of " . count($members) . " member(s).", null);

// Test SMS so you can verify cron ran (until go-live) – remove or set BIRTHDAY_CRON_TEST_PHONE to '' in config/app.php
if (defined('BIRTHDAY_CRON_TEST_PHONE') && BIRTHDAY_CRON_TEST_PHONE !== '') {
    require_once $baseDir . '/includes/sms.php';
    $testCfg = getSmsConfig();
    $testCfg['enabled'] = true;
    $testMsg = 'Nazareth cron test: birthday job ran at ' . date('Y-m-d H:i') . '.';
    $res = sendSms(BIRTHDAY_CRON_TEST_PHONE, $testMsg);
    if ($res['sent']) {
        $log('Test SMS sent to ' . BIRTHDAY_CRON_TEST_PHONE);
    } else {
        $log('Test SMS failed: ' . ($res['error'] ?? 'unknown'));
    }
}

exit(0);
