#!/usr/bin/env php
<?php
/**
 * Scheduled event reminders – run daily via cron
 * Sends SMS/email reminders for events happening tomorrow or today (morning of).
 * Uses message templates (Phase 1) if available, or default format.
 *
 * Usage: php cron/event-reminders.php
 * Cron example: 0 7 * * * cd /path/to/nazareth && php cron/event-reminders.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/templates.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 . '/event-reminders.log', $line, FILE_APPEND | LOCK_EX);
    }
};

$log('Event reminders cron started.');
$runId = logNotificationRunStart('event_reminders');

try {
    // Ensure reminder columns exist
    try {
        $pdo->query("SELECT reminder_enabled FROM events LIMIT 1");
    } catch (PDOException $e) {
        if (strpos($e->getMessage(), 'Unknown column') !== false) {
            $pdo->exec("ALTER TABLE events ADD COLUMN reminder_enabled TINYINT(1) DEFAULT 0");
            $pdo->exec("ALTER TABLE events ADD COLUMN reminder_when ENUM('day_before', 'morning_of') DEFAULT 'day_before'");
            $pdo->exec("ALTER TABLE events ADD COLUMN reminder_recipient_type ENUM('all', 'groups') DEFAULT 'all'");
            $pdo->exec("ALTER TABLE events ADD COLUMN reminder_group_ids TEXT NULL");
            $pdo->exec("ALTER TABLE events ADD COLUMN reminder_sent_at DATETIME NULL");
        }
    }

    $today = date('Y-m-d');
    $tomorrow = date('Y-m-d', strtotime('+1 day'));
    $currentHour = (int) date('H');

    // Find events that need reminders:
    // - reminder_enabled = 1
    // - reminder_sent_at IS NULL (not yet sent)
    // - (reminder_when = 'day_before' AND event_date = tomorrow) OR (reminder_when = 'morning_of' AND event_date = today AND current hour >= 7)
    $events = [];
    $stmt = $pdo->prepare("
        SELECT id, title, description, event_date, event_time, location,
               reminder_when, reminder_recipient_type, reminder_group_ids
        FROM events
        WHERE reminder_enabled = 1
          AND reminder_sent_at IS NULL
          AND (
              (reminder_when = 'day_before' AND event_date = ?)
              OR (reminder_when = 'morning_of' AND event_date = ? AND ? >= 7)
          )
    ");
    $stmt->execute([$tomorrow, $today, $currentHour]);
    $events = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (empty($events)) {
        $log('No events need reminders today. Done.');
        exit(0);
    }

    $log(count($events) . ' event(s) need reminders.');

    $sendSms = getSetting('event_reminder_sms', '1') === '1';
    $sendEmail = getSetting('event_reminder_email', '1') === '1';

    // Try to get template, fallback to default
    $smsTemplate = getTemplateByName('Event reminder SMS');
    $emailTemplate = getTemplateByName('Event reminder Email');

    $sent = 0;
    $errors = [];

    foreach ($events as $event) {
        $eventId = (int) $event['id'];
        $eventDate = $event['event_date'];
        $eventTime = $event['event_time'] ? date('g:i A', strtotime($event['event_time'])) : '';
        $eventTitle = $event['title'];
        $eventLocation = $event['location'] ?? '';
        $contextKey = 'event:' . $eventId;

        // Get recipients
        $recipients = [];
        if ($event['reminder_recipient_type'] === 'all') {
            $stmt = $pdo->query("SELECT id, first_name, last_name, phone, email FROM members WHERE phone IS NOT NULL OR email IS NOT NULL");
            $recipients = $stmt->fetchAll(PDO::FETCH_ASSOC);
        } else {
            $groupIds = json_decode($event['reminder_group_ids'], true) ?: [];
            if (!empty($groupIds)) {
                $placeholders = str_repeat('?,', count($groupIds) - 1) . '?';
                $stmt = $pdo->prepare("
                    SELECT DISTINCT m.id, m.first_name, m.last_name, m.phone, m.email
                    FROM members m
                    JOIN group_members gm ON m.id = gm.member_id
                    WHERE gm.group_id IN ($placeholders)
                      AND (m.phone IS NOT NULL OR m.email IS NOT NULL)
                ");
                $stmt->execute($groupIds);
                $recipients = $stmt->fetchAll(PDO::FETCH_ASSOC);
            }
        }

        if (empty($recipients)) {
            $log("  Event '$eventTitle': No recipients found.");
            continue;
        }

        $log("  Event '$eventTitle': Sending to " . count($recipients) . " recipient(s).");

        $eventSent = 0;
        foreach ($recipients as $member) {
            $memberName = trim(($member['first_name'] ?? '') . ' ' . ($member['last_name'] ?? ''));
            if ($memberName === '') {
                $memberName = 'Member #' . (int) $member['id'];
            }

            $context = [
                'member_name' => $memberName,
                'event_title' => $eventTitle,
                'event_date' => date('l, F j, Y', strtotime($eventDate)),
                'event_time' => $eventTime,
                'event_location' => $eventLocation,
                'date' => date('Y-m-d'),
                'church_name' => SITE_NAME,
            ];

            // SMS
            if ($sendSms && !empty($member['phone'])) {
                if ($smsTemplate) {
                    $smsBody = replaceTemplatePlaceholders($smsTemplate['body'], $context);
                } else {
                    $smsBody = "Reminder: $eventTitle on " . date('M j', strtotime($eventDate));
                    if ($eventTime) {
                        $smsBody .= " at $eventTime";
                    }
                    if ($eventLocation) {
                        $smsBody .= " ($eventLocation)";
                    }
                }
                $result = sendSms($member['phone'], $smsBody);
                if ($result['sent']) {
                    $eventSent++;
                    logNotificationDelivery([
                        'run_id' => $runId,
                        'kind' => 'event_reminders',
                        'channel' => 'sms',
                        'context_key' => $contextKey,
                        'recipient_member_id' => (int) $member['id'],
                        'recipient_phone' => $member['phone'],
                        'recipient_name' => $memberName,
                        'provider' => (getSmsConfig()['provider'] ?? null),
                        'status' => 'sent',
                        'error_message' => null,
                    ]);
                } elseif (!empty($result['error'])) {
                    $errors[] = "SMS $memberName: " . $result['error'];
                    logNotificationDelivery([
                        'run_id' => $runId,
                        'kind' => 'event_reminders',
                        'channel' => 'sms',
                        'context_key' => $contextKey,
                        'recipient_member_id' => (int) $member['id'],
                        'recipient_phone' => $member['phone'],
                        'recipient_name' => $memberName,
                        'provider' => (getSmsConfig()['provider'] ?? null),
                        'status' => 'failed',
                        'error_message' => $result['error'],
                    ]);
                }
            }

            // Email
            if ($sendEmail && !empty($member['email'])) {
                if ($emailTemplate) {
                    $emailSubject = replaceTemplatePlaceholders($emailTemplate['subject'] ?? 'Event Reminder', $context);
                    $emailBody = replaceTemplatePlaceholders($emailTemplate['body'], $context);
                } else {
                    $emailSubject = "Reminder: $eventTitle";
                    $emailBody = "<p>Dear $memberName,</p>";
                    $emailBody .= "<p>This is a reminder about the upcoming event:</p>";
                    $emailBody .= "<p><strong>$eventTitle</strong><br>";
                    $emailBody .= "Date: " . date('l, F j, Y', strtotime($eventDate)) . "<br>";
                    if ($eventTime) {
                        $emailBody .= "Time: $eventTime<br>";
                    }
                    if ($eventLocation) {
                        $emailBody .= "Location: $eventLocation<br>";
                    }
                    $emailBody .= "</p>";
                    $emailBody .= "<p>We look forward to seeing you there!</p>";
                }
                $result = sendMail($member['email'], $emailSubject, $emailBody);
                if ($result['sent']) {
                    $eventSent++;
                    logNotificationDelivery([
                        'run_id' => $runId,
                        'kind' => 'event_reminders',
                        'channel' => 'email',
                        'context_key' => $contextKey,
                        'recipient_member_id' => (int) $member['id'],
                        'recipient_email' => $member['email'],
                        'recipient_name' => $memberName,
                        'provider' => 'smtp',
                        'status' => 'sent',
                        'error_message' => null,
                    ]);
                } elseif (!empty($result['error'])) {
                    $errors[] = "Email $memberName: " . $result['error'];
                    logNotificationDelivery([
                        'run_id' => $runId,
                        'kind' => 'event_reminders',
                        'channel' => 'email',
                        'context_key' => $contextKey,
                        'recipient_member_id' => (int) $member['id'],
                        'recipient_email' => $member['email'],
                        'recipient_name' => $memberName,
                        'provider' => 'smtp',
                        'status' => 'failed',
                        'error_message' => $result['error'],
                    ]);
                }
            }
        }

        if ($eventSent > 0) {
            // Mark reminder as sent
            $pdo->prepare("UPDATE events SET reminder_sent_at = NOW() WHERE id = ?")->execute([$eventId]);
            $sent++;
            $log("  Event '$eventTitle': Reminders sent.");
        }

        // PWA push notifications removed (will be rebuilt later)
    }

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

    $log("Event reminders cron finished. Processed $sent of " . count($events) . " event(s).");
    logNotificationRunFinish($runId ?? 0, 'ok', "Processed $sent of " . count($events) . " event(s).", null);
    exit(0);
} catch (Exception $e) {
    $log('Error: ' . $e->getMessage());
    logNotificationRunFinish($runId ?? 0, 'error', null, $e->getMessage());
    exit(1);
}
