<?php
// ============================================================
//  Monthly charge reminder cron
// ============================================================
//
//  Runs daily. On each member's charge date it sends a heads-up
//  email: "PayFast will charge your card today."
//
//  Invoices are NOT created here — they are created by
//  payfast-itn.php only when PayFast confirms actual payment.
//
//  Run daily at ~6am before PayFast charges (usually midday):
//    https://…/cron/monthly-invoicing.php?secret=XXX
//
// ============================================================

require_once __DIR__ . '/_bootstrap.php';
require_once __DIR__ . '/../includes/mail.php';

$run_id = cron_begin('monthly-charge-reminder');

// Active subscriptions charging today
$due_today = db_all(
    "SELECT pt.*, m.email, m.first_name, m.business_name, m.tier, m.id AS member_id
       FROM payment_tokens pt
       JOIN members m ON m.id = pt.member_id
       WHERE pt.status = 'active'
         AND pt.next_charge_at = CURDATE()"
);

echo "  Found " . count($due_today) . " subscription(s) due today\n";

$processed = 0;
foreach ($due_today as $sub) {
    // Look up price for the email
    $plan = db_row(
        'SELECT price_cents FROM subscription_plans WHERE slug = :s AND active = 1',
        ['s' => strtolower($sub['tier'])]
    );
    $TIER_PRICES = ['Bronze'=>50000,'Silver'=>120000,'Gold'=>250000,'Platinum'=>500000,'Diamond'=>1000000];
    $price_cents = $plan ? (int)$plan['price_cents'] : ($TIER_PRICES[$sub['tier']] ?? 50000);
    $amount_display = 'R ' . number_format($price_cents / 100, 2, '.', ' ');

    mail_send(
        $sub['email'],
        'Buy Local Lowveld — your subscription renews today',
        "Hi {$sub['first_name']},\n\n" .
        "Your Buy Local Lowveld {$sub['tier']} membership subscription " .
        "of {$amount_display} will be charged to your card today.\n\n" .
        "Once the payment goes through, your invoice will appear in your dashboard:\n" .
        SITE_URL . "/member/welcome.php\n\n" .
        "If you'd like to cancel, you can do so from your dashboard before the charge processes.\n\n" .
        "— The Buy Local team\n"
    );

    echo "  ✓ reminder sent to {$sub['email']} ({$amount_display})\n";
    $processed++;
}

cron_finish($run_id, 'ok', $processed);