<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\PaymentMethod;

class PaymentMethodController extends Controller
{
    public function index(Request $request)
    {
        return response()->json([
            'success' => true,
            'payment_methods' => $request->user()->paymentMethods()->orderBy('created_at', 'desc')->get()
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'type' => 'required|string', // visa, mastercard, apple_pay, google_pay
            'card_name' => 'nullable|string',
            'card_number_last_four' => 'nullable|string',
            'expiry_date' => 'nullable|string',
        ]);

        $pm = $request->user()->paymentMethods()->create(array_merge(
            $request->only(['type', 'card_name', 'card_number_last_four', 'expiry_date']),
            ['is_connected' => true]
        ));

        return response()->json([
            'success' => true,
            'payment_method' => $pm,
            'message' => 'Payment method added successfully'
        ]);
    }

    public function destroy(Request $request, $id)
    {
        $pm = $request->user()->paymentMethods()->findOrFail($id);
        $pm->delete();

        return response()->json([
            'success' => true,
            'message' => 'Payment method removed'
        ]);
    }
}
