<?php
// pages/components/plan_info.php
// Plan/Subscription Information box component (sidebar)
// All inline HTML is captured via output buffering as per project guidelines

// Inputs (for demo/dev):
//   ?customers=1234 (or ?customer_count=1234)
//   ?valid_until=2025-12-31 (any strtotime()-parsable string)

$customerCount = (int) mh_get('customers', mh_get('customer_count', 900, 'int'), 'int');

// Define tiers based on customer count
$tiers = [
    ['id' => 'free',       'label' => 'MailBeez Free',              'max' => 500],
    ['id' => 'startup',    'label' => 'Startup • 2k customers',     'max' => 2000],
    ['id' => 'business',   'label' => 'Business • 10k customers',   'max' => 10000],
    ['id' => 'enterprise', 'label' => 'Enterprise • 100k customers','max' => 100000],
];

// Pick current tier by count (first tier whose max >= count)
$currentTier = $tiers[count($tiers) - 1];
foreach ($tiers as $t) {
    if ($customerCount <= $t['max']) { $currentTier = $t; break; }
}
$tierMax = (int) ($currentTier['max'] ?? 1000);

// Valid-until date handling
$validStr = trim((string) mh_get('valid_until', '', 'string'));
$validTs  = $validStr !== '' ? @strtotime($validStr) : (time() + 12 * 86400); // default: in 12 days
$expired  = ($validTs !== false) ? ($validTs < time()) : false;
$validDate = $validTs !== false ? date('d M, Y', $validTs) : '—';

// Progress percent (clamped)
$pct = $tierMax > 0 ? max(0, min(100, (int) round(($customerCount / $tierMax) * 100))) : 0;

// Usage bar thresholds
$percLimit1 = 85; // warn (orange) at/above this percent
$percLimit2 = 99; // critical (red) at/above this percent

// Determine usage bar color class
$barColorClass = 'bg-brand';
if ($pct >= $percLimit2) {
    $barColorClass = 'bg-danger-600';
} elseif ($pct >= $percLimit1) {
    $barColorClass = 'bg-warning-500';
}

// Headline switches to upgrade callout when close to limit or expired
$nearLimit = ($pct >= $percLimit1);
$headline  = $expired || $nearLimit ? 'Upgrade Your Plan' : 'Plan details';
$plansUrl = \Components\Router::url('configuration', ['partial' => 1]);
$tabParam = \Components\Router::tabParam();
$pushUrl  = '?' . \Components\Base::h($tabParam) . '=configuration';
$iconClass = 'text-secondary/40';
if ($pct >= $percLimit2) {
    $iconClass = 'text-danger animate-pulse';
    $iconSvg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" class="shrink-0 ' . $iconClass . '"><path fill-rule="evenodd" d="M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003ZM12 8.25a.75.75 0 0 1 .75.75v3.75a.75.75 0 0 1-1.5 0V9a.75.75 0 0 1 .75-.75Zm0 8.25a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Z" clip-rule="evenodd" /></svg>';
} elseif ($pct >= $percLimit1) {
    $iconClass = 'text-warning';
    $iconSvg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" class="shrink-0 ' . $iconClass . '"><path fill-rule="evenodd" d="M2.25 12c0-5.385 4.365-9.75 9.75-9.75s9.75 4.365 9.75 9.75-4.365 9.75-9.75 9.75S2.25 17.385 2.25 12ZM12 8.25a.75.75 0 0 1 .75.75v3.75a.75.75 0 0 1-1.5 0V9a.75.75 0 0 1 .75-.75Zm0 8.25a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Z" clip-rule="evenodd" /></svg>';
} else {
    $iconSvg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" class="shrink-0 ' . $iconClass . '"><path fill-rule="evenodd" d="M12.516 2.17a.75.75 0 0 0-1.032 0 11.209 11.209 0 0 1-7.877 3.08.75.75 0 0 0-.722.515A12.74 12.74 0 0 0 2.25 9.75c0 5.942 4.064 10.933 9.563 12.348a.749.749 0 0 0 .374 0c5.499-1.415 9.563-6.406 9.563-12.348 0-1.39-.223-2.73-.635-3.985a.75.75 0 0 0-.722-.516l-.143.001c-2.996 0-5.717-1.17-7.734-3.08Zm3.094 8.016a.75.75 0 1 0-1.22-.872l-3.236 4.53L9.53 12.22a.75.75 0 0 0-1.06 1.06l2.25 2.25a.75.75 0 0 0 1.14-.094l3.75-5.25Z" clip-rule="evenodd" /></svg>';
}
$ringClass = '';
if ($pct >= $percLimit2) {
    $ringClass = 'ring-2 ring-danger-600';
} elseif ($pct >= $percLimit1) {
    $ringClass = 'ring-2 ring-warning-500';
}


ob_start();
?>
<div class="mt-2 -m-4  text-nowrap   group-data-[collapsed=true]/collapse:translate-x-2!  group-data-[collapsed=true]/collapse:-mx-2!">
    <div x-data="{ open: (function(){ try { return JSON.parse(localStorage.getItem('plan-info-open') ?? 'true'); } catch(e){ return true; } })() }" x-init="$watch('open', v => localStorage.setItem('plan-info-open', JSON.stringify(v)))"
         class="rounded-xl  bg-muted ring ring-inset ring-divider dark:bg-white/5 p-4 <?= $ringClass ?>">
        <div class="">
            <button type="button" class="flex w-full items-center justify-between text-sm font-semibold text-secondary hover:text-brand focus:outline-none" @click="if (document.documentElement.getAttribute('data-collapsed')==='true') { try { toggleCollapsed(); } catch(e) {} open = true; } else { open = !open }" :aria-expanded="open ? 'true' : 'false'">
                <span class="inline-flex items-center gap-2  group-data-[collapsed=true]/collapse:-translate-x-0.25! transition-all ">
                    <div class="size-4.5 text-center ">
                    <?= $iconSvg ?>
                    </div>
                    <span class="group-data-[collapsed=true]/collapse:hidden group-data-[collapsed=true]/collapse:w-0!"><?= \Components\Base::h($headline) ?></span>
                </span>


                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="size-4 text-secondary/70 transition-transform duration-200 group-data-[collapsed=true]/collapse:hidden" :class="open ? '-rotate-180' : ''">
                  <path fill-rule="evenodd" d="M5.23 7.21a.75.75 0 0 1 1.06.02L10 10.94l3.71-3.71a.75.75 0 1 1 1.06 1.06l-4.24 4.25a.75.75 0 0 1-1.06 0L5.21 8.29a.75.75 0 0 1 .02-1.08z" clip-rule="evenodd" />
                </svg>

            </button>
        </div>

        <div x-show="open" x-collapse x-cloak class="group-data-[collapsed=true]/collapse:hidden">
        <p class="mt-2 text-xs text-secondary/80">
            <span class="font-medium text-secondary"><?= \Components\Base::h($currentTier['label']) ?></span>
        </p>

        <div class="mt-3">
            <div class="flex items-center justify-between text-xs text-secondary/70">
                <span>Customers</span>
                <span><?= number_format($customerCount) ?> / <?= number_format($tierMax) ?></span>
            </div>
            <div class="mt-2 h-2.5 w-full overflow-hidden rounded-full bg-muted shadow-inner">
                <div class="h-full rounded-full <?= $barColorClass ?> transition-[width] duration-300" style="width: <?= (int)$pct ?>%"></div>
            </div>
        </div>

        <div class="mt-3 flex items-center justify-between text-xs">
            <span class="text-secondary/70">Valid until:</span>
            <span class="font-medium <?= $expired ? 'text-danger' : 'text-secondary' ?>"><?= \Components\Base::h($validDate) ?></span>
        </div>
<!--
        <button class="mt-4 w-full rounded-lg bg-brand px-3 py-2 text-center text-sm font-semibold text-white shadow-sm hover:opacity-90 focus:outline-none"
                hx-get="<?= $plansUrl ?>"
                hx-target="#app-container"
                hx-swap="innerHTML"
                hx-push-url="<?= $pushUrl ?>">
            See All Plans
-->
        </button>
    </div>
    </div>
</div>
<?php
// Emit buffered HTML so this component can be included or served standalone
// (If served via Router as a partial, it will render just this markup.)
echo ob_get_clean();
