<?php

namespace App\Http\Controllers\Api\V1;

use App\Services\PaymentService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AdminPaymentController extends BaseController
{
    public function __construct(
        private PaymentService $paymentService
    ) {}

    /**
     * Get all payments (admin only)
     */
    public function index(Request $request): JsonResponse
    {
        try {
            $user = Auth::user();
            if (!$user || $user->role_type !== 3) { // 3=admin
                return $this->forbiddenResponse('Only admins can view all payments');
            }

            $filters = $request->only([
                'status', 'booking_id', 'tenant_id', 'landlord_id', 'payment_type', 
                'payment_method', 'due_date_from', 'due_date_to', 'per_page'
            ]);

            $payments = $this->paymentService->getAllPayments($filters);

            return $this->successResponse(
                $this->paymentService->formatPaymentsForResponse($payments),
                'Payments retrieved successfully'
            );
        } catch (\Exception $e) {
            return $this->serverErrorResponse('Failed to retrieve payments: ' . $e->getMessage());
        }
    }

    /**
     * Get payment details (admin view)
     */
    public function show(Request $request, $id): JsonResponse
    {
        try {
            $user = Auth::user();
            if (!$user || $user->role_type !== 3) { // 3=admin
                return $this->forbiddenResponse('Only admins can view payment details');
            }

            $payment = $this->paymentService->getPaymentById((int) $id);
            if (!$payment) {
                return $this->notFoundResponse('Payment not found');
            }

            return $this->successResponse(
                $this->paymentService->formatPaymentForResponse($payment),
                'Payment retrieved successfully'
            );
        } catch (\Exception $e) {
            return $this->serverErrorResponse('Failed to retrieve payment: ' . $e->getMessage());
        }
    }

    /**
     * Update payment status (admin only)
     */
    public function updateStatus(Request $request, $id): JsonResponse
    {
        try {
            $user = Auth::user();
            if (!$user || $user->role_type !== 3) { // 3=admin
                return $this->forbiddenResponse('Only admins can update payment status');
            }

            $validated = $request->validate([
                'status' => 'required|integer|in:1,2,3,4', // 1=pending, 2=completed, 3=failed, 4=refunded
            ]);

            $payment = $this->paymentService->updatePaymentStatus((int) $id, $validated['status'], $user);

            return $this->successResponse(
                $this->paymentService->formatPaymentForResponse($payment),
                'Payment status updated successfully'
            );
        } catch (\Exception $e) {
            return $this->errorResponse('Failed to update payment status: ' . $e->getMessage());
        }
    }

    /**
     * Get overdue payments (admin view)
     */
    public function overduePayments(Request $request): JsonResponse
    {
        try {
            $user = Auth::user();
            if (!$user || $user->role_type !== 3) { // 3=admin
                return $this->forbiddenResponse('Only admins can view overdue payments');
            }

            $overduePayments = $this->paymentService->getOverduePayments();

            return $this->successResponse(
                $overduePayments->map(fn($payment) => $this->paymentService->formatPaymentForResponse($payment)),
                'Overdue payments retrieved successfully'
            );
        } catch (\Exception $e) {
            return $this->serverErrorResponse('Failed to retrieve overdue payments: ' . $e->getMessage());
        }
    }

    /**
     * Get payments due today (admin view)
     */
    public function dueTodayPayments(Request $request): JsonResponse
    {
        try {
            $user = Auth::user();
            if (!$user || $user->role_type !== 3) { // 3=admin
                return $this->forbiddenResponse('Only admins can view payments due today');
            }

            $dueTodayPayments = $this->paymentService->getPaymentsDueToday();

            return $this->successResponse(
                $dueTodayPayments->map(fn($payment) => $this->paymentService->formatPaymentForResponse($payment)),
                'Payments due today retrieved successfully'
            );
        } catch (\Exception $e) {
            return $this->serverErrorResponse('Failed to retrieve payments due today: ' . $e->getMessage());
        }
    }
}
