<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Invoice;
use App\Models\Payment;
use App\Models\AuditLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class PaymentAdminController extends Controller
{
    public function index(Request $request)
    {
        $query = Payment::with('order.user', 'invoice');

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }
        if ($request->filled('payment_method')) {
            $query->where('payment_method', $request->payment_method);
        }

        $payments = $query->orderBy('created_at', 'desc')->paginate(15)->withQueryString();
        $invoices = Invoice::with('order.user')->orderBy('created_at', 'desc')->take(10)->get();

        return view('admin.payments.index', compact('payments', 'invoices'));
    }

    public function verify(Request $request, string $id)
    {
        $payment = Payment::findOrFail($id);

        $payment->update([
            'status' => 'verified',
            'verified_by' => Auth::id(),
            'verified_at' => now(),
            'admin_notes' => $request->input('notes', 'Payment verified and credited to client account.'),
        ]);

        // Update order paid amount
        $order = $payment->order;
        $order->increment('paid_amount_bdt', $payment->amount_bdt);
        $order->update(['due_amount_bdt' => max(0, $order->total_amount_bdt - $order->paid_amount_bdt)]);

        // Update invoice if attached
        if ($payment->invoice) {
            $payment->invoice->increment('paid_bdt', $payment->amount_bdt);
            $payment->invoice->update([
                'due_bdt' => max(0, $payment->invoice->amount_bdt - $payment->invoice->paid_bdt),
                'status' => $payment->invoice->due_bdt <= 0 ? 'paid' : 'partially_paid',
            ]);
        }

        AuditLog::record('admin_verified_payment', $payment);

        return back()->with('success', "Payment of ৳" . number_format($payment->amount_bdt, 0) . " verified successfully.");
    }
}
