<?php

namespace App\Http\Controllers\API\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Models\DeliveryBoy;
use Illuminate\Http\Request;

class DeliveryBoyCommissionController extends Controller
{
    public function index()
    {
        $deliveryBoys = DeliveryBoy::with('user')
            ->select('id', 'user_id', 'full_name', 'phone', 'commission_rate', 'total_deliveries', 'status')
            ->get()
            ->map(function ($boy) {
                return [
                    'id' => $boy->id,
                    'name' => $boy->full_name,
                    'phone' => $boy->phone,
                    'email' => $boy->user->email ?? 'N/A',
                    'commission_rate' => $boy->commission_rate,
                    'total_deliveries' => $boy->total_deliveries,
                    'status' => $boy->status,
                ];
            });

        return response()->json(['data' => $deliveryBoys]);
    }

    public function updateCommission(Request $request, $id)
    {
        $request->validate([
            'commission_rate' => 'required|numeric|min:0|max:100',
        ]);

        $deliveryBoy = DeliveryBoy::findOrFail($id);
        $deliveryBoy->update([
            'commission_rate' => $request->commission_rate,
        ]);

        return response()->json([
            'message' => 'Commission rate updated successfully',
            'data' => $deliveryBoy,
        ]);
    }

    public function earnings($id)
    {
        $deliveryBoy = DeliveryBoy::findOrFail($id);

        $earnings = \DB::table('delivery_boy_earnings')
            ->where('delivery_boy_id', $id)
            ->where('status', '!=', 'cancelled')
            ->select(
                \DB::raw('SUM(amount) as total'),
                \DB::raw('COUNT(*) as count')
            )
            ->first();

        $monthEarnings = \DB::table('delivery_boy_earnings')
            ->where('delivery_boy_id', $id)
            ->where('status', '!=', 'cancelled')
            ->whereMonth('created_at', now()->month)
            ->whereYear('created_at', now()->year)
            ->sum('amount');

        return response()->json([
            'delivery_boy' => [
                'id' => $deliveryBoy->id,
                'name' => $deliveryBoy->full_name,
                'commission_rate' => $deliveryBoy->commission_rate,
            ],
            'total_earnings' => round($earnings->total ?? 0, 2),
            'total_deliveries' => $earnings->count ?? 0,
            'month_earnings' => round($monthEarnings ?? 0, 2),
        ]);
    }

    public function allEarnings(Request $request)
    {
        $perPage = $request->get('per_page', 15);
        $search = $request->get('search');
        $status = $request->get('status');
        $dateFrom = $request->get('date_from');
        $dateTo = $request->get('date_to');
        $deliveryBoyId = $request->get('delivery_boy_id');

        $query = \DB::table('delivery_boy_earnings')
            ->join('delivery_boys', 'delivery_boy_earnings.delivery_boy_id', '=', 'delivery_boys.id')
            ->leftJoin('orders', 'delivery_boy_earnings.order_id', '=', 'orders.id')
            ->select(
                'delivery_boy_earnings.*',
                'delivery_boys.full_name as delivery_boy_name',
                'delivery_boys.phone as delivery_boy_phone',
                'orders.order_number'
            );

        if ($search) {
            $query->where(function ($q) use ($search) {
                $q->where('delivery_boys.full_name', 'like', "%{$search}%")
                  ->orWhere('delivery_boys.phone', 'like', "%{$search}%")
                  ->orWhere('orders.order_number', 'like', "%{$search}%");
            });
        }

        if ($status) {
            $query->where('delivery_boy_earnings.status', $status);
        }

        if ($dateFrom) {
            $query->whereDate('delivery_boy_earnings.created_at', '>=', $dateFrom);
        }

        if ($dateTo) {
            $query->whereDate('delivery_boy_earnings.created_at', '<=', $dateTo);
        }

        if ($deliveryBoyId) {
            $query->where('delivery_boy_earnings.delivery_boy_id', $deliveryBoyId);
        }

        $earnings = $query->orderBy('delivery_boy_earnings.created_at', 'desc')
            ->paginate($perPage);

        // Summary stats
        $stats = [
            'total_earnings' => \DB::table('delivery_boy_earnings')
                ->where('status', '!=', 'cancelled')
                ->sum('amount'),
            'pending_earnings' => \DB::table('delivery_boy_earnings')
                ->where('status', 'pending')
                ->sum('amount'),
            'paid_earnings' => \DB::table('delivery_boy_earnings')
                ->where('status', 'paid')
                ->sum('amount'),
            'total_deliveries' => \DB::table('delivery_boy_earnings')
                ->where('status', '!=', 'cancelled')
                ->count(),
        ];

        return response()->json([
            'data' => $earnings->items(),
            'pagination' => [
                'total' => $earnings->total(),
                'per_page' => $earnings->perPage(),
                'current_page' => $earnings->currentPage(),
                'last_page' => $earnings->lastPage(),
            ],
            'stats' => $stats,
        ]);
    }

    public function updateEarningStatus(Request $request, $id)
    {
        $request->validate([
            'status' => 'required|in:pending,paid,cancelled',
            'payment_method' => 'nullable|in:cash,bank_transfer,wallet',
            'transaction_id' => 'nullable|string',
        ]);

        $earning = \DB::table('delivery_boy_earnings')->where('id', $id)->first();
        
        if (!$earning) {
            return response()->json(['message' => 'Earning not found'], 404);
        }

        \DB::table('delivery_boy_earnings')
            ->where('id', $id)
            ->update([
                'status' => $request->status,
                'payment_date' => $request->status === 'paid' ? now() : null,
                'payment_method' => $request->payment_method,
                'transaction_id' => $request->transaction_id,
                'updated_at' => now(),
            ]);

        return response()->json(['message' => 'Earning status updated successfully']);
    }
}
