@extends('layouts.admin')
@section('title', 'API Documentation')

@section('content')

{{-- Page header --}}
<div style="display:flex;align-items:flex-start;justify-content:space-between;margin-bottom:1.75rem;flex-wrap:wrap;gap:1rem">
  <div>
    <h1 style="font-size:1.25rem;font-weight:800;color:var(--foreground);letter-spacing:-.025em;margin:0 0 .25rem">
      License API Documentation
    </h1>
    <p style="font-size:.8125rem;color:var(--muted-foreground);margin:0">
      Complete reference for integrating license validation into your software products.
    </p>
  </div>
  <div style="display:flex;gap:.5rem;flex-wrap:wrap">
    <span style="display:inline-flex;align-items:center;gap:.375rem;font-size:.75rem;font-weight:600;
      padding:.3rem .75rem;border-radius:9999px;background:var(--muted);border:1px solid var(--border);color:var(--muted-foreground)">
      Base URL: <code style="font-family:monospace;color:var(--foreground)">{{ $baseUrl }}/api</code>
    </span>
    <span style="display:inline-flex;align-items:center;gap:.375rem;font-size:.75rem;font-weight:600;
      padding:.3rem .75rem;border-radius:9999px;background:#dcfce7;border:1px solid #bbf7d0;color:#16a34a">
      <svg width="10" height="10" fill="currentColor" viewBox="0 0 8 8"><circle cx="4" cy="4" r="4"/></svg>
      HMAC-SHA256 Auth
    </span>
  </div>
</div>

{{-- Two-column layout: TOC left, content right --}}
<div style="display:grid;grid-template-columns:220px 1fr;gap:1.5rem;align-items:start">

  {{-- ── Table of Contents ── --}}
  <div style="position:sticky;top:1.25rem">
    <div class="card" style="padding:1rem">
      <div style="font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.07em;
        color:var(--muted-foreground);margin-bottom:.75rem">Contents</div>
      @foreach([
        ['#overview',       'Overview'],
        ['#authentication', 'Authentication'],
        ['#signing',        'Signing Requests'],
        ['#activate',       'POST /activate'],
        ['#validate',       'POST /validate'],
        ['#heartbeat',      'POST /heartbeat'],
        ['#deactivate',     'POST /deactivate'],
        ['#check-update',   'POST /check-update'],
        ['#errors',         'Error Codes'],
        ['#rate-limiting',  'Rate Limiting'],
        ['#php-sdk',        'PHP SDK Helper'],
      ] as [$href, $label])
      <a href="{{ $href }}"
        style="display:block;padding:.3rem .5rem;font-size:.8rem;color:var(--muted-foreground);
          text-decoration:none;border-radius:.4rem;transition:all .1s"
        onmouseover="this.style.background='var(--muted)';this.style.color='var(--foreground)'"
        onmouseout="this.style.background='transparent';this.style.color='var(--muted-foreground)'">
        {{ $label }}
      </a>
      @endforeach
    </div>
  </div>

  {{-- ── Documentation content ── --}}
  <div style="display:flex;flex-direction:column;gap:1.5rem">

    @php
    $card = 'class="card" style="overflow:hidden"';
    $ch   = 'style="padding:1.125rem 1.375rem;border-bottom:1px solid var(--border);display:flex;align-items:center;gap:.75rem"';
    $cb   = 'style="padding:1.375rem"';
    $code = 'style="background:var(--muted);border:1px solid var(--border);border-radius:.65rem;padding:1.125rem 1.25rem;font-size:.76rem;font-family:monospace;color:var(--foreground);overflow-x:auto;line-height:1.75;margin:0;white-space:pre"';
    $badge = fn($m,$c) => "<span style=\"display:inline-flex;align-items:center;font-size:.65rem;font-weight:800;text-transform:uppercase;letter-spacing:.06em;padding:.2rem .55rem;border-radius:.35rem;background:{$c};\">$m</span>";
    @endphp

    {{-- ════════════════ OVERVIEW ════════════════ --}}
    <div {!! $card !!} id="overview">
      <div {!! $ch !!}>
        <svg width="16" height="16" fill="none" stroke="var(--foreground)" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.75"
            d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
        </svg>
        <span style="font-size:.9375rem;font-weight:700;color:var(--foreground)">Overview</span>
      </div>
      <div {!! $cb !!}>
        <p style="font-size:.875rem;color:var(--foreground);line-height:1.7;margin:0 0 1rem">
          The License Platform API lets your software products validate, activate, and manage licenses in real time.
          All communication is JSON over HTTPS. Every request must be cryptographically signed with the license's
          <strong>Secret Key</strong> using HMAC-SHA256 — there are no API keys or Bearer tokens.
        </p>
        <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:.875rem">
          @foreach([
            ['Base URL',      $baseUrl . '/api', '#6366f1'],
            ['Auth method',   'HMAC-SHA256 signature', '#0ea5e9'],
            ['Content-Type',  'application/json', '#f59e0b'],
            ['Rate limit',    '60 req / min / IP', '#ef4444'],
            ['Timestamp tol.','± 5 minutes', '#8b5cf6'],
            ['Nonce TTL',     '10 minutes (replay protection)', '#10b981'],
          ] as [$k, $v, $c])
          <div style="padding:.875rem;border:1px solid var(--border);border-radius:.65rem">
            <div style="font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.05em;
              color:var(--muted-foreground);margin-bottom:.375rem">{{ $k }}</div>
            <div style="font-size:.8125rem;font-weight:600;color:var(--foreground)">{{ $v }}</div>
          </div>
          @endforeach
        </div>
      </div>
    </div>

    {{-- ════════════════ AUTHENTICATION ════════════════ --}}
    <div {!! $card !!} id="authentication">
      <div {!! $ch !!}>
        <svg width="16" height="16" fill="none" stroke="var(--foreground)" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.75"
            d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/>
        </svg>
        <span style="font-size:.9375rem;font-weight:700;color:var(--foreground)">Authentication</span>
      </div>
      <div {!! $cb !!}>
        <p style="font-size:.875rem;color:var(--foreground);line-height:1.7;margin:0 0 1rem">
          Every API request requires three security fields in the JSON body:
        </p>
        <div style="display:flex;flex-direction:column;gap:.5rem;margin-bottom:1.25rem">
          @foreach([
            ['timestamp', 'integer', 'Unix timestamp (seconds). Must be within ±300 seconds of server time.'],
            ['nonce',     'string',  'Random unique string (16+ hex chars). Each nonce can only be used once within 10 minutes.'],
            ['signature', 'string',  'HMAC-SHA256 hex string computed from the payload using the license\'s secret key.'],
          ] as [$field, $type, $desc])
          <div style="display:flex;align-items:flex-start;gap:.875rem;padding:.75rem;
            background:var(--muted);border:1px solid var(--border);border-radius:.6rem">
            <code style="font-family:monospace;font-size:.8rem;font-weight:700;color:var(--foreground);
              background:var(--background);border:1px solid var(--border);border-radius:.35rem;
              padding:.15rem .45rem;white-space:nowrap;flex-shrink:0">{{ $field }}</code>
            <div>
              <span style="font-size:.72rem;font-weight:700;color:#6366f1;margin-right:.5rem">{{ $type }}</span>
              <span style="font-size:.8125rem;color:var(--muted-foreground)">{{ $desc }}</span>
            </div>
          </div>
          @endforeach
        </div>

        <div style="background:#fffbeb;border:1px solid #fde68a;border-radius:.65rem;
          padding:.875rem 1rem;font-size:.8125rem;color:#92400e;line-height:1.6">
          <strong>Where is the secret key?</strong> Each license has its own secret key.
          As an admin you can see it in <a href="{{ route('admin.licenses.index') }}"
          style="color:#92400e;font-weight:700">Admin → Licenses → [license] → API Credentials</a>.
          Customers see it in Customer Portal → Licenses → Credentials.
        </div>
      </div>
    </div>

    {{-- ════════════════ SIGNING ALGORITHM ════════════════ --}}
    <div {!! $card !!} id="signing">
      <div {!! $ch !!}>
        <svg width="16" height="16" fill="none" stroke="var(--foreground)" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.75"
            d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/>
        </svg>
        <span style="font-size:.9375rem;font-weight:700;color:var(--foreground)">Signing Requests</span>
      </div>
      <div {!! $cb !!}>
        <p style="font-size:.875rem;color:var(--foreground);line-height:1.7;margin:0 0 1rem">
          The signature is computed as follows — this must match exactly or the request is rejected:
        </p>
        <ol style="font-size:.875rem;color:var(--foreground);line-height:2;padding-left:1.375rem;margin:0 0 1.25rem">
          <li>Build the payload array with all fields <strong>including</strong> <code>timestamp</code> and <code>nonce</code>, but <strong>without</strong> <code>signature</code>.</li>
          <li>Sort the payload keys alphabetically (<code>ksort</code>).</li>
          <li>Build the message string: <code>timestamp + ":" + nonce + ":" + json_encode(sorted_payload)</code></li>
          <li>Compute: <code>signature = hash_hmac('sha256', message, secret_key)</code></li>
          <li>Add <code>signature</code> to the payload and send.</li>
        </ol>
        <pre {!! $code !!}>// PHP implementation
function signRequest(array $payload, string $secretKey): array
{
    $payload['timestamp'] = time();
    $payload['nonce']     = bin2hex(random_bytes(16));

    $data = $payload;
    ksort($data);

    $message = $payload['timestamp'] . ':' . $payload['nonce'] . ':' . json_encode($data);
    $payload['signature'] = hash_hmac('sha256', $message, $secretKey);

    return $payload;
}</pre>
      </div>
    </div>

    {{-- ════════════════ ACTIVATE ════════════════ --}}
    <div {!! $card !!} id="activate">
      <div {!! $ch !!}>
        {!! $badge('POST','#dcfce7;color:#16a34a') !!}
        <code style="font-family:monospace;font-size:.9rem;font-weight:700;color:var(--foreground)">/api/license/activate</code>
      </div>
      <div {!! $cb !!}>
        <p style="font-size:.875rem;color:var(--muted-foreground);margin:0 0 1.25rem;line-height:1.6">
          Activates a license for a domain/installation. Idempotent — re-activating the same domain returns the existing token.
        </p>

        <div style="font-size:.8rem;font-weight:700;color:var(--foreground);margin-bottom:.625rem">Request fields</div>
        <div style="overflow-x:auto;margin-bottom:1.25rem">
          <table style="width:100%;border-collapse:collapse;font-size:.8125rem">
            <thead>
              <tr style="background:var(--muted)">
                <th style="text-align:left;padding:.5rem .875rem;border:1px solid var(--border);font-weight:700">Field</th>
                <th style="text-align:left;padding:.5rem .875rem;border:1px solid var(--border);font-weight:700">Type</th>
                <th style="text-align:left;padding:.5rem .875rem;border:1px solid var(--border);font-weight:700">Required</th>
                <th style="text-align:left;padding:.5rem .875rem;border:1px solid var(--border);font-weight:700">Description</th>
              </tr>
            </thead>
            <tbody>
              @foreach([
                ['license_key',       'string',  'Yes', 'The license key (e.g. ABCD1234-EFGH5678-IJKL9012-MNOP3456)'],
                ['domain',            'string',  'Recommended', 'The domain or hostname being activated (e.g. example.com)'],
                ['installation_id',   'string',  'Recommended', 'Unique identifier for this installation (e.g. sha256 of hostname)'],
                ['machine_fingerprint','string', 'No',  'Hardware fingerprint for device-locked licenses'],
                ['server_hostname',   'string',  'No',  'Server hostname for audit logging'],
                ['os_platform',       'string',  'No',  'Operating system (e.g. Linux, Windows)'],
                ['product_version',   'string',  'No',  'Version of your product being activated'],
                ['timestamp',         'integer', 'Yes', 'Unix timestamp — see Authentication'],
                ['nonce',             'string',  'Yes', 'Unique random string — see Authentication'],
                ['signature',         'string',  'Yes', 'HMAC-SHA256 signature — see Signing Requests'],
              ] as [$f,$t,$r,$d])
              <tr>
                <td style="padding:.5rem .875rem;border:1px solid var(--border)"><code style="font-family:monospace;font-weight:600">{{ $f }}</code></td>
                <td style="padding:.5rem .875rem;border:1px solid var(--border);color:var(--muted-foreground)">{{ $t }}</td>
                <td style="padding:.5rem .875rem;border:1px solid var(--border)">
                  <span style="font-size:.7rem;font-weight:700;padding:.15rem .45rem;border-radius:9999px;
                    {{ $r==='Yes' ? 'background:#dcfce7;color:#16a34a' : ($r==='Recommended' ? 'background:#fef9c3;color:#a16207' : 'background:var(--muted);color:var(--muted-foreground)') }}">
                    {{ $r }}
                  </span>
                </td>
                <td style="padding:.5rem .875rem;border:1px solid var(--border);color:var(--muted-foreground)">{{ $d }}</td>
              </tr>
              @endforeach
            </tbody>
          </table>
        </div>

        <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;margin-bottom:1.25rem">
          <div>
            <div style="font-size:.8rem;font-weight:700;color:var(--foreground);margin-bottom:.5rem">Success Response (200)</div>
            <pre {!! $code !!}>{
  "success": true,
  "message": "activated",
  "license_key": "ABCD1234-...",
  "activation_id": "uuid-v4",
  "activation_token": "hex64chars",
  "status": "active",
  "type": "regular",
  "product": "My Product",
  "expires_at": "2026-12-31T00:00:00Z",
  "is_lifetime": false,
  "max_activations": 3,
  "activations_used": 1,
  "timestamp": 1748000000,
  "nonce": "abc123...",
  "signature": "hmac..."
}</pre>
          </div>
          <div>
            <div style="font-size:.8rem;font-weight:700;color:var(--foreground);margin-bottom:.5rem">Error Response (422)</div>
            <pre {!! $code !!}>{
  "success": false,
  "error": "MAX_ACTIVATIONS",
  "message": "Maximum activations reached."
}

// Possible error codes:
// INVALID_LICENSE
// INVALID_SIGNATURE
// MAX_ACTIVATIONS
// INVALID_DOMAIN</pre>
          </div>
        </div>

        <div style="font-size:.8rem;font-weight:700;color:var(--foreground);margin-bottom:.5rem">PHP Example</div>
        <pre {!! $code !!}>$secretKey  = 'YOUR-LICENSE-SECRET-KEY';
$licenseKey = 'ABCD1234-EFGH5678-IJKL9012-MNOP3456';

$payload = signRequest([
    'license_key'     => $licenseKey,
    'domain'          => $_SERVER['HTTP_HOST'],
    'installation_id' => hash('sha256', gethostname()),
    'product_version' => '2.1.0',
    'os_platform'     => PHP_OS,
], $secretKey);

$response = json_decode(file_get_contents(
    '{{ $baseUrl }}/api/license/activate',
    false,
    stream_context_create(['http' => [
        'method'  => 'POST',
        'header'  => "Content-Type: application/json\r\n",
        'content' => json_encode($payload),
        'timeout' => 10,
    ]])
));

if ($response && $response->success) {
    // IMPORTANT: store this token — you need it for validate, heartbeat, deactivate
    file_put_contents('license.json', json_encode([
        'activation_token' => $response->activation_token,
        'activation_id'    => $response->activation_id,
        'expires_at'       => $response->expires_at,
    ]));
    echo "Activated successfully!";
}</pre>
      </div>
    </div>

    {{-- ════════════════ VALIDATE ════════════════ --}}
    <div {!! $card !!} id="validate">
      <div {!! $ch !!}>
        {!! $badge('POST','#dcfce7;color:#16a34a') !!}
        <code style="font-family:monospace;font-size:.9rem;font-weight:700;color:var(--foreground)">/api/license/validate</code>
      </div>
      <div {!! $cb !!}>
        <p style="font-size:.875rem;color:var(--muted-foreground);margin:0 0 1.25rem;line-height:1.6">
          Validates an existing activation without changing its state. Verifies the activation integrity checksum and
          updates <code>last_validated_at</code>. Call this on each application boot or periodically.
        </p>
        <div style="font-size:.8rem;font-weight:700;color:var(--foreground);margin-bottom:.5rem">Key request fields (plus timestamp, nonce, signature)</div>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;margin-bottom:1.25rem">
          <pre {!! $code !!}>{
  "license_key":      "ABCD1234-...",
  "activation_token": "hex64...",  // preferred
  "domain":           "example.com", // alternative
  "timestamp":        1748000000,
  "nonce":            "abc123...",
  "signature":        "hmac..."
}</pre>
          <pre {!! $code !!}>// Success (200)
{
  "valid":         true,
  "license_key":   "ABCD1234-...",
  "status":        "active",
  "type":          "regular",
  "product":       "My Product",
  "expires_at":    "2026-12-31T00:00:00Z",
  "is_lifetime":   false,
  "activation_id": "uuid-v4",
  "timestamp":     1748000000,
  "signature":     "hmac..."
}
// Error codes: INVALID_LICENSE,
// INVALID_SIGNATURE, NOT_ACTIVATED,
// TAMPER_DETECTED</pre>
        </div>
        <div style="font-size:.8rem;font-weight:700;color:var(--foreground);margin-bottom:.5rem">PHP Example</div>
        <pre {!! $code !!}>$stored = json_decode(file_get_contents('license.json'), true);

$payload = signRequest([
    'license_key'      => $licenseKey,
    'activation_token' => $stored['activation_token'],
], $secretKey);

$response = apiPost('{{ $baseUrl }}/api/license/validate', $payload);

if (!$response || !$response->valid) {
    // License invalid — disable features or exit
    die('License validation failed.');
}</pre>
      </div>
    </div>

    {{-- ════════════════ HEARTBEAT ════════════════ --}}
    <div {!! $card !!} id="heartbeat">
      <div {!! $ch !!}>
        {!! $badge('POST','#dcfce7;color:#16a34a') !!}
        <code style="font-family:monospace;font-size:.9rem;font-weight:700;color:var(--foreground)">/api/license/heartbeat</code>
      </div>
      <div {!! $cb !!}>
        <p style="font-size:.875rem;color:var(--muted-foreground);margin:0 0 1.25rem;line-height:1.6">
          Lightweight ping to confirm the activation is still alive and update <code>last_heartbeat_at</code>.
          Send this periodically (recommended interval: every 24 hours as configured in admin settings).
          Also returns the current server time and expiry so your app can warn the user before expiry.
        </p>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;margin-bottom:1.25rem">
          <pre {!! $code !!}>{
  "license_key":      "ABCD1234-...",
  "activation_token": "hex64...",  // required
  "timestamp":        1748000000,
  "nonce":            "abc123...",
  "signature":        "hmac..."
}</pre>
          <pre {!! $code !!}>// Success (200)
{
  "alive":       true,
  "expires_at":  "2026-12-31T00:00:00Z",
  "server_time": "2026-06-02T10:00:00Z",
  "timestamp":   1748000000,
  "signature":   "hmac..."
}
// Error: INVALID_REQUEST, NOT_FOUND</pre>
        </div>
        <div style="font-size:.8rem;font-weight:700;color:var(--foreground);margin-bottom:.5rem">PHP Example</div>
        <pre {!! $code !!}>// Run this in a daily cron or background task
$payload = signRequest([
    'license_key'      => $licenseKey,
    'activation_token' => $stored['activation_token'],
], $secretKey);

$response = apiPost('{{ $baseUrl }}/api/license/heartbeat', $payload);

if ($response && $response->alive) {
    // Check expiry warning
    if ($response->expires_at) {
        $daysLeft = (strtotime($response->expires_at) - time()) / 86400;
        if ($daysLeft < 30) {
            showRenewalWarning((int) $daysLeft);
        }
    }
}</pre>
      </div>
    </div>

    {{-- ════════════════ DEACTIVATE ════════════════ --}}
    <div {!! $card !!} id="deactivate">
      <div {!! $ch !!}>
        {!! $badge('POST','#dcfce7;color:#16a34a') !!}
        <code style="font-family:monospace;font-size:.9rem;font-weight:700;color:var(--foreground)">/api/license/deactivate</code>
      </div>
      <div {!! $cb !!}>
        <p style="font-size:.875rem;color:var(--muted-foreground);margin:0 0 1.25rem;line-height:1.6">
          Deactivates a license from a specific domain/installation and frees up an activation slot.
          Call this when the user uninstalls your software or migrates to a new server.
          Works even if the license is expired.
        </p>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;margin-bottom:1.25rem">
          <pre {!! $code !!}>{
  "license_key":      "ABCD1234-...",
  "activation_token": "hex64...",  // preferred
  "domain":           "example.com", // alternative
  "timestamp":        1748000000,
  "nonce":            "abc123...",
  "signature":        "hmac..."
}</pre>
          <pre {!! $code !!}>// Success (200)
{
  "success":   true,
  "message":   "Activation removed.",
  "timestamp": 1748000000,
  "signature": "hmac..."
}
// Error: INVALID_REQUEST, NOT_FOUND</pre>
        </div>
        <div style="font-size:.8rem;font-weight:700;color:var(--foreground);margin-bottom:.5rem">PHP Example</div>
        <pre {!! $code !!}>// Call this from your uninstall script
$payload = signRequest([
    'license_key'      => $licenseKey,
    'activation_token' => $stored['activation_token'],
], $secretKey);

$response = apiPost('{{ $baseUrl }}/api/license/deactivate', $payload);

if ($response && $response->success) {
    @unlink('license.json'); // Remove stored token
    echo "License deactivated. You can now activate on another server.";
}</pre>
      </div>
    </div>

    {{-- ════════════════ CHECK-UPDATE ════════════════ --}}
    <div {!! $card !!} id="check-update">
      <div {!! $ch !!}>
        {!! $badge('POST','#dcfce7;color:#16a34a') !!}
        <code style="font-family:monospace;font-size:.9rem;font-weight:700;color:var(--foreground)">/api/license/check-update</code>
      </div>
      <div {!! $cb !!}>
        <p style="font-size:.875rem;color:var(--muted-foreground);margin:0 0 1.25rem;line-height:1.6">
          Checks whether a newer stable version of the product is available for the licensed user.
          Returns the latest version number, changelog, SHA-256 checksum, and a download URL if an update exists.
        </p>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem;margin-bottom:1.25rem">
          <pre {!! $code !!}>{
  "license_key":     "ABCD1234-...",
  "current_version": "2.0.1",
  "timestamp":       1748000000,
  "nonce":           "abc123...",
  "signature":       "hmac..."
}</pre>
          <pre {!! $code !!}>// Success (200)
{
  "update_available": true,
  "current_version":  "2.0.1",
  "latest_version":   "2.1.0",
  "changelog":        "- Fixed bug X\n- Added feature Y",
  "download_url":     "https://panel.../download/...",
  "checksum":         "sha256hex...",
  "timestamp":        1748000000,
  "signature":        "hmac..."
}
// No update: update_available: false,
// changelog + download_url = null</pre>
        </div>
        <div style="font-size:.8rem;font-weight:700;color:var(--foreground);margin-bottom:.5rem">PHP Example</div>
        <pre {!! $code !!}>$payload = signRequest([
    'license_key'     => $licenseKey,
    'current_version' => '2.0.1',
], $secretKey);

$response = apiPost('{{ $baseUrl }}/api/license/check-update', $payload);

if ($response && $response->update_available) {
    echo "Update available: v{$response->latest_version}\n";
    echo "Changelog:\n{$response->changelog}\n";

    // Download and verify
    $file = file_get_contents($response->download_url);
    if (hash('sha256', $file) === $response->checksum) {
        file_put_contents('update.zip', $file);
        echo "Downloaded and verified!";
    } else {
        die("Checksum mismatch — file corrupted or tampered.");
    }
}</pre>
      </div>
    </div>

    {{-- ════════════════ ERROR CODES ════════════════ --}}
    <div {!! $card !!} id="errors">
      <div {!! $ch !!}>
        <svg width="16" height="16" fill="none" stroke="var(--foreground)" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.75"
            d="M12 9v2m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/>
        </svg>
        <span style="font-size:.9375rem;font-weight:700;color:var(--foreground)">Error Codes</span>
      </div>
      <div {!! $cb !!}>
        <p style="font-size:.875rem;color:var(--muted-foreground);margin:0 0 1rem;line-height:1.6">
          All errors return HTTP 422 with <code>success: false</code>. HTTP 429 is returned for rate limit violations.
        </p>
        <table style="width:100%;border-collapse:collapse;font-size:.8125rem">
          <thead>
            <tr style="background:var(--muted)">
              <th style="text-align:left;padding:.5rem .875rem;border:1px solid var(--border);font-weight:700">Error Code</th>
              <th style="text-align:left;padding:.5rem .875rem;border:1px solid var(--border);font-weight:700">HTTP</th>
              <th style="text-align:left;padding:.5rem .875rem;border:1px solid var(--border);font-weight:700">Meaning &amp; Action</th>
            </tr>
          </thead>
          <tbody>
            @foreach([
              ['INVALID_LICENSE',    '422', 'License key does not exist, is revoked, suspended, or expired. Show "License invalid" to user.'],
              ['INVALID_SIGNATURE',  '422', 'Signature mismatch. Check your secret key and signing algorithm. Also fires if timestamp drift > 5 min.'],
              ['MAX_ACTIVATIONS',    '422', 'All activation slots are used. User must deactivate another installation first.'],
              ['INVALID_DOMAIN',     '422', 'Domain format is invalid (not a valid hostname or IP address).'],
              ['NOT_ACTIVATED',      '422', 'No active activation found for the provided token/domain. Re-activate the license.'],
              ['TAMPER_DETECTED',    '422', 'Activation checksum mismatch. The local activation record was modified. Re-activate.'],
              ['NOT_FOUND',          '422', 'Activation token not found or already deactivated.'],
              ['INVALID_REQUEST',    '422', 'Generic — missing required fields or signature invalid. Check request structure.'],
              ['TOO_MANY_REQUESTS',  '429', 'Rate limit exceeded (10 failed attempts / 5 min per IP). Wait and retry.'],
            ] as [$code, $http, $desc])
            <tr>
              <td style="padding:.5rem .875rem;border:1px solid var(--border)">
                <code style="font-family:monospace;font-weight:700;font-size:.8rem;color:#dc2626">{{ $code }}</code>
              </td>
              <td style="padding:.5rem .875rem;border:1px solid var(--border);font-weight:700;color:var(--muted-foreground)">{{ $http }}</td>
              <td style="padding:.5rem .875rem;border:1px solid var(--border);color:var(--muted-foreground)">{{ $desc }}</td>
            </tr>
            @endforeach
          </tbody>
        </table>
      </div>
    </div>

    {{-- ════════════════ RATE LIMITING ════════════════ --}}
    <div {!! $card !!} id="rate-limiting">
      <div {!! $ch !!}>
        <svg width="16" height="16" fill="none" stroke="var(--foreground)" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.75"
            d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/>
        </svg>
        <span style="font-size:.9375rem;font-weight:700;color:var(--foreground)">Rate Limiting</span>
      </div>
      <div {!! $cb !!}>
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:1rem">
          @foreach([
            ['Global (per IP)', '60 requests per minute', 'Applies to all /api/license/* endpoints combined. Returns HTTP 429 when exceeded.'],
            ['Brute force guard', '10 failed attempts / 5 min', 'Tracks failed activation attempts per IP. Triggers a security event log in admin panel.'],
            ['Nonce uniqueness', '10 minute window', 'Each nonce value can only be used once within its 10-minute TTL — prevents replay attacks.'],
            ['Timestamp tolerance', '±300 seconds (5 min)', 'Requests with a timestamp more than 5 minutes old or in the future are rejected.'],
          ] as [$title, $limit, $desc])
          <div style="padding:.875rem;border:1px solid var(--border);border-radius:.65rem">
            <div style="font-size:.8rem;font-weight:700;color:var(--foreground);margin-bottom:.25rem">{{ $title }}</div>
            <div style="font-size:.875rem;font-weight:800;color:#6366f1;margin-bottom:.375rem">{{ $limit }}</div>
            <div style="font-size:.775rem;color:var(--muted-foreground);line-height:1.55">{{ $desc }}</div>
          </div>
          @endforeach
        </div>
      </div>
    </div>

    {{-- ════════════════ PHP SDK HELPER ════════════════ --}}
    <div {!! $card !!} id="php-sdk">
      <div {!! $ch !!}>
        <svg width="16" height="16" fill="none" stroke="var(--foreground)" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.75"
            d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"/>
        </svg>
        <span style="font-size:.9375rem;font-weight:700;color:var(--foreground)">PHP SDK Helper — Complete Copy-Paste Class</span>
      </div>
      <div {!! $cb !!}>
        <p style="font-size:.875rem;color:var(--muted-foreground);margin:0 0 1.25rem;line-height:1.6">
          Drop this class into your PHP product. It handles signing, HTTP requests, token storage, and error handling.
        </p>
        <pre {!! $code !!}>&lt;?php

/**
 * License Platform SDK
 * Drop this file into your project and include it.
 * Replace BASE_URL and set your license key + secret key.
 */
class LicensePlatformSDK
{
    private string $baseUrl;
    private string $licenseKey;
    private string $secretKey;
    private string $tokenFile;

    public function __construct(string $licenseKey, string $secretKey, string $baseUrl = '{{ $baseUrl }}')
    {
        $this->licenseKey = $licenseKey;
        $this->secretKey  = $secretKey;
        $this->baseUrl    = rtrim($baseUrl, '/');
        $this->tokenFile  = sys_get_temp_dir() . '/lp_' . md5($licenseKey) . '.json';
    }

    // ── Sign + send a request ──────────────────────────────────────
    private function request(string $endpoint, array $data): ?object
    {
        $data['license_key'] = $this->licenseKey;
        $payload = $this->sign($data);

        $context = stream_context_create(['http' => [
            'method'        => 'POST',
            'header'        => "Content-Type: application/json\r\nAccept: application/json\r\n",
            'content'       => json_encode($payload),
            'timeout'       => 10,
            'ignore_errors' => true,
        ]]);

        $response = @file_get_contents($this->baseUrl . '/api/license/' . $endpoint, false, $context);
        return $response ? json_decode($response) : null;
    }

    // ── HMAC-SHA256 signing ────────────────────────────────────────
    private function sign(array $payload): array
    {
        $payload['timestamp'] = time();
        $payload['nonce']     = bin2hex(random_bytes(16));

        $data = $payload;
        ksort($data);
        $message = $payload['timestamp'] . ':' . $payload['nonce'] . ':' . json_encode($data);
        $payload['signature'] = hash_hmac('sha256', $message, $this->secretKey);

        return $payload;
    }

    // ── Activate ───────────────────────────────────────────────────
    public function activate(): ?object
    {
        $response = $this->request('activate', [
            'domain'          => $_SERVER['HTTP_HOST'] ?? gethostname(),
            'installation_id' => hash('sha256', gethostname()),
            'product_version' => defined('APP_VERSION') ? APP_VERSION : '1.0.0',
            'os_platform'     => PHP_OS,
        ]);

        if ($response && $response->success) {
            file_put_contents($this->tokenFile, json_encode([
                'activation_token' => $response->activation_token,
                'activation_id'    => $response->activation_id,
                'expires_at'       => $response->expires_at,
            ]));
        }

        return $response;
    }

    // ── Validate ───────────────────────────────────────────────────
    public function validate(): bool
    {
        $stored = $this->loadToken();
        if (!$stored) return false;

        $response = $this->request('validate', [
            'activation_token' => $stored['activation_token'],
        ]);

        return (bool) ($response->valid ?? false);
    }

    // ── Heartbeat ──────────────────────────────────────────────────
    public function heartbeat(): ?object
    {
        $stored = $this->loadToken();
        if (!$stored) return null;

        return $this->request('heartbeat', [
            'activation_token' => $stored['activation_token'],
        ]);
    }

    // ── Deactivate ─────────────────────────────────────────────────
    public function deactivate(): bool
    {
        $stored = $this->loadToken();
        if (!$stored) return false;

        $response = $this->request('deactivate', [
            'activation_token' => $stored['activation_token'],
        ]);

        if ($response && $response->success) {
            @unlink($this->tokenFile);
            return true;
        }

        return false;
    }

    // ── Check for updates ──────────────────────────────────────────
    public function checkUpdate(string $currentVersion): ?object
    {
        return $this->request('check-update', [
            'current_version' => $currentVersion,
        ]);
    }

    // ── Helper ─────────────────────────────────────────────────────
    private function loadToken(): ?array
    {
        if (!file_exists($this->tokenFile)) return null;
        return json_decode(file_get_contents($this->tokenFile), true);
    }
}

// ── Usage example ─────────────────────────────────────────────────
$sdk = new LicensePlatformSDK(
    licenseKey: 'ABCD1234-EFGH5678-IJKL9012-MNOP3456',
    secretKey:  'your-secret-key-from-license-credentials'
);

// On first install:
$result = $sdk->activate();
if (!$result || !$result->success) {
    die("Activation failed: " . ($result->message ?? 'Unknown error'));
}

// On every app boot:
if (!$sdk->validate()) {
    die("License validation failed. Please contact support.");
}

// Periodically (daily cron):
$sdk->heartbeat();

// On uninstall:
$sdk->deactivate();</pre>
      </div>
    </div>

  </div>{{-- /content column --}}
</div>

@endsection
