<?php
declare(strict_types=1);

require_once dirname(__DIR__, 2) . '/common/auth_middleware.php';
require_once dirname(__DIR__, 2) . '/common/session_store.php';

try {
    golder_require_method('POST');

    $master = golder_master_pdo();
    golder_apply_default_rate_limit($master, golder_api_rate_limit_route_key('desktop_sync'), 120, 60);

    $tokenRow = golder_auth_token($master, 'desktop_sync');
    $customerId = (int)($tokenRow['customer_id'] ?? 0);
    $customer = golder_customer_by_id($master, $customerId);
    if (!$customer) {
        golder_json_response(['status' => 'error', 'code' => 'CUSTOMER_NOT_FOUND'], 404);
    }

    $input = golder_read_json_body();
    if (!$input) {
        $input = $_POST;
    }

    $metadata = [];
    $metadataRaw = $tokenRow['metadata_json'] ?? null;
    if (is_string($metadataRaw) && trim($metadataRaw) !== '') {
        $decodedMetadata = json_decode($metadataRaw, true);
        if (is_array($decodedMetadata)) {
            $metadata = $decodedMetadata;
        }
    }

    $payloadJson = trim((string)($input['license_payload'] ?? ''));
    $signature = trim((string)($input['license_signature'] ?? ''));
    $keyId = trim((string)($input['license_key_id'] ?? golder_license_key_id()));
    $hardwareId = substr(trim((string)($metadata['hardware_id'] ?? '')), 0, 120);

    $customer = golder_enforce_customer_plan($master, $customerId) ?: $customer;
    $effective = golder_customer_effective_plan($customer);
    $licenseStatus = strtolower(trim((string)($customer['license_status'] ?? 'active')));
    $desktopExpired = golder_customer_desktop_access_expired($customer);
    $syncStatus = (string)($effective['sync_status'] ?? 'disabled');
    $webMobileEnabled = !empty($effective['web_mobile_enabled']) ? 1 : 0;
    $desktopExpiry = (string)($effective['desktop_expiry_date'] ?? '');
    $syncExpiry = (string)($effective['sync_expiry_date'] ?? '');

    $publicKey = '';
    try {
        $st = $master->prepare('SELECT public_key FROM license_public_keys WHERE key_id = :id AND is_active = 1 LIMIT 1');
        $st->execute([':id' => $keyId]);
        $publicKey = trim((string)$st->fetchColumn());
    } catch (Throwable $_ignored) {
    }

    $signatureOk = false;
    if ($payloadJson !== '' && $signature !== '') {
        $signatureOk = golder_license_verify_payload($payloadJson, $signature, $publicKey);
    }

    $freshLicense = golder_issue_customer_license($master, $customer, $hardwareId);
    $desktopValid = !in_array($licenseStatus, ['cancelled', 'suspended'], true) && !$desktopExpired;

    golder_json_response([
        'status' => 'ok',
        'valid' => $desktopValid,
        'signature_valid' => $signatureOk,
        'license_status' => $licenseStatus,
        'expired' => $desktopExpired,
        'desktop_expiry_date' => $desktopExpiry,
        'sync_expiry_date' => $syncExpiry,
        'sync_status' => $syncStatus,
        'web_mobile_enabled' => $webMobileEnabled,
        'effective_plan' => $effective,
        'fresh_license' => [
            'license_payload' => (string)$freshLicense['payload'],
            'license_signature' => (string)$freshLicense['signature'],
            'license_key_id' => (string)$freshLicense['key_id'],
            'license_public_key' => (string)$freshLicense['public_key'],
            'license_algorithm' => 'Ed25519',
            'desktop_expiry_date' => $desktopExpiry,
            'sync_expiry_date' => $syncExpiry,
            'sync_status' => $syncStatus,
            'web_mobile_enabled' => $webMobileEnabled,
            'expiry_date' => $desktopExpiry,
            'license_expiry_date' => $desktopExpiry,
        ],
    ]);
} catch (Throwable $e) {
    error_log(
        sprintf(
            '[golder api/license/verify] %s in %s:%d',
            $e->getMessage(),
            $e->getFile(),
            $e->getLine()
        )
    );
    golder_json_error(500, 'INTERNAL_SERVER_ERROR', 'License verification service failed. Check server error logs for details.');
}
