<?php
/**
 * Plan Guard — enforces subscription limits per tenant
 */
class PlanGuard {

    private static ?array $plan    = null;
    private static ?array $features= null;

    private static function load(): void {
        if (self::$plan !== null) return;
        $tenantId = Auth::tenantId();
        $row = db()->prepare(
            "SELECT p.*, s.status as sub_status, s.current_period_end
             FROM subscriptions s
             JOIN plans p ON p.id = s.plan_id
             WHERE s.tenant_id = ? AND s.status = 'active'
             ORDER BY s.id DESC LIMIT 1"
        );
        $row->execute([$tenantId]);
        self::$plan = $row->fetch() ?: ['max_products'=>50,'max_users'=>2,'max_locations'=>1,'features'=>'{}'];
        self::$features = json_decode(self::$plan['features'] ?? '{}', true);
    }

    public static function getPlan(): array {
        self::load(); return self::$plan;
    }

    public static function hasFeature(string $feature): bool {
        self::load();
        return !empty(self::$features[$feature]);
    }

    public static function checkLimit(string $resource, int $count = 1): array {
        self::load();
        $tenantId  = Auth::tenantId();
        
        // Check if this is a feature-based resource (not a countable table)
        $featureResources = ['reports_advanced', 'inventory_advanced', 'analytics_advanced'];
        if (in_array($resource, $featureResources)) {
            // For feature-based resources, check if the feature is enabled in the plan
            $allowed = self::hasFeature($resource);
            return [
                'allowed' => $allowed,
                'limit'   => $allowed ? 1 : 0,
                'current' => $allowed ? 0 : 1,
            ];
        }
        
        $limit     = (int)(self::$plan["max_{$resource}"] ?? 0);
        if ($limit === -1) return ['allowed' => true, 'limit' => -1, 'current' => 0];

        $tableMap  = ['products' => 'products', 'users' => 'users', 'locations' => 'locations'];
        $table     = $tableMap[$resource] ?? $resource;
        $stmt      = db()->prepare("SELECT COUNT(*) FROM `{$table}` WHERE tenant_id = ? AND is_active = 1");
        $stmt->execute([$tenantId]);
        $current   = (int)$stmt->fetchColumn();

        return [
            'allowed' => ($current + $count) <= $limit,
            'limit'   => $limit,
            'current' => $current,
            'count'   => $count
        ];
    }

    public static function enforce(string $resource, int $count = 1): void {
        $check = self::checkLimit($resource, $count);
        if (!$check['allowed']) {
            http_response_code(402);
            $msg = "Plan limit reached! Your plan allows {$check['limit']} {$resource}, but you're trying to add " . ($count > 1 ? "{$count} more (bringing total to " . ($check['current'] + $count) . ")" : "another one") . ". Please upgrade your plan.";
            
            if (self::isApi()) {
                die(json_encode(['success'=>false,'message'=>$msg,'upgrade'=>true]));
            }
            
            // Fix session key to match helpers.php flash()
            $_SESSION['flash']['error'] = $msg;
            header('Location: ' . APP_URL . '/billing'); exit;
        }
    }

    private static function isApi(): bool {
        return !empty($_SERVER['HTTP_X_REQUESTED_WITH'])
            || str_contains($_SERVER['CONTENT_TYPE'] ?? '', 'json');
    }

    public static function getUsage(?int $tenantId = null): array {
        $tenantId = $tenantId ?? Auth::tenantId();
        self::load();
        $counts = [];
        foreach (['products','users','locations'] as $r) {
            $stmt = db()->prepare("SELECT COUNT(*) FROM `{$r}` WHERE tenant_id = ? AND is_active = 1");
            $stmt->execute([$tenantId]);
            $counts[$r] = (int)$stmt->fetchColumn();
        }
        return [
            'products'  => ['current' => $counts['products'],  'limit' => self::$plan['max_products']],
            'users'     => ['current' => $counts['users'],     'limit' => self::$plan['max_users']],
            'locations' => ['current' => $counts['locations'], 'limit' => self::$plan['max_locations']],
        ];
    }
}
