<?php

declare(strict_types=1);

$config = require __DIR__ . '/../config.php';
require __DIR__ . '/../lib/Db.php';
require __DIR__ . '/../lib/Billing.php';
require __DIR__ . '/../lib/Paystack.php';
require __DIR__ . '/../lib/Mnotify.php';
require __DIR__ . '/../lib/Mailer.php';

$pdo = Db::pdo($config['db']);

$args = $argv;
array_shift($args);

$opts = [];
foreach ($args as $a) {
    if (str_starts_with($a, '--') && str_contains($a, '=')) {
        [$k, $v] = explode('=', substr($a, 2), 2);
        $opts[$k] = $v;
    }
}

$task = $opts['task'] ?? 'monthly';
$month = $opts['month'] ?? date('Y-m');

function logLine(string $m): void {
    echo '[' . date('c') . '] ' . $m . PHP_EOL;
}

try {
    if ($task === 'generate') {
        $r = Billing::ensureInvoicesForMonth($pdo, $month);
        logLine('Generated invoices: ' . json_encode($r));
        exit(0);
    }

    if ($task === 'remind') {
        $channel = $opts['channel'] ?? 'sms';

        $stmt = $pdo->prepare(
            "SELECT i.id AS invoice_id, i.billing_month, i.due_date, i.amount_due, i.amount_paid,
                    (i.amount_due - i.amount_paid) AS balance,
                    l.first_name, l.last_name,
                    g.full_name AS guardian_name, g.phone AS guardian_phone, g.email AS guardian_email
             FROM invoices i
             JOIN learners l ON l.id = i.learner_id
             LEFT JOIN guardians g ON g.id = i.guardian_id
             WHERE i.billing_month = ? AND i.status IN ('unpaid','partial')"
        );
        $stmt->execute([$month]);
        $rows = $stmt->fetchAll();

        $sent = 0;
        $failed = 0;

        foreach ($rows as $r) {
            $amount = number_format((float)$r['balance'], 2);
            $learner = trim($r['first_name'] . ' ' . $r['last_name']);

            if ($channel === 'sms') {
                if (!$r['guardian_phone']) {
                    $failed++;
                    continue;
                }
                $msg = "Superb Systems Academy: Payment reminder for {$learner}. Amount due: GHS {$amount}.";
                Mnotify::sendSms($config['mnotify'], (string)$r['guardian_phone'], $msg);
                $sent++;
            } else {
                if (!$r['guardian_email']) {
                    $failed++;
                    continue;
                }
                $subject = 'Payment Reminder - Superb Systems Academy';
                $body = "<p>Payment reminder for <strong>{$learner}</strong>.</p><p>Amount due: <strong>GHS {$amount}</strong></p>";
                Mailer::send($config['email'], (string)$r['guardian_email'], $subject, $body);
                $sent++;
            }
        }

        logLine("Reminders complete. sent={$sent} failed={$failed}");
        exit(0);
    }

    logLine('Unknown task');
    exit(1);
} catch (Throwable $e) {
    logLine('Error: ' . $e->getMessage());
    exit(1);
}
