<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Asset;
use App\Models\TransactionAsset;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Midtrans\Config;
use Midtrans\Snap;
use Carbon\Carbon;

class TransactionAssetController extends Controller
{
    public function __construct()
    {
        // Konfigurasi Midtrans
        Config::$serverKey = env('MIDTRANS_SERVER_KEY');
        Config::$isProduction = (bool) env('MIDTRANS_IS_PRODUCTION', false);
        Config::$isSanitized = true;
        Config::$is3ds = true;
    }

    /**
     * Menampilkan riwayat transaksi asset user
     */
    public function index()
    {
        $transactions = TransactionAsset::with('asset')
            ->where('user_id', Auth::id())
            ->orderBy('created_at', 'desc')
            ->get();

        // Auto-expire check
        $transactions->transform(function ($item) {
            if ($item->status === 'pending' && $item->payment_due_date && now()->gt($item->payment_due_date)) {
                $item->status = 'expired';
                $item->save();
            }
            $item->reference_name = $item->asset ? $item->asset->title : 'Digital Asset';
            return $item;
        });

        return response()->json([
            'success' => true,
            'data' => $transactions
        ]);
    }

    /**
     * Membuat transaksi baru (Checkout Asset)
     */
    public function store(Request $request)
    {
        $request->validate([
            'asset_id' => 'required|exists:assets,id',
        ]);

        $asset = Asset::findOrFail($request->asset_id);
        $user = Auth::user();

        // Buat Order ID unik
        $orderId = 'THEA-ASST-' . time() . '-' . strtoupper(bin2hex(random_bytes(2)));

        // 1. Simpan ke database
        $transaction = TransactionAsset::create([
            'order_id' => $orderId,
            'user_id' => $user->id,
            'asset_id' => $asset->id,
            'amount' => $asset->price, // Pastikan tabel asset punya kolom price
            'status' => 'pending',
            'payment_due_date' => now()->addHours(24),
        ]);

        // 2. Generate Snap Token Midtrans
        $params = [
            'transaction_details' => [
                'order_id' => $orderId,
                'gross_amount' => (int) $transaction->amount,
            ],
            'customer_details' => [
                'first_name' => $user->name,
                'email' => $user->email,
            ],
            'item_details' => [
                [
                    'id' => $asset->id,
                    'price' => (int) $transaction->amount,
                    'quantity' => 1,
                    'name' => 'Asset: ' . $asset->name,
                ]
            ]
        ];

        try {
            $snapToken = Snap::getSnapToken($params);
            $transaction->update(['snap_token' => $snapToken]);

            return response()->json([
                'success' => true,
                'message' => 'Transaction created',
                'data' => $transaction
            ]);
        } catch (\Exception $e) {
            return response()->json(['message' => 'Midtrans Error: ' . $e->getMessage()], 500);
        }
    }

    /**
     * Menampilkan detail transaksi berdasarkan Order ID
     */
    public function show($orderId)
    {
        $transaction = TransactionAsset::with('asset')
            ->where('order_id', $orderId)
            ->where('user_id', Auth::id())
            ->firstOrFail();

        // Refresh status if expired
        if ($transaction->status === 'pending' && $transaction->payment_due_date && now()->gt($transaction->payment_due_date)) {
            $transaction->update(['status' => 'expired']);
        }

        $transaction->reference_name = $transaction->asset ? $transaction->asset->name : 'Digital Asset';

        return response()->json([
            'success' => true,
            'data' => $transaction
        ]);
    }
}