<?php
/**
 * Meal-time reminder cron script.
 *
 * Schedule (crontab, runs every 30 min in IST):
 *   30 * * * * php /path/to/cron_reminders.php >> /dev/null 2>&1/*
 *
 * Assumes server timezone is Asia/Kolkata (IST, UTC+5:30).
 * If your server runs UTC, add: date_default_timezone_set('Asia/Kolkata');
 */

date_default_timezone_set('Asia/Kolkata');

$config = include __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';

$now      = new DateTime();
$nowHour  = (int)$now->format('H');
$nowMin   = (int)$now->format('i');
$today    = $now->format('Y-m-d');

// Fetch users who have a saved diet plan (they opted in by generating one)
$stmt = $pdo->query("
    SELECT u.chat_id, u.first_name, u.wake_time, u.workout
    FROM users u
    INNER JOIN diet_plans dp ON dp.chat_id = u.chat_id
    WHERE u.wake_time IS NOT NULL AND u.wake_time != ''
    GROUP BY u.chat_id
");
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

foreach ($users as $user) {
    $chatId   = $user['chat_id'];
    $name     = $user['first_name'] ?? 'there';
    $wakeTime = parseWakeTime($user['wake_time']);
    if (!$wakeTime) continue;

    [$wakeHour, $wakeMin] = $wakeTime;

    // Define meal slots relative to wake time (offset in hours, label, reminder text)
    $slots = [
        ['offset' => 0,  'key' => 'breakfast',  'text' => "🌅 Good morning, <b>{$name}</b>! Time for <b>Breakfast</b>. Don't skip your first meal — it fuels your morning! 💪"],
        ['offset' => 2,  'key' => 'snack1',     'text' => "🍎 <b>Mid-morning snack time!</b> Grab a banana, nuts, or yogurt to keep energy levels up."],
        ['offset' => 4,  'key' => 'lunch',      'text' => "🍽️ <b>Lunch time!</b> Have a balanced meal with protein, carbs, and veggies. Stay consistent!"],
        ['offset' => 7,  'key' => 'snack2',     'text' => "🥜 <b>Evening snack time!</b> A light snack now will help you power through the rest of the day."],
        ['offset' => 9,  'key' => 'dinner',     'text' => "🌙 <b>Dinner time!</b> Keep it light and high in protein. Avoid heavy carbs close to bed."],
        ['offset' => 11, 'key' => 'bedtime',    'text' => "🛌 <b>Bedtime snack (optional):</b> Casein protein, a glass of milk, or a handful of almonds for overnight recovery."],
    ];

    foreach ($slots as $slot) {
        $slotHour = ($wakeHour + $slot['offset']) % 24;

        // Match if within ±15 min of the slot time
        if (!timeMatches($nowHour, $nowMin, $slotHour, $wakeMin)) continue;

        // Avoid duplicate sends for the same slot today
        $reminderKey = $today . '_' . $slot['key'];
        if (reminderAlreadySent($pdo, $chatId, $reminderKey)) continue;

        sendTelegramMessage($config['telegram_token'], $chatId, $slot['text']);
        logReminder($pdo, $chatId, $reminderKey);
    }
}

// ─── Helpers ────────────────────────────────────────────────────────────────

/**
 * Parse a time string like "6:30 AM", "07:00", "6 AM" into [hour24, minute].
 */
function parseWakeTime($raw) {
    $raw = trim($raw);
    if (preg_match('/(\d{1,2}):(\d{2})\s*(AM|PM)?/i', $raw, $m)) {
        $h = (int)$m[1];
        $min = (int)$m[2];
        if (!empty($m[3])) {
            $ampm = strtoupper($m[3]);
            if ($ampm === 'PM' && $h !== 12) $h += 12;
            if ($ampm === 'AM' && $h === 12) $h = 0;
        }
        return [$h, $min];
    }
    if (preg_match('/(\d{1,2})\s*(AM|PM)/i', $raw, $m)) {
        $h   = (int)$m[1];
        $ampm = strtoupper($m[2]);
        if ($ampm === 'PM' && $h !== 12) $h += 12;
        if ($ampm === 'AM' && $h === 12) $h = 0;
        return [$h, 0];
    }
    return null;
}

/**
 * Check if current time is within ±15 min of target [hour, min].
 */
function timeMatches($nowH, $nowM, $targetH, $targetM) {
    $nowTotal    = $nowH * 60 + $nowM;
    $targetTotal = $targetH * 60 + $targetM;
    return abs($nowTotal - $targetTotal) <= 15;
}

/**
 * Check if this reminder was already sent today.
 */
function reminderAlreadySent($pdo, $chatId, $key) {
    $stmt = $pdo->prepare("SELECT id FROM reminder_log WHERE chat_id = ? AND reminder_key = ? LIMIT 1");
    $stmt->execute([$chatId, $key]);
    return (bool)$stmt->fetch();
}

/**
 * Log a sent reminder to prevent duplicates.
 */
function logReminder($pdo, $chatId, $key) {
    $pdo->prepare("INSERT INTO reminder_log (chat_id, reminder_key) VALUES (?, ?)")->execute([$chatId, $key]);
}

/**
 * Send a message via Telegram Bot API.
 */
function sendTelegramMessage($token, $chatId, $text) {
    $url  = "https://api.telegram.org/bot{$token}/sendMessage";
    $data = ['chat_id' => $chatId, 'text' => $text, 'parse_mode' => 'HTML'];
    $ch   = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POSTFIELDS     => $data,
    ]);
    curl_exec($ch);
}
