<?php
$dotenv = parse_ini_file('.env');

header('Content-Type: application/json');

class AppleMapKitTokenGenerator {
    private $privateKeyPath;
    private $keyId;
    private $teamId;
    private $domain;
    
    public function __construct($privateKeyPath, $keyId, $teamId, $domain) {
        $this->privateKeyPath = $privateKeyPath;
        $this->keyId = $keyId;
        $this->teamId = $teamId;
        $this->domain = $domain;
    }
    
    public function generateToken() {
        if (!file_exists($this->privateKeyPath)) {
            throw new Exception('Private key file not found');
        }
        
        $privateKey = file_get_contents($this->privateKeyPath);
        if (!$privateKey) {
            throw new Exception('Unable to read private key file');
        }
        
        $header = [
            'alg' => 'ES256',
            'kid' => $this->keyId,
            'typ' => 'JWT'
        ];
        
        $payload = [
            'iss' => $this->teamId,
            'iat' => time(),
            'exp' => time() + 3600 * 24 * 365, // 1 year
            'origin' => $this->domain
        ];
        
        $headerJson = json_encode($header);
        $payloadJson = json_encode($payload);
        
        $headerBase64 = $this->base64UrlEncode($headerJson);
        $payloadBase64 = $this->base64UrlEncode($payloadJson);
        
        $dataToSign = $headerBase64 . '.' . $payloadBase64;
        
        $privateKeyResource = openssl_pkey_get_private($privateKey);
        if (!$privateKeyResource) {
            throw new Exception('Unable to parse private key');
        }
        
        openssl_sign($dataToSign, $signature, $privateKeyResource, OPENSSL_ALGO_SHA256);
        
        $signatureBase64 = $this->base64UrlEncode($signature);
        $token = $dataToSign . '.' . $signatureBase64;
        
        return $token;
    }
    
    private function base64UrlEncode($data) {
        $base64 = base64_encode($data);
        $base64Url = strtr($base64, '+/', '-_');
        return rtrim($base64Url, '=');
    }
}

try {
    if (!isset($dotenv['APPLE_PRIVATE_KEY_PATH']) || 
        !isset($dotenv['APPLE_KEY_ID']) || 
        !isset($dotenv['APPLE_TEAM_ID'])) {
        throw new Exception('Apple API configuration missing in .env file');
    }
    
    $privateKeyPath = $dotenv['APPLE_PRIVATE_KEY_PATH'];
    $keyId = $dotenv['APPLE_KEY_ID'];
    $teamId = $dotenv['APPLE_TEAM_ID'];
    $domain = $_SERVER['HTTP_HOST'];
    
    $tokenGenerator = new AppleMapKitTokenGenerator($privateKeyPath, $keyId, $teamId, $domain);
    $token = $tokenGenerator->generateToken();
    
    echo json_encode([
        'success' => true,
        'token' => $token
    ]);
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>