<?php
// Set timezone
date_default_timezone_set('Asia/Jakarta');
function signetureBlibli($storeCode, $username, $requestId, $storeId, $channelId, $time, $apiKey)
{
    // Menyusun string yang akan di-hash
    $dataToSign = "storeCode=$storeCode&username=$username&requestId=$requestId&storeId=$storeId&channelId=$channelId&signatureTime=$time";

    // Menggunakan HMAC-SHA256 untuk menghasilkan signature
    $signature = hash_hmac('sha256', $dataToSign, $apiKey, true);

    // Mengubah hasil hash menjadi base64
    $base64Signature = base64_encode($signature);

    return $base64Signature;
}
function generateUUID()
{
    // Menghasilkan byte acak
    $data = random_bytes(16);

    // Mengubah byte menjadi format UUID
    // Set bits versi UUID (versi 4) di byte tertentu
    $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // versi 4
    $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // variant 10

    // Formatkan sebagai string UUID
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
function generateBasicAuthHeader($username, $password)
{
    // Menggabungkan username dan password dalam format 'username:password'
    $credentials = base64_encode($username . ':' . $password);
    return 'Basic ' . $credentials;
}
function BlibliGetListOrder($startDate, $endDate, $storeCode, $channelId, $ApiSellerKey, $page = 0, $size = 10)
{
    $username = BLIBLI_API_ID;
    $password = BLIBLI_API_KEY;
    $storeId = BLIBLI_STORE_ID;
    $apiKey = BLIBLI_API_KEY;
    $baseUrl = BLIBLI_API_BASE_URL;
    $endPoint = '/proxy/seller/v1/orders/packages/filter';
    $uuid = generateUUID();
    $requestId =  $uuid;

    $time = time() * 1000;
    $sign = signetureBlibli($storeCode, $username, $password, $requestId, $storeId, strtolower(str_replace(' ', '-', $channelId)), $time, $apiKey);

    // Menyusun parameter untuk body request
    $filter = [
        'filter' => [
            'statusFPDateRange' => [
                'start' => $startDate,
                'end' => $endDate
            ]
        ],
        'sorting' => [
            'by' => 'statusFPUpdatedTimestamp',
            'direction' => 'DESC'
        ],
        'paging' => [
            'page' => $page,
            'size' => $size
        ],
        'orderItemStatuses' => [
            'FP',
        ],
    ];

    $authorization = generateBasicAuthHeader($username, $password);
    // Menyiapkan headers untuk request
    $headers = [
        'Api-Seller-Key: ' . $ApiSellerKey,
        'Signature: ' . $sign,
        'Signature-Time: ' . $time,
        'requestId: ' . $requestId,
        'Authorization: ' . $authorization,
        'Content-Type: application/json',
        'Accept: application/json',
    ];

    $params = [
        'storeCode' => $storeCode,
        'requestId' => $requestId,
        'storeId' => $storeId,
        'channelId' => strtolower(str_replace(' ', '-', $channelId)),
    ];

    // Menggunakan executeCurl untuk melakukan request
    return executeCurl($baseUrl, $endPoint, $params, $headers, 'POST', $filter); // Mengirim request POST
}
function BlibliFulfillOrder($orderId, $storeCode, $channelId, $ApiSellerKey, $awbNo)
{
    $username = BLIBLI_API_ID;
    $password = BLIBLI_API_KEY;
    $storeId = BLIBLI_STORE_ID;
    $apiKey = BLIBLI_API_KEY;
    $baseUrl = BLIBLI_API_BASE_URL;
    $endPoint = "/proxy/seller/v1/orders/regular/{$orderId}/fulfill";
    $uuid = generateUUID();
    $requestId = $uuid;

    $time = time() * 1000;
    $sign = signetureBlibli($storeCode, $username, $password, $requestId, $storeId, strtolower(str_replace(' ', '-', $channelId)), $time, $apiKey);

    // Menyusun body untuk request
    $body = [
        'awbNo' => $awbNo
    ];

    // Menyiapkan headers untuk request
    $headers = [
        'Api-Seller-Key: ' . $ApiSellerKey,
        'Signature: ' . $sign,
        'Signature-Time: ' . $time,
        'requestId: ' . $requestId,
        'Content-Type: application/json',
        'Accept: application/json',
    ];

    $params = [
        'requestId' => $requestId,
        'username' => $username,
        'storeId' => $storeId,
        'storeCode' => $storeCode,
        'channelId' => strtolower(str_replace(' ', '-', $channelId)),
    ];

    // Menggunakan executeCurl untuk melakukan request
    return executeCurl($baseUrl, $endPoint, $params, $headers, 'POST', $body); // Mengirim request POST
}
function BlibliGetShippingLabel($orderId, $storeCode, $channelId, $ApiSellerKey)
{
    $username = BLIBLI_API_ID;
    $password = BLIBLI_API_KEY;
    $storeId = BLIBLI_STORE_ID;
    $apiKey = BLIBLI_API_KEY;
    $baseUrl = BLIBLI_API_BASE_URL;
    $endPoint = "/proxy/seller/v1/orders/{$orderId}/shippingLabel";
    $uuid = generateUUID();
    $requestId = $uuid;

    $authorization = generateBasicAuthHeader($username, $password);

    $time = time() * 1000;
    $sign = signetureBlibli($storeCode, $username, $password, $requestId, $storeId, strtolower(str_replace(' ', '-', $channelId)), $time, $apiKey);

    // Menyiapkan headers untuk request
    $headers = [
        'Api-Seller-Key: ' . $ApiSellerKey,
        'Signature: ' . $sign,
        'Signature-Time: ' . $time,
        'requestId: ' . $requestId,
        'Authorization: ' . $authorization,
        'Content-Type: application/json',
        'Accept: application/json',
    ];

    $params = [
        'requestId' => $requestId,
        'username' => $username,
        'storeId' => $storeId,
        'storeCode' => $storeCode,
        'channelId' => strtolower(str_replace(' ', '-', $channelId)),
    ];

    // Menggunakan executeCurl untuk melakukan request
    return executeCurl($baseUrl, $endPoint, $params, $headers, 'GET'); // Mengirim request GET
}
function BlibliCreatePackage($businessPartnerCode, $channelId, $ApiSellerKey, $orderItemIdsArray)
{
    $username = BLIBLI_API_ID;
    $password = BLIBLI_API_KEY;
    $apiKey = BLIBLI_API_KEY;
    $baseUrl = BLIBLI_API_BASE_URL;
    $storeId = BLIBLI_STORE_ID;
    $endPoint = '/proxy/mta/api/businesspartner/v1/order/createPackage';
    $uuid = generateUUID();
    $requestId = $uuid;

    $time = time() * 1000;
    $sign = signetureBlibli($businessPartnerCode, $username, $password, $requestId, $storeId, strtolower(str_replace(' ', '-', $channelId)), $time, $apiKey);

    $authorization = generateBasicAuthHeader($username, $password);

    // Menyusun body untuk request
    $body = [
        'orderItemIds' => $orderItemIdsArray
    ];

    // Menyiapkan headers untuk request
    $headers = [
        'Api-Seller-Key: ' . $ApiSellerKey,
        'Signature: ' . $sign,
        'Signature-Time: ' . $time,
        'requestId: ' . $requestId,
        'Authorization: ' . $authorization,
        'Content-Type: application/json',
        'Accept: application/json',
    ];

    $params = [
        'requestId' => $requestId,
        'storeId' => $storeId,
        'businessPartnerCode' => $businessPartnerCode,
        'channelId' => strtolower(str_replace(' ', '-', $channelId)),
    ];

    // Menggunakan executeCurl untuk melakukan request
    return executeCurl($baseUrl, $endPoint, $params, $headers, 'POST', $body);
}
function BlibliGetCombineShipping($businessPartnerCode, $orderItemNo, $channelId, $ApiSellerKey)
{
    $username = BLIBLI_API_ID;
    $password = BLIBLI_API_KEY;
    $apiKey = BLIBLI_API_KEY;
    $baseUrl = BLIBLI_API_BASE_URL;
    $storeId = BLIBLI_STORE_ID;
    $endPoint = '/proxy/mta/api/businesspartner/v1/order/getCombineShipping';
    $uuid = generateUUID();
    $requestId = $uuid;

    $time = time() * 1000;
    $sign = signetureBlibli($businessPartnerCode, $username, $password, $requestId, $storeId, strtolower(str_replace(' ', '-', $channelId)), $time, $apiKey);

    // Menyiapkan headers untuk request
    $headers = [
        'Api-Seller-Key: ' . $ApiSellerKey,
        'Signature: ' . $sign,
        'Signature-Time: ' . $time,
        'requestId: ' . $requestId,
        'Content-Type: application/json',
        'Accept: application/json',
    ];

    $params = [
        'businessPartnerCode' => $businessPartnerCode,
        'requestId' => $requestId,
        'storeId' => $storeId,
        'orderItemNo' => $orderItemNo,
        'channelId' => strtolower(str_replace(' ', '-', $channelId)),
    ];

    // Menggunakan executeCurl untuk melakukan request
    return executeCurl($baseUrl, $endPoint, $params, $headers, 'GET'); // Mengirim request GET
}
function BlibliGetOrderItem($orderItemId, $storeCode, $channelId, $ApiSellerKey)
{
    $username = BLIBLI_API_ID;
    $password = BLIBLI_API_KEY;
    $storeId = BLIBLI_STORE_ID;
    $apiKey = BLIBLI_API_KEY;
    $baseUrl = BLIBLI_API_BASE_URL;
    $endPoint = "/proxy/seller/v1/orders/items/{$orderItemId}";
    $uuid = generateUUID();
    $requestId = $uuid;

    $time = time() * 1000;
    $sign = signetureBlibli($storeCode, $username, $password, $requestId, $storeId, strtolower(str_replace(' ', '-', $channelId)), $time, $apiKey);

    $authorization = generateBasicAuthHeader($username, $password);
    // Menyiapkan headers untuk request
    $headers = [
        'Api-Seller-Key: ' . $ApiSellerKey,
        'Signature: ' . $sign,
        'Signature-Time: ' . $time,
        'requestId: ' . $requestId,
        'Content-Type: application/json',
        'Accept: application/json',
        'Authorization: ' . $authorization,
    ];

    $params = [
        'requestId' => $requestId,
        'username' => $username,
        'storeId' => $storeId,
        'storeCode' => $storeCode,
        'channelId' => strtolower(str_replace(' ', '-', $channelId)),
    ];

    // Menggunakan executeCurl untuk melakukan request
    return executeCurl($baseUrl, $endPoint, $params, $headers, 'GET'); // Mengirim request GET
}
function BlibliInsertOrderData($orderArray)
{
    global $db;
    $orderItemIds = array();
    try {
        // Insert into orders table
        $orderInsertQuery = "INSERT INTO orders (
            order_sn,
            buyer_username,
            order_status,
            recipient_name,
            status
        ) VALUES (?, ?, ?, ?, ?)";

        $stmt = $db->prepare($orderInsertQuery);
        $stmt->bind_param(
            'sssss',
            $orderArray['orderItems'][0]['order']['id'],
            $orderArray['orderItems'][0]['order']['customerFullName'],
            $orderArray['orderItems'][0]['order']['itemStatus'],
            $orderArray['orderItems'][0]['order']['customerFullName'],
            'new'
        );
        $stmt->execute();

        // Get the inserted order ID
        $orderId = $db->insert_id();

        // Insert into order_detail table
        $orderDetailInsertQuery = "INSERT INTO order_detail (
            order_id,
            order_sn,
            order_item_id,
            item_name,
            model_quantity_purchased,
            model_discounted_price,
            model_original_price,
            model_sku,
            item_sku
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

        $stmtDetail = $db->prepare($orderDetailInsertQuery);

        foreach ($orderArray['orderItems'] as $orderItem) {
            $stmtDetail->bind_param(
                'isssiddss',
                $orderId,
                $orderArray['packageId'],
                $orderItem['order']['itemId'],
                $orderItem['product']['itemName'],
                $orderItem['order']['quantity'],
                $orderItem['product']['finalPrice'],
                $orderItem['product']['price'],
                $orderItem['product']['sellerSku'],
                $orderItem['product']['blibliSku']
            );
            $stmtDetail->execute();

            $orderItemIds[] = $orderItem['order']['itemId'];
        }

        // Close statements
        $stmt->close();
        $stmtDetail->close();

        return [true, $orderItemIds];
    } catch (Exception $e) {
        error_log("Error inserting order data: " . $e->getMessage());
        return [false, $orderItemIds];
    }
}
