<?php
require_once __DIR__ . '/../sdk/Constants.php';
require_once __DIR__ . '/../sdk/LazopClient.php';
require_once __DIR__ . '/../sdk/LazopLogger.php';
require_once __DIR__ . '/../sdk/LazopRequest.php';
require_once __DIR__ . '/../sdk/UrlConstants.php';
// Set timezone
date_default_timezone_set('Asia/Jakarta');

use Picqer\Barcode\BarcodeGeneratorPNG;

function LazadaReadyToShip($accessToken, $packages)
{
    $url = LAZADA_BASE_ID_URL; // Pastikan konstanta ini sudah didefinisikan
    $appkey = LAZADA_APP_KEY; // Pastikan konstanta ini sudah didefinisikan
    $appSecret = LAZADA_APP_SECRET; // Pastikan konstanta ini sudah didefinisikan

    $c = new LazopClient($url, $appkey, $appSecret);
    $request = new LazopRequest('/order/package/rts', 'POST');

    // Buat parameter `readyToShipReq` dari input
    $readyToShipReq = json_encode([
        'packages' => $packages
    ]);

    // Tambahkan parameter ke request
    $request->addApiParam('readyToShipReq', $readyToShipReq);

    // Eksekusi permintaan API
    $response = $c->execute($request, $accessToken);

    // Decode respons ke array
    $responseData = json_decode($response, true);

    // Cek apakah ada kesalahan dalam respons
    if (isset($responseData['code']) && $responseData['code'] !== '0') {
        throw new Exception("Error: " . $responseData['message']);
    }

    // Kembalikan data
    return $responseData['result'] ?? [];
}

function LazadaAuth($code)
{
    $url = LAZADA_BASE_URL;
    $appkey = LAZADA_APP_KEY;
    $appSecret = LAZADA_APP_SECRET;
    $c = new LazopClient($url, $appkey, $appSecret);
    $request = new LazopRequest('/auth/token/create');
    $request->addApiParam('code', $code);

    return json_decode($c->execute($request), true);
}

function InsertAuthToken($data)
{
    global $db;
    $shop_id = $data['country_user_info'][0]['seller_id'];
    $platform_id = 4; // Sesuaikan dengan ID platform (misalnya Lazada = 1)
    $shop_name = $data['account'];
    $refresh_token = $data['refresh_token'];
    $access_token = $data['access_token'];
    $expire_in = $data['expires_in'];

    // Periksa apakah data dengan shop_id dan platform_id sudah ada
    $checkSql = "SELECT COUNT(*) as count FROM shop WHERE shop_id = ? AND platform_id = ?";
    $checkStmt = $db->prepare($checkSql);
    $checkStmt->bind_param('ii', $shop_id, $platform_id);
    $checkStmt->execute();
    $result = $checkStmt->get_result();
    $row = $result->fetch_assoc();

    if ($row['count'] > 0) {
        // Jika sudah ada, lakukan UPDATE
        $updateSql = "UPDATE shop SET shop_name = ?, refresh_token = ?, access_token = ?, expire_in = ? 
                      WHERE shop_id = ? AND platform_id = ?";
        $updateStmt = $db->prepare($updateSql);
        $updateStmt->bind_param('sssiii', $shop_name, $refresh_token, $access_token, $expire_in, $shop_id, $platform_id);

        if ($updateStmt->execute()) {
            return true;
        } else {
            // echo "Error: " . $updateStmt->error;
            return false;
        }
    } else {
        // Jika belum ada, lakukan INSERT
        $insertSql = "INSERT INTO shop (shop_id, platform_id, shop_name, refresh_token, access_token, expire_in)
                      VALUES (?, ?, ?, ?, ?, ?)";
        $insertStmt = $db->prepare($insertSql);
        $insertStmt->bind_param('iisssi', $shop_id, $platform_id, $shop_name, $refresh_token, $access_token, $expire_in);

        if ($insertStmt->execute()) {
            return true;
        } else {
            // echo "Error: " . $insertStmt->error;
            return false;
        }
    }
}

function LazadaRefreshToken($refreshToken)
{
    $url = LAZADA_BASE_URL;
    $appkey = LAZADA_APP_KEY;
    $appSecret = LAZADA_APP_SECRET;
    $c = new LazopClient($url, $appkey, $appSecret);
    $request = new LazopRequest('/auth/token/refresh');
    $request->addApiParam('refresh_token', $refreshToken);
    $response = $c->execute($request);
    $responseData = json_decode($response, true);
    return  $responseData;
}

function LazadaPrintAWB($accessToken, $packages, $doc_type = 'PDF', $maxRetries = 3)
{
    $url = LAZADA_BASE_ID_URL;
    $appkey = LAZADA_APP_KEY;
    $appSecret = LAZADA_APP_SECRET;

    $c = new LazopClient($url, $appkey, $appSecret);
    $request = new LazopRequest('/order/package/document/get', 'POST');

    // Create parameter `getDocumentReq` from input
    $getDocumentReq = json_encode([
        'doc_type' => $doc_type,
        'packages' => $packages
    ]);

    // Add parameter to request
    $request->addApiParam('getDocumentReq', $getDocumentReq);

    $attempts = 0;
    while ($attempts < $maxRetries) {
        // Execute API request
        $response = $c->execute($request, $accessToken);

        // Decode response to array
        $responseData = json_decode($response, true);

        // Check for errors in the response
        if (isset($responseData['code']) && $responseData['code'] !== '0') {
            throw new Exception("Error: " . $responseData['message']);
        }

        // Check if result is available
        if (isset($responseData['result']) && !empty($responseData['result'])) {
            return $responseData['result'];
        }

        // Increment attempts
        $attempts++;
    }

    // If no result after retries, throw an exception
    throw new Exception("Failed to retrieve result after $maxRetries attempts.");
}


function LazadaGetSeller($accessToken)
{
    $url = LAZADA_BASE_ID_URL;
    $appkey = LAZADA_APP_KEY;
    $appSecret = LAZADA_APP_SECRET;
    $c = new LazopClient($url, $appkey, $appSecret);
    $request = new LazopRequest('/seller/get', 'GET');
    var_dump($c->execute($request, $accessToken));
}

function LazadaGetOrderDetails($accessToken, $order_id)
{
    $url = LAZADA_BASE_ID_URL; // Pastikan konstanta ini sudah didefinisikan
    $appkey = LAZADA_APP_KEY; // Pastikan konstanta ini sudah didefinisikan
    $appSecret = LAZADA_APP_SECRET; // Pastikan konstanta ini sudah didefinisikan

    $c = new LazopClient($url, $appkey, $appSecret);
    $request = new LazopRequest('/order/get', 'GET');

    // Tambahkan parameter `order_id` ke request
    $request->addApiParam('order_id', $order_id);

    // Eksekusi permintaan API
    $response = $c->execute($request, $accessToken);

    // Decode respons ke array
    $responseData = json_decode($response, true);

    // Cek apakah ada kesalahan dalam respons
    if (isset($responseData['code']) && $responseData['code'] !== '0') {
        throw new Exception("Error: " . $responseData['message']);
    }

    // Kembalikan data
    return $responseData['data'] ?? [];
}

function LazadaGetOrders($accessToken, $refreshToken, $shopId)
{
    global $db;
    $url = LAZADA_BASE_ID_URL;
    $appkey = LAZADA_APP_KEY;
    $appSecret = LAZADA_APP_SECRET;

    // Hitung tanggal hari ini dan 7 hari sebelumnya
    // $today = date('Y-m-d\TH:i:s+08:00'); // Format ISO 8601
    $DaysAgo = date('Y-m-d\TH:i:s+08:00', strtotime('-2 days'));

    $c = new LazopClient($url, $appkey, $appSecret);
    $request = new LazopRequest('/orders/get', 'GET');

    // Tambahkan parameter dengan range waktu
    // $request->addApiParam('update_before', $today);
    $request->addApiParam('created_after', $DaysAgo);
    // $request->addApiParam('sort_direction', 'DESC');
    // $request->addApiParam('offset', '0');
    // $request->addApiParam('limit', '5');
    // $request->addApiParam('sort_by', 'updated_at');

    // Opsional: Filter lainnya seperti status
    $request->addApiParam('status', 'pending');
    // $request->addApiParam('status', 'unpaid');

    // $request->addApiParam('status', 'shipped');

    // Eksekusi permintaan API dan kembalikan hasil
    $response = $c->execute($request, $accessToken);

    $data = json_decode($response, true);
    $code = $data['code'] ?? '';
    if ($code == 'IllegalAccessToken') {
        $token = LazadaRefreshToken($refreshToken);
        $access_token = isset($token['access_token']) ? $token['access_token'] : null;
        $refresh_token = isset($token['refresh_token']) ? $token['refresh_token'] : null;
        $sql = "UPDATE shop SET refresh_token = ?, access_token = ? WHERE shop_id = ?";
        $stmt = $db->prepare($sql);
        $stmt->bind_param("sss", $refresh_token, $access_token, $shopId);
        $stmt->execute();
    }

    return $data['data'] ?? [];  // Decode respons menjadi array
}

function LazadaGetShipmentProvider($accessToken, $orders)
{
    $url = LAZADA_BASE_ID_URL; // Konstanta base URL
    $appkey = LAZADA_APP_KEY; // Konstanta app key
    $appSecret = LAZADA_APP_SECRET; // Konstanta app secret

    $c = new LazopClient($url, $appkey, $appSecret);
    $request = new LazopRequest('/order/shipment/providers/get', 'POST');

    // Buat parameter `getShipmentProvidersReq` dari array orders
    $getShipmentProvidersReq = json_encode(['orders' => $orders]);

    // Tambahkan parameter ke request
    $request->addApiParam('getShipmentProvidersReq', $getShipmentProvidersReq);

    // Eksekusi request API
    $response = $c->execute($request, $accessToken);

    // Decode respons ke array
    $responseData = json_decode($response, true);

    // Cek apakah ada kesalahan dalam respons
    if (isset($responseData['code']) && $responseData['code'] !== '0') {
        throw new Exception("Error: " . $responseData['message']);
    }

    // Kembalikan data pengiriman
    return $responseData['result']['data']['shipping_allocate_type'] ?? false;
}

function LazadaPack($accessToken, $order, $delivery_type, $shipping_allocate_type)
{
    $url = LAZADA_BASE_ID_URL; // Pastikan konstanta ini sudah didefinisikan
    $appkey = LAZADA_APP_KEY; // Pastikan konstanta ini sudah didefinisikan
    $appSecret = LAZADA_APP_SECRET; // Pastikan konstanta ini sudah didefinisikan

    $c = new LazopClient($url, $appkey, $appSecret);
    $request = new LazopRequest('/order/fulfill/pack', 'POST');

    // Buat parameter `packReq` dari input
    $packReq = json_encode([
        'pack_order_list' => $order,
        'delivery_type' => $delivery_type,
        'shipping_allocate_type' => $shipping_allocate_type,
    ]);

    // Tambahkan parameter ke request
    $request->addApiParam('packReq', $packReq);

    // Eksekusi permintaan API
    $response = $c->execute($request, $accessToken);

    // Decode respons ke array
    $responseData = json_decode($response, true);

    // Cek apakah ada kesalahan dalam respons
    if (isset($responseData['code']) && $responseData['code'] !== '0') {
        throw new Exception("Error: " . $responseData['message']);
    }

    // Kembalikan data
    return $responseData ?? false;
}


function LazadaInsertOrUpdateOrder($orderData, $shopId)
{
    global $db;

    // Ambil informasi order dari array
    $shippingCarrier = "LEX-ID";
    $order_sn = $orderData['order_number'];
    $shop_id = $shopId;
    $buyer_username = $orderData['customer_first_name'] . ' ' . $orderData['customer_last_name'];
    $order_status = implode(',', $orderData['statuses']); // Gabungkan status jika ada lebih dari satu
    $payment_method = $orderData['payment_method'];
    $total_amount = $orderData['price'];
    $create_time = date('Y-m-d H:i:s', strtotime($orderData['created_at']));
    $update_time = date('Y-m-d H:i:s', strtotime($orderData['updated_at']));
    $currency = 'IDR'; // Bisa diatur sesuai kebutuhan

    // Cek apakah order sudah ada dengan order_sn dan platform_id
    $checkSql = "SELECT order_status FROM orders WHERE order_sn = ? AND shop_id = ?";
    $checkStmt = $db->prepare($checkSql);
    $checkStmt->bind_param('si', $order_sn, $shop_id);
    $checkStmt->execute();
    $result = $checkStmt->get_result();

    if ($result->num_rows > 0) {
        // Jika order sudah ada, cek status
        $existingOrder = $result->fetch_assoc();

        if ($existingOrder['order_status'] !== $order_status) {
            // Update status jika berbeda
            $updateSql = "UPDATE orders 
                          SET order_status = ?, updated_at = ?
                          WHERE order_sn = ? AND shop_id = ?";
            $updateStmt = $db->prepare($updateSql);
            $updateStmt->bind_param('sssi', $order_status, $update_time, $order_sn, $shop_id);
            $updateStmt->execute();
        }

        $order_id = $db->insert_id();
        return [0, $order_sn];
        // Tidak perlu insert ke order_detail
    } else {
        // Jika order belum ada, lakukan INSERT ke orders
        $insertSql = "INSERT INTO orders (order_sn, shop_id, buyer_username, order_status, payment_method, total_amount, currency, create_time, shipping_carrier) 
                      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $insertStmt = $db->prepare($insertSql);
        $insertStmt->bind_param(
            'sisssssss',
            $order_sn,
            $shop_id,
            $buyer_username,
            $order_status,
            $payment_method,
            $total_amount,
            $currency,
            $create_time,
            $shippingCarrier
        );
        $insertStmt->execute();

        // Ambil ID order yang baru dimasukkan
        $order_id = $db->insert_id();

        return  [$order_id, $order_sn];
    }
}

function LazadaInsertOrderDetail($item, $order_id)
{
    global $db;

    // Ambil data dari $item
    $order_sn = $item['order_id']; // Order ID dari item
    $order_item_id = $item['order_item_id'];
    $item_name = $item['name'];
    $model_id = $item['sku_id'];
    $model_quantity_purchased = 1; // Jika tidak tersedia jumlah, gunakan default 1
    $model_discounted_price = $item['paid_price'];
    $model_original_price = $item['item_price'];
    $image_url = $item['product_main_image'];
    $model_sku = $item['sku'];
    $item_sku = $item['shop_sku'];

    // SQL untuk memasukkan data ke tabel order_detail
    $sql = "INSERT INTO order_detail (
                order_id, 
                order_sn, 
                order_item_id, 
                item_name, 
                model_id, 
                model_quantity_purchased, 
                model_discounted_price, 
                model_original_price, 
                image_url, 
                model_sku, 
                item_sku
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    // Siapkan statement
    if ($stmt = $db->prepare($sql)) {
        // Bind parameter ke statement
        $stmt->bind_param(
            'isissiddsss',
            $order_id,
            $order_sn,
            $order_item_id,
            $item_name,
            $model_id,
            $model_quantity_purchased,
            $model_discounted_price,
            $model_original_price,
            $image_url,
            $model_sku,
            $item_sku
        );

        // Eksekusi statement
        if ($stmt->execute()) {
            return true;
        } else {
            // echo "Gagal memasukkan data ke order_detail: " . $stmt->error . "\n";
            return false;
        }
    } else {
        // echo "Gagal mempersiapkan statement: " . $db->error . "\n";
        return false;
    }
}

function LazadaGetOrderItems($accessToken, $order_id)
{
    $url = LAZADA_BASE_ID_URL; // Pastikan konstanta ini sudah didefinisikan
    $appkey = LAZADA_APP_KEY; // Pastikan konstanta ini sudah didefinisikan
    $appSecret = LAZADA_APP_SECRET; // Pastikan konstanta ini sudah didefinisikan

    $c = new LazopClient($url, $appkey, $appSecret);
    $request = new LazopRequest('/order/items/get', 'GET');

    // Tambahkan parameter order_id
    $request->addApiParam('order_id', $order_id);

    // Eksekusi permintaan API
    $response = $c->execute($request, $accessToken);

    // Decode respons menjadi array
    $responseData = json_decode($response, true);

    // Cek apakah ada kesalahan
    if (isset($responseData['code']) && $responseData['code'] !== '0') {
        throw new Exception("Error: " . $responseData['message']);
    }

    // Kembalikan data detail order
    return $responseData['data'] ?? [];
}

function LazadaDownloadAWB($pdf_url, $orderSN, $maxRetries = 3)
{
    // Tentukan folder dan nama file
    $nameDownload = 'storage/awb/awb-' . $orderSN . '.pdf';

    // Cek apakah folder "storage/awb" ada, jika tidak buat foldernya
    $folderPath = dirname($nameDownload);
    if (!is_dir($folderPath)) {
        mkdir($folderPath, 0777, true); // Buat folder dengan izin akses penuh
    }

    $attempts = 0;
    $success = false;
    $error = '';

    while ($attempts < $maxRetries && !$success) {
        // Gunakan cURL untuk mendownload file
        $ch = curl_init($pdf_url);
        $fp = fopen($nameDownload, 'wb'); // Buka file untuk menulis

        curl_setopt($ch, CURLOPT_FILE, $fp);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Ikuti redirect jika ada
        curl_setopt($ch, CURLOPT_TIMEOUT, 60); // Timeout 60 detik
        curl_setopt($ch, CURLOPT_FAILONERROR, true); // Error jika gagal HTTP
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Nonaktifkan verifikasi sertifikat
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // Nonaktifkan verifikasi hostname

        $success = curl_exec($ch); // Eksekusi cURL
        $error = curl_error($ch);

        curl_close($ch);
        fclose($fp);

        // Jika unduhan gagal, hapus file sementara
        if (!$success && file_exists($nameDownload)) {
            unlink($nameDownload);
        }

        $attempts++;
    }

    // Periksa apakah unduhan berhasil setelah semua percobaan
    if ($success) {
        return $nameDownload; // Return path file yang diunduh
    } else {
        throw new Exception("Gagal mendownload file setelah $maxRetries percobaan: " . $error);
    }
}