<?php

namespace App\Http\Controllers;

use App\Models\Payment;
use App\Models\Order;
use App\Models\PaymentOption;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class PaymentController extends Controller
{
    /**
     * Display a listing of all payments (Admin only).
     */
    public function index(Request $request)
    {
        $user = Auth::guard('api')->user();
        if (!$user || !$user->isAdmin()) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized - Admin access required',
            ], 403);
        }

        try {
            $perPage = $request->get('per_page', 15);
            $payments = Payment::with(['order', 'paymentOption'])->paginate($perPage);

            return response()->json([
                'success' => true,
                'data' => $payments->items(),
                'pagination' => [
                    'total' => $payments->total(),
                    'per_page' => $payments->perPage(),
                    'current_page' => $payments->currentPage(),
                    'last_page' => $payments->lastPage(),
                    'from' => $payments->firstItem(),
                    'to' => $payments->lastItem(),
                    'has_more' => $payments->hasMorePages(),
                ],
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch payments',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Create a new payment for an order.
     */
    public function store(Request $request)
    {
        $user = Auth::guard('api')->user();
        if (!$user) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized',
            ], 401);
        }

        $validator = Validator::make($request->all(), [
            'order_id' => 'required|exists:orders,id',
            'payment_option_id' => 'required|exists:payment_options,id',
            'transaction_id' => 'nullable|string|unique:payments',
            'notes' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors(),
            ], 422);
        }

        try {
            $order = Order::find($request->order_id);
            
            // Check if user is admin or owns the order
            if (!$user->isAdmin() && $order->user_id !== $user->id) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized - You can only pay for your own orders',
                ], 403);
            }

            // Check if payment option is active
            $paymentOption = PaymentOption::find($request->payment_option_id);
            if (!$paymentOption->status) {
                return response()->json([
                    'success' => false,
                    'message' => 'Payment option is not available',
                ], 422);
            }

            // Check if order already has a completed payment
            $existingPayment = Payment::where('order_id', $request->order_id)
                ->where('status', 'completed')
                ->first();
            
            if ($existingPayment) {
                return response()->json([
                    'success' => false,
                    'message' => 'Order already has a completed payment',
                ], 422);
            }

            $payment = Payment::create([
                'order_id' => $request->order_id,
                'payment_option_id' => $request->payment_option_id,
                'amount' => $order->total_amount,
                'status' => 'pending',
                'transaction_id' => $request->transaction_id,
                'notes' => $request->notes,
            ]);

            $payment->load(['order', 'paymentOption']);

            return response()->json([
                'success' => true,
                'message' => 'Payment created successfully',
                'data' => $payment,
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to create payment',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Display the specified payment.
     */
    public function show(Payment $payment)
    {
        $user = Auth::guard('api')->user();
        
        // Check if user is admin or owns the order
        if (!$user->isAdmin() && $payment->order->user_id !== $user->id) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized',
            ], 403);
        }

        try {
            $payment->load(['order', 'paymentOption']);

            return response()->json([
                'success' => true,
                'data' => $payment,
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch payment',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Update payment status (Admin only).
     */
    public function update(Request $request, Payment $payment)
    {
        $user = Auth::guard('api')->user();
        if (!$user || !$user->isAdmin()) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized - Admin access required',
            ], 403);
        }

        $validator = Validator::make($request->all(), [
            'status' => 'required|in:pending,completed,failed,refunded',
            'notes' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed',
                'errors' => $validator->errors(),
            ], 422);
        }

        try {
            $payment->update($request->only('status', 'notes'));
            $payment->load(['order', 'paymentOption']);

            return response()->json([
                'success' => true,
                'message' => 'Payment updated successfully',
                'data' => $payment,
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to update payment',
                'error' => $e->getMessage(),
            ], 500);
        }
    }

    /**
     * Delete a payment (Admin only).
     */
    public function destroy(Payment $payment)
    {
        $user = Auth::guard('api')->user();
        if (!$user || !$user->isAdmin()) {
            return response()->json([
                'success' => false,
                'message' => 'Unauthorized - Admin access required',
            ], 403);
        }

        try {
            $payment->delete();

            return response()->json([
                'success' => true,
                'message' => 'Payment deleted successfully',
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to delete payment',
                'error' => $e->getMessage(),
            ], 500);
        }
    }
}
