<?php

namespace App\Models;

use App\Core\Database;
use App\Core\Cache;

/**
 * CompanySubscription Model
 * Manages active tenancies linked to subscription plans.
 */
class CompanySubscription extends BaseModel
{
    protected static string $table = 'company_subscriptions';

    /**
     * Get active subscription for a company
     */
    public static function findActiveByCompany(int $companyId): ?array
    {
        $cacheKey = "company_subscription_{$companyId}";

        return Cache::remember($cacheKey, 300, function () use ($companyId) {
            $now = date('Y-m-d H:i:s');
            return Database::selectOne(
                "SELECT cs.*, sp.name as plan_name, sp.max_sessions, sp.max_requests, 
                        sp.max_voice_requests, sp.max_ocr_requests, sp.features
                 FROM " . static::$table . " cs
                 JOIN subscription_plans sp ON cs.plan_id = sp.id
                 WHERE cs.company_id = ? 
                   AND cs.status = 'active' 
                   AND cs.starts_at <= ? 
                   AND cs.ends_at >= ?
                 LIMIT 1",
                [$companyId, $now, $now]
            ) ?: [];
        }) ?: null;
    }

    /**
     * Create or update subscription for a company
     */
    public static function subscribeCompany(int $companyId, int $planId, int $durationDays = 30, ?string $gateway = null, ?string $ref = null): string
    {
        $now = time();
        $startsAt = date('Y-m-d H:i:s', $now);
        $endsAt = date('Y-m-d H:i:s', $now + ($durationDays * 86400));

        // Deactivate previous active subscriptions
        Database::execute(
            "UPDATE " . static::$table . " SET status = 'expired' WHERE company_id = ? AND status = 'active'",
            [$companyId]
        );

        // Clear active subscription cache for the company
        Cache::delete("company_subscription_{$companyId}");

        return self::create([
            'company_id' => $companyId,
            'plan_id' => $planId,
            'status' => 'active',
            'starts_at' => $startsAt,
            'ends_at' => $endsAt,
            'payment_gateway' => $gateway,
            'subscription_ref' => $ref
        ]);
    }
}
