<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\TransactionPlan;
use App\Models\Plan; // Asumsi kamu punya model Plan untuk master data paket
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Carbon\Carbon;
use Midtrans\Config;
use Midtrans\Snap;

class TransactionPlanController extends Controller
{
    /**
     * Membuat Invoice baru (Checkout)
     */
    public function checkout(Request $request)
    {
        $request->validate([
            'plan_id' => 'required|exists:plans,id',
            'type' => 'required|in:customer,contributor',
        ]);

        $user = Auth::user();
        $plan = Plan::findOrFail($request->plan_id);

        // 1. Generate Order ID unik
        $orderId = 'THEA-' . strtoupper($request->type[0]) . '-' . time() . '-' . strtoupper(Str::random(4));

        // 2. Buat record transaksi (Bayar sebelum aktif)
        $transaction = TransactionPlan::create([
            'order_id'         => $orderId,
            'user_id'          => $user->id,
            'transaction_type' => $request->type, // customer atau contributor
            'reference_id'     => $plan->id,
            'amount'           => $plan->price,
            'status'           => 'pending',
            'payment_due_date' => Carbon::now()->addHours(24), // Tenggat waktu 24 jam
        ]);

        Config::$serverKey = env('MIDTRANS_SERVER_KEY');
        Config::$isProduction = env('MIDTRANS_IS_PRODUCTION');
        Config::$isSanitized = true;
        Config::$is3ds = true;
        $params = [
            'transaction_details' => [
                'order_id' => $transaction->order_id,
                'gross_amount' => (int)$transaction->amount,
                // 'currency' => 'USD',
            ],
            'customer_details' => [
                'first_name' => Auth::user()->name,
                'email' => Auth::user()->email,
            ],
        ];
    
        try {
            $snapToken = Snap::getSnapToken($params);
            $transaction->update(['snap_token' => $snapToken]); // Simpan ke database
    
            return response()->json([
                'success' => true,
                'data' => $transaction
            ]);
        } catch (\Exception $e) {
            return response()->json(['message' => $e->getMessage()], 500);
        }

        return response()->json([
            'success' => true,
            'message' => 'Invoice berhasil dibuat. Silakan selesaikan pembayaran.',
            'data'    => [
                'order_id'         => $transaction->order_id,
                'amount'           => $transaction->amount,
                'due_date'         => $transaction->payment_due_date->toDateTimeString(),
                'status'           => $transaction->status,
                'snap_token'    => $transaction->snap_token, // Nanti diisi setelah integrasi Midtrans
            ]
        ], 201);
    }

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

        $transactions->transform(function ($item) {
            // Logika Auto-Expire
            if ($item->status === 'pending' && $item->payment_due_date && now()->gt($item->payment_due_date)) {
                $item->status = 'expired';
                $item->save();
            }

            // Kita tambahkan attribute custom 'reference_name' agar 
            // pas di React tinggal panggil t.reference_name
            $item->reference_name = $item->plan ? $item->plan->name : 'Unknown Plan';
            
            return $item;
        });

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

    /**
     * Detail transaksi tunggal
     */
    public function show($orderId)
    {
        $transaction = TransactionPlan::where('order_id', $orderId)
            ->where('user_id', Auth::id())
            ->firstOrFail();

        // Cek jika sudah kadaluarsa saat dibuka
        if ($transaction->status === 'pending' && now()->gt($transaction->payment_due_date)) {
            $transaction->update(['status' => 'expired']);
        }

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

    public function callback(Request $request)
    {
        $serverKey = env('MIDTRANS_SERVER_KEY');
        $hashed = hash("sha512", $request->order_id . $request->status_code . $request->gross_amount . $serverKey);

        if ($hashed == $request->signature_key) {
            if ($request->transaction_status == 'capture' || $request->transaction_status == 'settlement') {
                $transaction = TransactionPlan::where('order_id', $request->order_id)->first();
                if ($transaction) {
                    $transaction->update(['status' => 'paid']);
                    
                    // LOGIKA TAMBAHAN: Aktifkan plan, tambah credit, dll.
                    // $this->activateSubscription($transaction);
                }
            }
        }
    }
}