<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Services\PaypalService;
use App\Services\PaystackService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class CheckoutController extends Controller
{
    protected $paystackService;
    protected $paypalService;

    public function __construct(PaystackService $paystackService, PaypalService $paypalService)
    {
        $this->paystackService = $paystackService;
        $this->paypalService = $paypalService;
    }

    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|max:255',
            'address' => 'required|string',
            'payment_method' => 'required|string|in:paystack,paypal',
            'cart' => 'required|array',
            'total' => 'required|numeric',
        ]);

        $order = Order::create([
            'id' => Str::uuid(),
            'user_id' => Auth::id(),
            'name' => $validatedData['name'],
            'email' => $validatedData['email'],
            'address' => $validatedData['address'],
            'payment_method' => $validatedData['payment_method'],
            'cart_items' => $validatedData['cart'],
            'total_amount' => $validatedData['total'],
            'status' => 'pending',
        ]);

        $paymentData = [
            'amount' => $order->total_amount,
            'email' => $order->email,
            'order_id' => $order->id,
            'callback_url' => route('paystack.callback'),
            'reference' => $order->id,
            'metadata' => [
                'booking_id' => $order->id,
            ],
        ];

        if ($validatedData['payment_method'] === 'paystack') {
            $paymentData['callback_url'] = route('paystack.callback');
            $response = $this->paystackService->initializePayment($paymentData);
        } elseif ($validatedData['payment_method'] === 'paypal') {
            $response = $this->paypalService->initializePayment($paymentData);
        } else {
            return redirect()->route('home')->with('order', $order);
        }

        if (isset($response['status']) && $response['status']) {
            return response()->json([
                'authorization_url' => $response['authorization_url']
            ]);
        }

        return response()->json(['message' => $response['message'] ?? 'Payment initialization failed.'], 500);
    }
}
