<?php
declare(strict_types=1);

function midtrans_snap_token(PDO $pdo, array $order, array $items): ?string {
    $serverKey = (string) envv('MIDTRANS_SERVER_KEY', '');
    $isProduction = (bool) envv('MIDTRANS_IS_PRODUCTION', false);

    if ($serverKey === '') {
        return null;
    }

    $autoload = dirname(__DIR__, 2) . '/vendor/autoload.php';

    if (!is_file($autoload)) {
        return null;
    }

    require_once $autoload;

    \Midtrans\Config::$serverKey = $serverKey;
    \Midtrans\Config::$isProduction = $isProduction;
    \Midtrans\Config::$isSanitized = true;
    \Midtrans\Config::$is3ds = true;

    $itemDetails = [];

    foreach ($items as $item) {
        $itemDetails[] = [
            'id' => (string)$item['product_id'],
            'price' => (int)$item['price'],
            'quantity' => (int)$item['qty'],
            'name' => substr((string)$item['product_name'], 0, 50),
        ];
    }

    if ((int)$order['shipping_cost'] > 0) {
        $itemDetails[] = [
            'id' => 'SHIPPING',
            'price' => (int)$order['shipping_cost'],
            'quantity' => 1,
            'name' => 'Ongkir',
        ];
    }

    if ((int)$order['discount'] > 0) {
        $itemDetails[] = [
            'id' => 'DISCOUNT',
            'price' => -1 * (int)$order['discount'],
            'quantity' => 1,
            'name' => 'Diskon',
        ];
    }

    $params = [
        'transaction_details' => [
            'order_id' => $order['order_code'],
            'gross_amount' => (int)$order['total'],
        ],
        'customer_details' => [
            'first_name' => $order['customer_name'],
            'email' => $order['customer_email'] ?: 'customer@example.com',
            'phone' => $order['customer_phone'],
        ],
        'item_details' => $itemDetails,
    ];

    return \Midtrans\Snap::getSnapToken($params);
}
