<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\DeliveryMan;
use App\Models\RiderRevenueCollection;
use App\Services\RiderWalletService;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Http\Request;

class RiderRevenueController extends Controller
{
    public function index(Request $request)
    {
        $phone = trim((string) $request->input('phone', ''));

        $ridersQuery = DeliveryMan::where('approval_status', 'approved');
        if ($phone !== '') {
            $digits = preg_replace('/\D+/', '', $phone);
            $ridersQuery->where(function ($q) use ($phone, $digits) {
                $q->where('phone', 'like', '%' . $phone . '%');
                if ($digits !== '') {
                    $q->orWhere('phone', 'like', '%' . $digits . '%');
                }
            });
        }

        $riders = $ridersQuery
            ->orderByDesc('due_product_amount')
            ->orderByDesc('due_commission_amount')
            ->get();

        $collectionsQuery = RiderRevenueCollection::with('deliveryMan')
            ->where('status', 'completed')
            ->latest();

        if ($phone !== '') {
            $riderIds = $riders->pluck('id');
            $collectionsQuery->whereIn('delivery_man_id', $riderIds);
        }

        $collections = $collectionsQuery->limit(100)->get();

        $activeTab = $request->input('tab', 'cod');
        if (!in_array($activeTab, ['cod', 'digital', 'history'], true)) {
            $activeTab = 'cod';
        }

        return view('backEnd.rider_revenue.index', compact('riders', 'collections', 'phone', 'activeTab'));
    }

    public function sendOtp(Request $request, DeliveryMan $deliveryMan, RiderWalletService $wallet)
    {
        $result = $wallet->initiateCollection($deliveryMan, auth()->id(), $request->input('note'));

        if (!$result['ok']) {
            Toastr::error($result['message'], 'Error');
            return back();
        }

        Toastr::success($result['message'] . ' (' . ($result['email_hint'] ?? 'email') . ')', 'OTP Sent');
        return back()->with('collection_rider_id', $deliveryMan->id)->withInput(['tab' => 'cod', 'phone' => $request->input('phone')]);
    }

    public function complete(Request $request, DeliveryMan $deliveryMan, RiderWalletService $wallet)
    {
        $request->validate(['otp' => 'required|string|min:4|max:10']);

        $result = $wallet->completeCollection($deliveryMan, $request->otp, auth()->id());

        if (!$result['ok']) {
            Toastr::error($result['message'], 'Error');
            return back()->with('collection_rider_id', $deliveryMan->id)->withInput(['tab' => 'cod', 'phone' => $request->input('phone')]);
        }

        Toastr::success($result['message'], 'Collected');
        return back()->withInput(['tab' => 'cod', 'phone' => $request->input('phone')]);
    }

    public function payoutDigital(Request $request, DeliveryMan $deliveryMan, RiderWalletService $wallet)
    {
        $request->validate(['amount' => 'nullable|numeric|min:0']);
        $amount = $request->filled('amount') ? (float) $request->amount : 0;
        $result = $wallet->completeDigitalPayout($deliveryMan, $amount, auth()->id());

        if (!$result['ok']) {
            Toastr::error($result['message'], 'Error');
            return back()->withInput(['tab' => 'digital', 'phone' => $request->input('phone')]);
        }

        Toastr::success($result['message'], 'Payout');
        return back()->withInput(['tab' => 'digital', 'phone' => $request->input('phone')]);
    }
}
