<?php

// iyzico Checkout Form: ödeme sayfası açılır, sonuç müşterinin tarayıcısıyla geri döner,
// gelen token ile iyzico'dan ödeme durumu sorgulanır (sonuca güvenmeden doğrulanır).
function iyzico_base()
{
    return card_test_mode() ? 'https://sandbox-api.iyzipay.com' : 'https://api.iyzipay.com';
}

function iyzico_request($path, $body)
{
    $json = json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    $random = (string) round(microtime(true) * 1000) . random_int(1000, 9999);
    $signature = hash_hmac('sha256', $random . $path . $json, setting('iyzico_secret'));
    $auth = base64_encode('apiKey:' . setting('iyzico_api_key') . '&randomKey:' . $random . '&signature:' . $signature);

    $response = json_decode(http_request(iyzico_base() . $path, $json, [
        'Content-Type: application/json',
        'Accept: application/json',
        'Authorization: IYZWSv2 ' . $auth,
        'x-iyzi-rnd: ' . $random,
    ]), true);

    if (!is_array($response)) {
        throw new RuntimeException('iyzico: geçersiz cevap.');
    }
    return $response;
}

function iyzico_price($value)
{
    return rtrim(rtrim(number_format((float) $value, 2, '.', ''), '0'), '.') ?: '0';
}

function gateway_iyzico_start($order, $payment)
{
    [$first, $last] = split_name($order['name']);
    $address = $order['address'] . ' ' . $order['district'];
    $basket = payment_basket($order);
    $installments = array_values(array_filter([1, 2, 3, 6, 9, 12], fn($count) => $count <= card_max_installment()));

    $response = iyzico_request('/payment/iyzipos/checkoutform/initialize/auth/ecom', [
        'locale'              => 'tr',
        'conversationId'      => $payment['reference'],
        'price'               => iyzico_price(array_sum(array_column($basket, 'total'))),
        'paidPrice'           => iyzico_price($order['total']),
        'currency'            => 'TRY',
        'basketId'            => $payment['reference'],
        'paymentGroup'        => 'PRODUCT',
        'callbackUrl'         => url('odeme-sonuc?saglayici=iyzico'),
        'enabledInstallments' => $installments,
        'buyer'               => [
            'id'                  => 'M' . ($order['customer_id'] ?: $order['id']),
            'name'                => $first,
            'surname'             => $last,
            'gsmNumber'           => '+90' . phone_digits($order['phone']),
            'email'               => $order['email'],
            'identityNumber'      => '11111111111',
            'registrationAddress' => $address,
            'ip'                  => client_ip() ?: '127.0.0.1',
            'city'                => $order['city'],
            'country'             => 'Turkey',
        ],
        'shippingAddress' => ['contactName' => $order['name'], 'city' => $order['city'], 'country' => 'Turkey', 'address' => $address],
        'billingAddress'  => ['contactName' => $order['name'], 'city' => $order['city'], 'country' => 'Turkey', 'address' => $address],
        'basketItems'     => array_map(fn($line) => [
            'id'        => $line['id'],
            'name'      => mb_substr($line['name'], 0, 100),
            'category1' => 'Genel',
            'itemType'  => in_array($line['id'], ['KARGO', 'HIZMET'], true) ? 'VIRTUAL' : 'PHYSICAL',
            'price'     => iyzico_price($line['total']),
        ], $basket),
    ]);

    if (($response['status'] ?? '') !== 'success' || empty($response['paymentPageUrl'])) {
        throw new RuntimeException('iyzico: ' . ($response['errorMessage'] ?? 'ödeme başlatılamadı.'));
    }
    db_update('payments', ['transaction_id' => mb_substr($response['token'], 0, 100)], $payment['id']);
    return ['type' => 'redirect', 'url' => $response['paymentPageUrl']];
}

// iyzico'dan dönüş: token ile sonucu sorgular, ödeme kaydını günceller ve kaydı döner.
function gateway_iyzico_callback()
{
    $token = post('token', '');
    $payment = $token ? db_one("SELECT * FROM payments WHERE provider = 'iyzico' AND transaction_id = ?", [$token]) : null;
    if (!$payment) {
        return null;
    }

    try {
        $result = iyzico_request('/payment/iyzipos/checkoutform/auth/ecom/detail', ['locale' => 'tr', 'conversationId' => $payment['reference'], 'token' => $token]);
    } catch (Throwable $e) {
        payment_failed($payment, $e->getMessage());
        return $payment;
    }

    $raw = array_intersect_key($result, array_flip(['status', 'paymentStatus', 'paymentId', 'price', 'paidPrice', 'installment', 'basketId', 'errorMessage', 'cardAssociation', 'lastFourDigits']));
    $paid = ($result['status'] ?? '') === 'success'
        && ($result['paymentStatus'] ?? '') === 'SUCCESS'
        && ($result['basketId'] ?? '') === $payment['reference']
        // Taksit faizi nedeniyle ödenen tutar fazla olabilir ama sipariş tutarından az olamaz.
        && (float) ($result['paidPrice'] ?? 0) + 0.01 >= (float) $payment['amount'];

    $paid
        ? payment_paid($payment, $result['paymentId'] ?? $token, (int) ($result['installment'] ?? 1), $raw)
        : payment_failed($payment, $result['errorMessage'] ?? 'Ödeme tamamlanmadı.', $raw);
    return $payment;
}
