<?php
class SASubscriptionsController {
    public function index(): void {
        SuperAuth::requireLogin();
        
        $subscriptions = db()->query(
            "SELECT s.*, t.business_name, p.name as plan_name 
             FROM subscriptions s 
             JOIN tenants t ON t.id = s.tenant_id 
             JOIN plans p ON p.id = s.plan_id 
             ORDER BY s.created_at DESC"
        )->fetchAll();

        $pageTitle = 'Subscription Tracking';
        ob_start();
        include APP_ROOT . '/views/superadmin/subscriptions/index.php';
        $content = ob_get_clean();
        include APP_ROOT . '/views/superadmin/layout.php';
    }

    public function cancel(string $id): void {
        SuperAuth::requireLogin();
        Security::checkCsrf();

        db()->prepare("UPDATE subscriptions SET status='cancelled', ends_at=NOW() WHERE id=?")
           ->execute([$id]);

        flash('warning', 'Subscription cancelled successfully.');
        redirect('superadmin/subscriptions');
    }

    public function approve(string $id): void {
        SuperAuth::requireLogin();
        Security::checkCsrf();

        // Get subscription details
        $sub = db()->prepare("SELECT * FROM subscriptions WHERE id=?");
        $sub->execute([$id]);
        $subscription = $sub->fetch();

        if (!$subscription) {
            flash('error', 'Subscription not found');
            redirect('superadmin/subscriptions');
        }

        if ($subscription['status'] !== 'pending') {
            flash('error', 'Only pending subscriptions can be approved');
            redirect('superadmin/subscriptions');
        }

        // Update subscription to active and set tenant to active
        db()->prepare("UPDATE subscriptions SET status='active' WHERE id=?")
           ->execute([$id]);

        db()->prepare("UPDATE tenants SET status='active' WHERE id=?")
           ->execute([$subscription['tenant_id']]);

        flash('success', 'Subscription approved and tenant activated successfully.');
        redirect('superadmin/subscriptions');
    }
}
