<?php

declare(strict_types=1);

if ($argc < 3) {
    fwrite(STDERR, "usage: php prestashop_cookie_bridge.php <mode> <bootstrap>\n");
    exit(1);
}

$mode = $argv[1];
$bootstrap = $argv[2];
$input = json_decode(stream_get_contents(STDIN), true);

if (!is_array($input)) {
    fwrite(STDERR, "invalid input\n");
    exit(1);
}

if (!is_file($bootstrap)) {
    fwrite(STDERR, "bootstrap not found\n");
    exit(1);
}

$cookieName = $input['cookie_name'] ?? null;
if (!$cookieName) {
    fwrite(STDERR, "cookie name missing\n");
    exit(1);
}

$_SERVER['HTTP_HOST'] = $_SERVER['HTTP_HOST'] ?? 'localhost';
$_SERVER['REQUEST_METHOD'] = $_SERVER['REQUEST_METHOD'] ?? 'GET';
$_SERVER['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR'] ?? '127.0.0.1';
$_COOKIE[$cookieName] = $input['raw_cookie'] ?? '';

require_once $bootstrap;

if (!class_exists('Cookie')) {
    fwrite(STDERR, "prestashop cookie class unavailable\n");
    exit(1);
}

$cookie = new Cookie($cookieName);

if ($mode !== 'decode') {
    fwrite(STDERR, "unsupported mode\n");
    exit(1);
}

$reflection = new ReflectionClass($cookie);
$content = [];
if ($reflection->hasProperty('_content')) {
    $property = $reflection->getProperty('_content');
    $property->setAccessible(true);
    $content = $property->getValue($cookie);
}

$response = [
    'customer_id' => isset($content['id_customer']) ? (int) $content['id_customer'] : null,
    'cart_id' => isset($content['id_cart']) ? (int) $content['id_cart'] : null,
    'language_id' => isset($content['id_lang']) ? (int) $content['id_lang'] : null,
    'currency_id' => isset($content['id_currency']) ? (int) $content['id_currency'] : null,
    'shop_id' => isset($content['id_shop']) ? (int) $content['id_shop'] : null,
    'guest_id' => isset($content['id_guest']) ? (int) $content['id_guest'] : null,
    'is_logged_in' => !empty($content['logged']),
    'expires_at' => null,
    'values' => array_map(static function ($value): string {
        if (is_bool($value)) {
            return $value ? '1' : '0';
        }
        if (is_scalar($value) || $value === null) {
            return (string) $value;
        }
        return json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?: '';
    }, $content),
    'raw_cookie' => $input['raw_cookie'] ?? '',
];

header('Content-Type: application/json');
echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
