<?php
/**
 * CLI cron job: php api/cron/expiry_reminders.php
 *
 * Two jobs in one pass, both idempotent (safe to run as often as you like):
 *   1. Auto-expires listings whose expiry_date has passed (active -> expired),
 *      so "My Listings" and the admin panel show accurate status instead of
 *      relying only on the marketplace's implicit date filter.
 *   2. Creates a notification for active listings and pantry items expiring
 *      within REMINDER_WINDOW_DAYS — deduped per item per day.
 *
 * Suggested crontab entry (once a day is enough, but hourly is harmless
 * thanks to the same-day dedupe below):
 *   0 8 * * * /usr/bin/php /path/to/ragreen/api/cron/expiry_reminders.php >> /path/to/ragreen/storage/cron.log 2>&1
 *
 * CLI-only: this is not reachable over the web, since it has no auth check
 * of its own and isn't meant to be — it acts on every user's data.
 */

if (php_sapi_name() !== 'cli') {
    http_response_code(403);
    exit("This script can only be run from the command line.\n");
}

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/notifications.php';

const REMINDER_WINDOW_DAYS = 3;

$pdo = Database::connect();
$sent = 0;

// --- Auto-expire listings whose expiry date has passed ---
// Marketplace browsing already excludes past-expiry listings via a date filter
// (see products/list.php), but the stored status should reflect reality too —
// otherwise a seller's "My Listings" page shows a dead listing as "Active".
$expiredCount = $pdo->exec("UPDATE products SET status = 'expired' WHERE status = 'active' AND expiry_date IS NOT NULL AND expiry_date < CURDATE()");

// --- Listings expiring soon (notify the seller) ---
$stmt = $pdo->prepare("
    SELECT id, owner_id, name, expiry_date, DATEDIFF(expiry_date, CURDATE()) AS days_left
    FROM products
    WHERE status = 'active'
      AND expiry_date IS NOT NULL
      AND expiry_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL ? DAY)
");
$stmt->execute([REMINDER_WINDOW_DAYS]);
$expiringProducts = $stmt->fetchAll();

foreach ($expiringProducts as $p) {
    $marker = "(#product-{$p['id']})";

    $dedupeStmt = $pdo->prepare("
        SELECT id FROM notifications
        WHERE user_id = ? AND type = 'listing_expiry' AND message LIKE ? AND DATE(created_at) = CURDATE()
        LIMIT 1
    ");
    $dedupeStmt->execute([$p['owner_id'], "%$marker%"]);
    if ($dedupeStmt->fetch()) {
        continue; // already reminded today
    }

    $daysLeft = (int) $p['days_left'];
    $when = $daysLeft <= 0 ? 'today' : ($daysLeft === 1 ? 'tomorrow' : "in $daysLeft days");
    $message = "Your listing \"{$p['name']}\" expires $when. $marker";

    create_notification($pdo, (int) $p['owner_id'], 'listing_expiry', $message);
    $sent++;
}

// --- Pantry items expiring soon (notify the household) ---
$stmt = $pdo->prepare("
    SELECT id, user_id, product_name, expiry_date, DATEDIFF(expiry_date, CURDATE()) AS days_left
    FROM pantry_items
    WHERE expiry_date IS NOT NULL
      AND expiry_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL ? DAY)
");
$stmt->execute([REMINDER_WINDOW_DAYS]);
$expiringPantry = $stmt->fetchAll();

foreach ($expiringPantry as $item) {
    $marker = "(#pantry-{$item['id']})";

    $dedupeStmt = $pdo->prepare("
        SELECT id FROM notifications
        WHERE user_id = ? AND type = 'pantry_expiry' AND message LIKE ? AND DATE(created_at) = CURDATE()
        LIMIT 1
    ");
    $dedupeStmt->execute([$item['user_id'], "%$marker%"]);
    if ($dedupeStmt->fetch()) {
        continue;
    }

    $daysLeft = (int) $item['days_left'];
    $when = $daysLeft <= 0 ? 'today' : ($daysLeft === 1 ? 'tomorrow' : "in $daysLeft days");
    $message = "\"{$item['product_name']}\" in your pantry expires $when. $marker";

    create_notification($pdo, (int) $item['user_id'], 'pantry_expiry', $message);
    $sent++;
}

echo "Expiry reminders complete: $sent notification(s) created, $expiredCount listing(s) auto-expired.\n";
