<?php
include_once __DIR__ . "/../db.php";

function hasActiveSubscription($chat_id): bool {
    global $pdo;
    $stmt = $pdo->prepare("SELECT id FROM subscriptions WHERE chat_id = ? AND status = 'active' AND expires_at > NOW() LIMIT 1");
    $stmt->execute([$chat_id]);
    return (bool)$stmt->fetchColumn();
}

function getSubscription($chat_id): ?array {
    global $pdo;
    $stmt = $pdo->prepare("SELECT * FROM subscriptions WHERE chat_id = ? AND status = 'active' AND expires_at > NOW() ORDER BY expires_at DESC LIMIT 1");
    $stmt->execute([$chat_id]);
    return $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
}

function grantSubscription($chat_id, $plan_type, $granted_by = 'admin'): void {
    global $pdo;
    $days = ['monthly' => 30, '3month' => 90, '6month' => 180, '12month' => 365];
    $d    = $days[$plan_type] ?? 30;

    $existing = getSubscription($chat_id);
    if ($existing) {
        // Extend existing active subscription
        $pdo->prepare("UPDATE subscriptions SET expires_at = DATE_ADD(expires_at, INTERVAL ? DAY) WHERE id = ?")
            ->execute([$d, $existing['id']]);
    } else {
        $pdo->prepare("INSERT INTO subscriptions (chat_id, plan_type, expires_at, granted_by) VALUES (?, ?, DATE_ADD(NOW(), INTERVAL ? DAY), ?)")
            ->execute([$chat_id, $plan_type, $d, $granted_by]);
    }
}

function cancelSubscription($chat_id): void {
    global $pdo;
    $pdo->prepare("UPDATE subscriptions SET status = 'cancelled' WHERE chat_id = ? AND status = 'active'")
        ->execute([$chat_id]);
}

function sendSubscriptionInfo($chat_id): void {
    global $config;
    $sub     = getSubscription($chat_id);
    $support = ltrim($config['support_username'] ?? '', '@');

    $planLabels = ['monthly' => '1 Month', '3month' => '3 Months', '6month' => '6 Months', '12month' => '12 Months'];
    $priceKeys  = ['monthly' => 'sub_price_monthly', '3month' => 'sub_price_3month', '6month' => 'sub_price_6month', '12month' => 'sub_price_12month'];

    if ($sub) {
        $expiry  = date('d M Y', strtotime($sub['expires_at']));
        $daysLeft = max(0, (int)ceil((strtotime($sub['expires_at']) - time()) / 86400));
        $label   = $planLabels[$sub['plan_type']] ?? $sub['plan_type'];

        $msg  = "⭐ <b>Premium Subscription Active</b>\n\n";
        $msg .= "Plan: <b>{$label}</b>\n";
        $msg .= "Expires: <b>{$expiry}</b> ({$daysLeft} days left)\n\n";
        $msg .= "✅ Unlimited diet & workout plans\n";
        $msg .= "✅ Weekly progress reports (auto)\n";
        $msg .= "✅ All free tools\n";

        $keyboard = [
            "inline_keyboard" => [
                [["text" => "🔄 Extend Subscription", "url" => "https://t.me/{$support}"]],
                [["text" => "🏠 Main Menu", "callback_data" => "main_menu"]],
            ]
        ];
    } else {
        $msg  = "⭐ <b>Go Premium</b>\n\n";
        $msg .= "Unlock unlimited access to all features:\n\n";
        foreach ($priceKeys as $type => $key) {
            $price = getSetting($key, '—');
            $msg  .= "• {$planLabels[$type]}: <b>₹{$price}</b>\n";
        }
        $msg .= "\n✅ Unlimited plan generation (no credits)\n";
        $msg .= "✅ Weekly auto progress reports\n";
        $msg .= "✅ All free tools\n\n";
        $msg .= "💳 No subscription? Use <b>credits</b> (pay per plan).";

        $keyboard = [
            "inline_keyboard" => [
                [["text" => "🌟 Subscribe Now", "url" => "https://t.me/{$support}"]],
                [["text" => "💳 Buy Credits",   "url" => "https://t.me/{$support}"]],
                [["text" => "🏠 Main Menu",      "callback_data" => "main_menu"]],
            ]
        ];
    }

    sendMessage($chat_id, $msg, $keyboard);
}
