<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Invoice;
use Midtrans\Config;
use Midtrans\Snap;



class InvoiceController extends Controller
{
    public function __construct()
    {
        // Set konfigurasi Midtrans saat controller diinisialisasi
        Config::$serverKey = config('midtrans.server_key');
        Config::$isProduction = config('midtrans.is_production');
        Config::$isSanitized = config('midtrans.is_sanitized');
        Config::$is3ds = config('midtrans.is_3ds');
    }

    /**
     * Menampilkan daftar tagihan (saat ini dan riwayat).
     */
    public function index()
    {
        $user = Auth::user();
        $currentInvoice = Invoice::where('user_id', $user->id)
            ->where('status', 'unpaid')
            ->whereNotNull('published_at')
            ->first();
        
        $invoiceHistory = Invoice::where('user_id', $user->id)
            ->where('status', 'paid')
            ->whereNotNull('published_at')
            ->orderBy('created_at', 'desc')
            ->paginate(10);

        return view('invoices.index', [
            'currentInvoice' => $currentInvoice,
            'invoiceHistory' => $invoiceHistory
        ]);
    }

    /**
     * Menampilkan detail satu tagihan & tombol bayar.
     */
    // app/Http/Controllers/InvoiceController.php

    public function show(Invoice $invoice, Request $request)
{
    if ($invoice->user_id !== Auth::id()) {
        abort(403, 'AKSES DITOLAK');
    }

    // Jika sudah lunas, langsung tampilkan resi
    if ($invoice->status == 'paid') {
        return view('invoices.show', [
            'invoice' => $invoice,
            'snapToken' => null
        ]);
    }

    // Buat order_id dan token BARU setiap kali halaman dibuka (jika status unpaid)
    if ($invoice->status == 'unpaid') {
        // Selalu buat order_id baru agar tidak konflik dengan transaksi sebelumnya
        $orderId = 'PAMSIMAS-' . $invoice->id . '-' . time();

        $params = [
            'transaction_details' => [
                'order_id' => $orderId,
                'gross_amount' => $invoice->total_amount,
            ],
            'customer_details' => [
                'first_name' => $invoice->user->name,
                'email' => $invoice->user->email,
                'phone' => $invoice->user->profile->phone_number,
            ],
        ];

        $snapToken = Snap::getSnapToken($params);
        
        $invoice->midtrans_order_id = $orderId;
        $invoice->snap_token = $snapToken;
        // Status tetap unpaid
        $invoice->save();
    }

    return view('invoices.show', [
        'invoice' => $invoice,
        'snapToken' => $invoice->snap_token
    ]);
}
}