<?php

namespace App\Services\Midtrans;

use Midtrans\CoreApi;
use Midtrans\Config;
use Illuminate\Support\Facades\Log;

class CreateVAService extends Midtrans
{
    protected $order;

    public function __construct($order)
    {
        parent::__construct();

        $this->order = $order;
    }

    protected function initializeMidtrans()
    {
        // Konfigurasi Midtrans
        Config::$serverKey = env('MIDTRANS_SERVER_KEY');
        Config::$isProduction = false; // Ubah ke true jika menggunakan lingkungan produksi
        Config::$isSanitized = true;
        Config::$is3ds = true;
    }

    public function getVA()
    {
        $itemDetails = [];

        foreach ($this->order->orderItems as $orderItem) {
            $itemDetails[] = [
                'id' => $orderItem->product->id,
                'price' => $orderItem->product->price,
                'quantity' => $orderItem->quantity,
                'name' => $orderItem->product->name,
            ];
        }

        // Menambahkan biaya pengiriman ke item details
        $itemDetails[] = [
            'id' => 'SHIPPING_COST',
            'price' => $this->order->shipping_cost,
            'quantity' => 1,
            'name' => 'SHIPPING_COST',
        ];

        $itemDetails[] = [
            'id' => 'DISCOUNT',
            'price' => (($this->order->discount / 100) * $this->order->subtotal) * -1,
            'quantity' => 1,
            'name' => 'DISCOUNT',
        ];

        $grossAmount = array_reduce($itemDetails, function ($sum, $item) {
            return $sum + ($item['price'] * $item['quantity']);
        }, 0);

        Log::info('Calculated Gross Amount:', ['gross_amount' => $grossAmount]);
        Log::info('Item Details:', $itemDetails);

        $params = [
            'payment_type' => 'bank_transfer',
            'transaction_details' => [
                'order_id' => $this->order->transaction_number,
                'gross_amount' => $this->order->total_cost,
            ],
            'item_details' => $itemDetails,
            'customer_details' => [
                'first_name' => $this->order->user->name,
                'email' => $this->order->user->email
            ],
            'bank_transfer' => [
                'bank' => $this->order->payment_va_name,
            ],
        ];

        $response = CoreApi::charge($params);

        return $response;
    }
}
