<?php

namespace App\Http\Controllers;

use App\Models\Order;
use App\Models\ProductVariant;
use App\Models\User;
use App\Services\FulfillmentService;
use App\Services\ProviderFulfillmentService;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use RuntimeException;

class AdminBulkActionController extends Controller
{
    public function orders(Request $request, FulfillmentService $fulfillment, ProviderFulfillmentService $providers)
    {
        $payload = $request->validate([
            'action' => ['required', Rule::in(['mark_paid', 'complete', 'provider_fulfill'])],
            'ids' => ['required', 'array', 'min:1'],
            'ids.*' => ['integer', 'exists:orders,id'],
        ]);

        $orders = Order::with('items.productVariant.providerMappings.provider')->whereIn('id', $payload['ids'])->get();
        $failed = [];

        foreach ($orders as $order) {
            if ($payload['action'] === 'mark_paid') {
                $fulfillment->markPaid($order, $request->user());
            }

            if ($payload['action'] === 'complete') {
                $fulfillment->complete($order, $request->user());
            }

            if ($payload['action'] === 'provider_fulfill') {
                try {
                    $providers->fulfillOrder($order, $request->user());
                } catch (RuntimeException $exception) {
                    $failed[] = $order->order_number.': '.$exception->getMessage();
                }
            }
        }

        if ($failed !== []) {
            return back()
                ->with('status', 'تم تنفيذ الإجراء الجماعي مع وجود طلبات تحتاج مراجعة.')
                ->withErrors(['bulk' => implode(' | ', array_slice($failed, 0, 5))]);
        }

        return back()->with('status', 'تم تنفيذ الإجراء الجماعي على الطلبات.');
    }

    public function products(Request $request)
    {
        $payload = $request->validate([
            'action' => ['required', Rule::in(['activate', 'deactivate', 'feature', 'unfeature', 'best_seller', 'not_best_seller'])],
            'ids' => ['required', 'array', 'min:1'],
            'ids.*' => ['integer', 'exists:product_variants,id'],
        ]);

        $updates = match ($payload['action']) {
            'activate' => ['status' => 'active'],
            'deactivate' => ['status' => 'inactive'],
            'feature' => ['is_featured' => true],
            'unfeature' => ['is_featured' => false],
            'best_seller' => ['is_best_seller' => true],
            'not_best_seller' => ['is_best_seller' => false],
        };

        ProductVariant::whereIn('id', $payload['ids'])->update($updates);

        return back()->with('status', 'تم تنفيذ الإجراء الجماعي على المنتجات.');
    }

    public function customers(Request $request)
    {
        $payload = $request->validate([
            'action' => ['required', Rule::in(['activate', 'suspend', 'freeze_wallets', 'unfreeze_wallets'])],
            'ids' => ['required', 'array', 'min:1'],
            'ids.*' => ['integer', 'exists:users,id'],
        ]);

        $customers = User::where('role', '!=', 'admin')->whereIn('id', $payload['ids'])->with('wallet')->get();

        foreach ($customers as $customer) {
            if ($payload['action'] === 'activate') {
                $customer->update(['status' => 'active']);
            }

            if ($payload['action'] === 'suspend') {
                $customer->update(['status' => 'suspended']);
            }

            if (in_array($payload['action'], ['freeze_wallets', 'suspend'], true)) {
                $customer->wallet?->update(['is_frozen' => true]);
            }

            if (in_array($payload['action'], ['unfreeze_wallets', 'activate'], true)) {
                $customer->wallet?->update(['is_frozen' => false]);
            }
        }

        return back()->with('status', 'تم تنفيذ الإجراء الجماعي على العملاء.');
    }
}
