<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\Payment;
use App\Models\Order;
use App\Models\Wallet;
use App\Models\WalletTransaction;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class PaymentController extends Controller
{
    public function processPayment(Request $request, $orderId)
    {
        $order = Order::findOrFail($orderId);

        if ($request->payment_method === 'wallet') {
            return $this->processWalletPayment($order, $request->user());
        } elseif ($request->payment_method === 'card') {
            return $this->processCardPayment($order, $request);
        } else {
            return $this->processCashPayment($order);
        }
    }

    private function processWalletPayment($order, $user)
    {
        $wallet = Wallet::where('user_id', $user->id)->firstOrFail();

        if ($wallet->balance < $order->total) {
            return response()->json(['message' => 'Insufficient wallet balance'], 400);
        }

        $wallet->decrement('balance', $order->total);

        WalletTransaction::create([
            'wallet_id' => $wallet->id,
            'type' => 'debit',
            'amount' => $order->total,
            'balance_after' => $wallet->balance,
            'description' => "Payment for order #{$order->order_number}",
            'reference_type' => 'Order',
            'reference_id' => $order->id,
        ]);

        $payment = Payment::create([
            'order_id' => $order->id,
            'user_id' => $user->id,
            'transaction_id' => 'WALLET-' . strtoupper(Str::random(10)),
            'payment_method' => 'wallet',
            'status' => 'completed',
            'amount' => $order->total,
            'paid_at' => now(),
        ]);

        $order->update(['payment_status' => 'paid']);

        return response()->json(['message' => 'Payment successful', 'payment' => $payment]);
    }

    private function processCardPayment($order, $request)
    {
        // Stripe/PayHere integration here
        $payment = Payment::create([
            'order_id' => $order->id,
            'user_id' => $request->user()->id,
            'transaction_id' => 'CARD-' . strtoupper(Str::random(10)),
            'payment_method' => 'card',
            'status' => 'completed',
            'amount' => $order->total,
            'paid_at' => now(),
        ]);

        $order->update(['payment_status' => 'paid']);

        return response()->json(['message' => 'Payment successful', 'payment' => $payment]);
    }

    private function processCashPayment($order)
    {
        $payment = Payment::create([
            'order_id' => $order->id,
            'user_id' => $order->user_id,
            'payment_method' => 'cash',
            'status' => 'pending',
            'amount' => $order->total,
        ]);

        return response()->json(['message' => 'Cash on delivery selected', 'payment' => $payment]);
    }

    public function refund($orderId)
    {
        $order = Order::with('payment')->findOrFail($orderId);
        $payment = $order->payment;

        if ($payment->payment_method === 'wallet') {
            $wallet = Wallet::where('user_id', $order->user_id)->first();
            $wallet->increment('balance', $order->total);

            WalletTransaction::create([
                'wallet_id' => $wallet->id,
                'type' => 'credit',
                'amount' => $order->total,
                'balance_after' => $wallet->balance,
                'description' => "Refund for order #{$order->order_number}",
                'reference_type' => 'Order',
                'reference_id' => $order->id,
            ]);
        }

        $payment->update(['status' => 'refunded']);
        $order->update(['payment_status' => 'refunded']);

        return response()->json(['message' => 'Refund processed successfully']);
    }

    public function walletBalance(Request $request)
    {
        $wallet = Wallet::where('user_id', $request->user()->id)->firstOrFail();
        
        return response()->json($wallet);
    }

    public function walletTransactions(Request $request)
    {
        $wallet = Wallet::where('user_id', $request->user()->id)->firstOrFail();
        $transactions = WalletTransaction::where('wallet_id', $wallet->id)
            ->latest()
            ->paginate(20);

        return response()->json($transactions);
    }

    public function addFunds(Request $request)
    {
        $wallet = Wallet::where('user_id', $request->user()->id)->firstOrFail();
        $wallet->increment('balance', $request->amount);

        WalletTransaction::create([
            'wallet_id' => $wallet->id,
            'type' => 'credit',
            'amount' => $request->amount,
            'balance_after' => $wallet->balance,
            'description' => 'Wallet top-up',
        ]);

        return response()->json(['message' => 'Funds added successfully', 'wallet' => $wallet]);
    }
}
