<?php
// app/Http/Controllers/Api/Admin/PaymentMethodController.php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Traits\ApiResponse;
use App\Models\PaymentMethod;
use App\Http\Requests\Api\Admin\PaymentMethodRequest;
use App\Http\Resources\Api\PaymentMethodResource;
use App\Http\Resources\Api\PaymentMethodCollection;
use Illuminate\Http\Request;

class PaymentMethodController extends Controller
{
    use ApiResponse;

    /**
     * Get all payment methods with pagination
     */
    public function index(Request $request)
    {
        try {
            $query = PaymentMethod::when($request->search, function ($q, $search) {
                    $q->where('name', 'like', "%{$search}%");
                })
                ->when($request->code, function ($q, $code) {
                    $q->where('code', $code);
                })
                ->when($request->is_active !== null, function ($q) use ($request) {
                    $q->where('is_active', $request->is_active);
                })
                ->orderBy('created_at', 'desc');

            $perPage = $request->per_page ?? 20;
            $paymentMethods = $query->paginate($perPage);

            return $this->successResponse(
                new PaymentMethodCollection($paymentMethods),
                'Payment methods retrieved successfully'
            );
        } catch (\Exception $e) {
            return $this->errorResponse('Failed to retrieve payment methods', 500, $e->getMessage());
        }
    }

    /**
     * Get single payment method
     */
    public function show($id)
    {
        try {
            $paymentMethod = PaymentMethod::find($id);

            if (!$paymentMethod) {
                return $this->errorResponse('Payment method not found', 404);
            }

            return $this->successResponse(
                new PaymentMethodResource($paymentMethod),
                'Payment method retrieved successfully'
            );
        } catch (\Exception $e) {
            return $this->errorResponse('Failed to retrieve payment method', 500, $e->getMessage());
        }
    }

    /**
     * Create new payment method
     */
    public function store(PaymentMethodRequest $request)
    {
        try {
            // Check for duplicate name
            $existingMethod = PaymentMethod::where('name', $request->name)->first();
            if ($existingMethod) {
                return $this->errorResponse('Payment method name already exists', 400);
            }

            $paymentMethod = PaymentMethod::create($request->validated());

            return $this->successResponse(
                new PaymentMethodResource($paymentMethod),
                'Payment method created successfully',
                201
            );
        } catch (\Exception $e) {
            return $this->errorResponse('Failed to create payment method', 500, $e->getMessage());
        }
    }

    /**
     * Update payment method
     */
    public function update(PaymentMethodRequest $request, $id)
    {
        try {
            $paymentMethod = PaymentMethod::find($id);

            if (!$paymentMethod) {
                return $this->errorResponse('Payment method not found', 404);
            }

            // Check for duplicate name
            if ($request->has('name') && $request->name !== $paymentMethod->name) {
                $existingMethod = PaymentMethod::where('name', $request->name)->first();
                if ($existingMethod) {
                    return $this->errorResponse('Payment method name already exists', 400);
                }
            }

            $paymentMethod->update($request->validated());

            return $this->successResponse(
                new PaymentMethodResource($paymentMethod->fresh()),
                'Payment method updated successfully'
            );
        } catch (\Exception $e) {
            return $this->errorResponse('Failed to update payment method', 500, $e->getMessage());
        }
    }

    /**
     * Delete payment method
     */
    public function destroy($id)
    {
        try {
            $paymentMethod = PaymentMethod::find($id);

            if (!$paymentMethod) {
                return $this->errorResponse('Payment method not found', 404);
            }

            // Check if payment method has payments
            if ($paymentMethod->payments()->exists()) {
                return $this->errorResponse(
                    'Cannot delete payment method because it has associated payments',
                    400
                );
            }

            $paymentMethod->delete();

            return $this->successResponse(
                null,
                'Payment method deleted successfully'
            );
        } catch (\Exception $e) {
            return $this->errorResponse('Failed to delete payment method', 500, $e->getMessage());
        }
    }

    /**
     * Toggle payment method status
     */
    public function toggleStatus($id)
    {
        try {
            $paymentMethod = PaymentMethod::find($id);

            if (!$paymentMethod) {
                return $this->errorResponse('Payment method not found', 404);
            }

            $paymentMethod->update(['is_active' => !$paymentMethod->is_active]);

            return $this->successResponse(
                new PaymentMethodResource($paymentMethod),
                'Payment method status updated successfully'
            );
        } catch (\Exception $e) {
            return $this->errorResponse('Failed to update payment method status', 500, $e->getMessage());
        }
    }

    /**
     * Get payment method statistics
     */
    public function statistics()
    {
        try {
            $totalMethods = PaymentMethod::count();
            $activeMethods = PaymentMethod::where('is_active', true)->count();

            $methodsWithStats = PaymentMethod::withCount(['payments' => function ($query) {
                $query->where('status', 'confirmed');
            }])
            ->with(['payments' => function ($query) {
                $query->selectRaw('payment_method_id, SUM(amount) as total_amount')
                      ->where('status', 'confirmed')
                      ->groupBy('payment_method_id');
            }])
            ->get()
            ->map(function ($method) {
                return [
                    'id' => $method->id,
                    'name' => $method->name,
                    'code' => $method->code,
                    'total_payments' => $method->payments_count,
                    'total_amount' => $method->payments->first()->total_amount ?? 0
                ];
            });

            return $this->successResponse([
                'total_methods' => $totalMethods,
                'active_methods' => $activeMethods,
                'methods_with_stats' => $methodsWithStats
            ], 'Payment method statistics retrieved successfully');
        } catch (\Exception $e) {
            return $this->errorResponse('Failed to retrieve statistics', 500, $e->getMessage());
        }
    }
}