<?php
/**
 * Birthday helpers – upcoming birthdays, today's birthdays, send wishes
 */

/**
 * Get members with a birthday on the given month-day (e.g. today)
 */
function getMembersWithBirthdayOn($pdo, $month, $day) {
    $stmt = $pdo->prepare('
        SELECT id, title, first_name, middle_name, last_name, date_of_birth, phone, email
        FROM members
        WHERE date_of_birth IS NOT NULL
          AND MONTH(date_of_birth) = ?
          AND DAY(date_of_birth) = ?
        ORDER BY last_name, first_name
    ');
    $stmt->execute([$month, $day]);
    return $stmt->fetchAll();
}

/**
 * Get upcoming birthdays within the next $days days (including today)
 */
function getUpcomingBirthdays($pdo, $days = 60) {
    $stmt = $pdo->query('
        SELECT id, title, first_name, middle_name, last_name, date_of_birth
        FROM members
        WHERE date_of_birth IS NOT NULL
        ORDER BY MONTH(date_of_birth), DAY(date_of_birth)
    ');
    $all = $stmt->fetchAll();
    $today = new DateTime('today');
    $result = [];
    foreach ($all as $m) {
        $dob = new DateTime($m['date_of_birth']);
        $next = new DateTime($today->format('Y') . '-' . $dob->format('m-d'));
        if ($next < $today) {
            $next->modify('+1 year');
        }
        $diff = $today->diff($next)->days;
        if ($next < $today) $diff = 0;
        if ($diff <= $days) {
            $m['next_birthday'] = $next->format('Y-m-d');
            $m['days_until'] = (int) $diff;
            $m['age'] = $next->format('Y') - $dob->format('Y');
            $result[] = $m;
        }
    }
    usort($result, function ($a, $b) {
        return $a['days_until'] <=> $b['days_until'];
    });
    return $result;
}

/**
 * Build birthday message from template. Placeholders: {name} = first name.
 * {church} is replaced with nothing so the sender ID (e.g. PCG-Naz) is the only church identifier and message space is saved.
 */
function getBirthdayMessage($template, $firstName, $churchName = null) {
    if ($template === null || $template === '') {
        return "Happy Birthday $firstName! May God's blessings be with you today and always.";
    }
    return str_replace(['{name}', '{church}'], [$firstName, ''], $template);
}

/**
 * Resolve a birthday template for a member.
 * Accepts either:
 * - string|null: single template for everyone
 * - array: day-born templates, expected keys: sun, mon, tue, wed, thu, fri, sat; optional 'fallback'
 */
function resolveBirthdayTemplateForMember($member, $messageTemplate) {
    if (!is_array($messageTemplate)) {
        return $messageTemplate; // string|null
    }

    $fallback = $messageTemplate['fallback'] ?? null;
    $dobRaw = $member['date_of_birth'] ?? null;
    if (!$dobRaw) {
        return $fallback;
    }

    try {
        $dob = new DateTime($dobRaw);
    } catch (Exception $e) {
        return $fallback;
    }

    // 0 (Sunday) ... 6 (Saturday)
    $w = (int)$dob->format('w');
    $keys = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
    $key = $keys[$w] ?? null;
    if (!$key) return $fallback;

    $tpl = $messageTemplate[$key] ?? null;
    return ($tpl !== null && $tpl !== '') ? $tpl : $fallback;
}

/**
 * Send birthday wishes to a member (SMS and/or email based on settings)
 * $messageTemplate: optional custom template (from settings); use {name} for first name.
 */
function sendBirthdayWishes($pdo, $member, $smsConfig, $emailConfig, $messageTemplate = null) {
    $name = trim(($member['title'] ?? '') . ' ' . ($member['first_name'] ?? '') . ' ' . ($member['middle_name'] ?? '') . ' ' . ($member['last_name'] ?? ''));
    $firstName = $member['first_name'] ?? $name;
    $tpl = resolveBirthdayTemplateForMember($member, $messageTemplate);
    $messageText = getBirthdayMessage($tpl, $firstName);
    $results = ['sms' => null, 'email' => null];

    if (!empty($smsConfig['enabled']) && !empty($member['phone'])) {
        require_once __DIR__ . '/sms.php';
        $smsMessage = (mb_strlen($messageText) > 160) ? mb_substr($messageText, 0, 160) : $messageText;
        $results['sms'] = sendSms($member['phone'], $smsMessage);
    }

    if (!empty($emailConfig['enabled']) && !empty($member['email'])) {
        require_once __DIR__ . '/mail.php';
        $subject = 'Happy Birthday from ' . (defined('SITE_NAME') ? SITE_NAME : 'Nazareth');
        $bodyHtml = '<p>Dear ' . htmlspecialchars($firstName) . ',</p><p>' . nl2br(htmlspecialchars($messageText)) . '</p>';
        $bodyPlain = "Dear $firstName,\n\n$messageText";
        $results['email'] = sendMail($member['email'], $subject, $bodyHtml, $bodyPlain);
    }

    return $results;
}
