<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Payment;
use App\Services\AccountService;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class PaymentController extends Controller
{
    /**
     * Membuat order pembayaran baru (status pending).
     * Frontend memakai order_id untuk mengarahkan user ke payment gateway,
     * lalu gateway memanggil endpoint webhook saat pembayaran sukses.
     */
    public function checkout(Request $request)
    {
        $validated = $request->validate([
            'email' => 'required|email',
            'name' => 'nullable|string|max:255',
            'package_name' => 'required|string|max:191',
            'amount' => 'required|numeric|min:0',
            'gateway' => 'nullable|string|max:50',
        ]);

        $payment = Payment::create([
            'email' => $validated['email'],
            'name' => $validated['name'] ?? null,
            'order_id' => 'ORD-' . strtoupper(Str::random(12)),
            'package_name' => $validated['package_name'],
            'amount' => $validated['amount'],
            'gateway' => $validated['gateway'] ?? null,
            'payment_status' => 'pending',
        ]);

        return response()->json([
            'success' => true,
            'order_id' => $payment->order_id,
            'amount' => $payment->amount,
        ], 201);
    }

    /**
     * Callback dari payment gateway.
     * Saat status 'paid': update payment, provisi akun (password acak),
     * dan kirim email otomatis berisi link website + password.
     */
    public function webhook(Request $request)
    {
        $validated = $request->validate([
            'order_id' => 'required|string',
            'payment_status' => 'required|in:paid,failed,expired',
            'transaction_id' => 'nullable|string',
            'gateway' => 'nullable|string|max:50',
        ]);

        $payment = Payment::where('order_id', $validated['order_id'])->first();

        if (!$payment) {
            return response()->json(['success' => false, 'message' => 'Order tidak ditemukan.'], 404);
        }

        // Jaga agar akun tidak dibuat dua kali
        if ($payment->payment_status === 'paid') {
            return response()->json(['success' => true, 'message' => 'Sudah diproses.']);
        }

        if ($validated['payment_status'] === 'paid') {
            $payment->update([
                'payment_status' => 'paid',
                'paid_at' => now(),
                'gateway' => $validated['gateway'] ?? $payment->gateway,
                'gateway_transaction_id' => $validated['transaction_id'] ?? null,
            ]);

            app(AccountService::class)->provision([
                'email' => $payment->email,
                'name' => $payment->name,
                'package_name' => $payment->package_name,
                'price' => $payment->amount,
            ]);

            return response()->json(['success' => true, 'message' => 'Pembayaran diterima.']);
        }

        $payment->update(['payment_status' => $validated['payment_status']]);

        return response()->json(['success' => true]);
    }
}
