<?php

namespace App\Http\Controllers\API\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\Restaurant;
use App\Services\SuperAdminOrderControlService;
use Illuminate\Http\Request;

class OrderControlController extends Controller
{
    public function forceCancel(Request $request, Order $order)
    {
        $validated = $request->validate([
            'reason' => 'required|string|max:500'
        ]);

        $result = SuperAdminOrderControlService::forceCancel($order, $validated['reason']);

        return response()->json($result, $result['success'] ? 200 : 422);
    }

    public function reassignDeliveryBoy(Request $request, Order $order)
    {
        $validated = $request->validate([
            'delivery_boy_id' => 'required|exists:users,id',
            'reason' => 'required|string|max:500'
        ]);

        $result = SuperAdminOrderControlService::reassignDeliveryBoy(
            $order, 
            $validated['delivery_boy_id'], 
            $validated['reason']
        );

        return response()->json($result, $result['success'] ? 200 : 422);
    }

    public function processRefund(Request $request, Order $order)
    {
        $validated = $request->validate([
            'refund_amount' => 'required|numeric|min:0.01|max:' . $order->total,
            'reason' => 'required|string|max:500'
        ]);

        $result = SuperAdminOrderControlService::processManualRefund(
            $order, 
            $validated['refund_amount'], 
            $validated['reason']
        );

        return response()->json($result, $result['success'] ? 200 : 422);
    }

    public function blockRestaurant(Request $request, Restaurant $restaurant)
    {
        $validated = $request->validate([
            'reason' => 'required|string|max:500',
            'duration_hours' => 'nullable|integer|min:1|max:720'
        ]);

        $result = SuperAdminOrderControlService::blockRestaurant(
            $restaurant, 
            $validated['reason'], 
            $validated['duration_hours'] ?? null
        );

        return response()->json($result, $result['success'] ? 200 : 422);
    }

    public function unblockRestaurant(Request $request, Restaurant $restaurant)
    {
        $validated = $request->validate([
            'reason' => 'required|string|max:500'
        ]);

        $result = SuperAdminOrderControlService::unblockRestaurant($restaurant, $validated['reason']);

        return response()->json($result, $result['success'] ? 200 : 422);
    }

    public function getAvailableDeliveryBoys(Order $order)
    {
        $deliveryBoys = SuperAdminOrderControlService::getAvailableDeliveryBoys($order);

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

    public function getBlockedRestaurants()
    {
        $blockedRestaurants = SuperAdminOrderControlService::getBlockedRestaurants();

        return response()->json([
            'success' => true,
            'data' => $blockedRestaurants
        ]);
    }

    public function getOrderActions(Order $order)
    {
        $availableActions = [];

        if (!in_array($order->status, ['cancelled', 'delivered'])) {
            $availableActions[] = 'force_cancel';
        }

        if (in_array($order->status, ['accepted', 'preparing', 'ready_for_pickup', 'picked_up'])) {
            $availableActions[] = 'reassign_delivery';
        }

        if (in_array($order->status, ['delivered', 'cancelled']) && $order->refund_amount == 0) {
            $availableActions[] = 'manual_refund';
        }

        return response()->json([
            'success' => true,
            'data' => [
                'order_id' => $order->id,
                'current_status' => $order->status,
                'available_actions' => $availableActions,
                'delivery_boy' => $order->delivery?->deliveryBoy?->name ?? 'Not Assigned',
                'restaurant_blocked' => $order->restaurant->is_blocked ?? false
            ]
        ]);
    }

    public function bulkActions(Request $request)
    {
        $validated = $request->validate([
            'order_ids' => 'required|array|min:1',
            'order_ids.*' => 'exists:orders,id',
            'action' => 'required|in:force_cancel,block_restaurant',
            'reason' => 'required|string|max:500',
            'duration_hours' => 'nullable|integer|min:1|max:720'
        ]);

        $orders = Order::whereIn('id', $validated['order_ids'])->get();
        $results = [];

        foreach ($orders as $order) {
            switch ($validated['action']) {
                case 'force_cancel':
                    $result = SuperAdminOrderControlService::forceCancel($order, $validated['reason']);
                    break;
                case 'block_restaurant':
                    $result = SuperAdminOrderControlService::blockRestaurant(
                        $order->restaurant, 
                        $validated['reason'], 
                        $validated['duration_hours'] ?? null
                    );
                    break;
            }
            
            $results[] = [
                'order_id' => $order->id,
                'success' => $result['success'],
                'message' => $result['message']
            ];
        }

        $successCount = collect($results)->where('success', true)->count();

        return response()->json([
            'success' => true,
            'message' => "{$successCount} out of " . count($results) . " actions completed successfully",
            'data' => $results
        ]);
    }
}