<?php
require '../includes/config.php';
require '../endpoint/smtp_mail.php';

/* =========================
   FETCH SUBSCRIPTIONS
========================= */
$query = "
    SELECT
        s.id,
        s.company_id,
        s.plan,
        s.status,
        s.ends_at,
        s.trial_ends_at,
        s.reminder_7_sent,
        s.expired_email_sent,
        c.company_name,
        c.company_email
    FROM subscriptions s
    JOIN company c ON c.id = s.company_id
    WHERE s.status IN ('trial', 'active', 'expired')
";

$result = $conn->query($query);

while ($row = $result->fetch_assoc()) {

    /* =========================
       DETERMINE CORRECT END DATE
    ========================== */
    $endsAtRaw = ($row['plan'] === 'trial' && !empty($row['trial_ends_at']))
        ? $row['trial_ends_at']
        : $row['ends_at'];

    if (empty($endsAtRaw)) {
        continue; // safety skip
    }

    $endsAt   = new DateTime($endsAtRaw);
    $todayStr = (new DateTime())->format('Y-m-d');

    /* =========================
       7-DAY REMINDER
    ========================== */
    $remindOn = (clone $endsAt)->modify('-7 days')->format('Y-m-d');

    if (
        $todayStr === $remindOn &&
        !$row['reminder_7_sent']
    ) {

        sendExpiryReminderEmail(
            $row['company_email'],
            $row['company_name'],
            $endsAt->format('d M Y'),
            ucfirst($row['plan'])
        );

        $stmt = $conn->prepare("
            UPDATE subscriptions
            SET reminder_7_sent = 1
            WHERE id = ?
        ");
        $stmt->bind_param("i", $row['id']);
        $stmt->execute();
    }

    /* =========================
       EXPIRED CHECK
    ========================== */
    $expiredOn = $endsAt->format('Y-m-d');

    if (
        $todayStr > $expiredOn &&
        !$row['expired_email_sent']
    ) {

        sendPlanExpiredEmail(
            $row['company_email'],
            $row['company_name'],
            ucfirst($row['plan'])
        );

        $stmt = $conn->prepare("
            UPDATE subscriptions
            SET
                status = 'expired',
                expired_email_sent = 1
            WHERE id = ?
        ");
        $stmt->bind_param("i", $row['id']);
        $stmt->execute();
    }
}
