<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Plan;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class PlanController extends Controller
{
    public function index(Request $request)
    {
        $allowedSort = ['id', 'name', 'slug', 'sort_order', 'created_at'];
        $sortBy = $request->query('sort', 'sort_order');
        $sortOrder = strtolower($request->query('order', 'asc')) === 'desc' ? 'desc' : 'asc';
        if (! in_array($sortBy, $allowedSort)) {
            $sortBy = 'sort_order';
        }

        $perPage = max(1, min(100, (int) $request->get('per_page', 20)));
        $search = $request->query('search');

        $query = Plan::query()->withCount('vendors')->orderBy($sortBy, $sortOrder);

        if ($search && is_string($search)) {
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', '%' . $search . '%')
                    ->orWhere('slug', 'like', '%' . $search . '%');
            });
        }

        $plans = $query->paginate($perPage);

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

    /**
     * لیست ساده پلن‌ها برای دراپ‌داون (فقط پلن‌های فعال).
     */
    public function list(Request $request)
    {
        $plans = Plan::query()
            ->where('is_active', true)
            ->orderBy('sort_order')
            ->orderBy('name')
            ->get(['id', 'name', 'slug']);

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

    public function store(Request $request)
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'slug' => [
                'required',
                'string',
                'max:100',
                'regex:/^[a-z0-9_-]+$/',
                Rule::unique('plans', 'slug'),
            ],
            'description' => ['nullable', 'string'],
            'features' => ['nullable', 'array'],
            'features.*' => ['string', 'max:255'],
            'max_users' => ['nullable', 'integer', 'min:0'],
            'max_customers' => ['nullable', 'integer', 'min:0'],
            'max_orders_per_month' => ['nullable', 'integer', 'min:0'],
            'max_transactions_per_month' => ['nullable', 'integer', 'min:0'],
            'max_metals_per_month' => ['nullable', 'integer', 'min:0'],
            'price_monthly' => ['nullable', 'numeric', 'min:0'],
            'price_yearly' => ['nullable', 'numeric', 'min:0'],
            'is_active' => ['nullable', 'boolean'],
            'sort_order' => ['nullable', 'integer', 'min:0'],
        ]);

        $plan = Plan::create([
            'name' => $data['name'],
            'slug' => $data['slug'],
            'description' => $data['description'] ?? null,
            'features' => $data['features'] ?? null,
            'max_users' => $data['max_users'] ?? null,
            'max_customers' => $data['max_customers'] ?? null,
            'max_orders_per_month' => $data['max_orders_per_month'] ?? null,
            'max_transactions_per_month' => $data['max_transactions_per_month'] ?? null,
            'max_metals_per_month' => $data['max_metals_per_month'] ?? null,
            'price_monthly' => $data['price_monthly'] ?? null,
            'price_yearly' => $data['price_yearly'] ?? null,
            'is_active' => $data['is_active'] ?? true,
            'sort_order' => $data['sort_order'] ?? 0,
        ]);

        return response()->json([
            'success' => true,
            'data' => $plan,
            'message' => 'پلن با موفقیت ایجاد شد',
        ], 201);
    }

    public function show(Plan $plan)
    {
        $plan->loadCount('vendors');

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

    public function update(Request $request, Plan $plan)
    {
        $data = $request->validate([
            'name' => ['sometimes', 'string', 'max:255'],
            'slug' => [
                'sometimes',
                'string',
                'max:100',
                'regex:/^[a-z0-9_-]+$/',
                Rule::unique('plans', 'slug')->ignore($plan->id),
            ],
            'description' => ['nullable', 'string'],
            'features' => ['nullable', 'array'],
            'features.*' => ['string', 'max:255'],
            'max_users' => ['nullable', 'integer', 'min:0'],
            'max_customers' => ['nullable', 'integer', 'min:0'],
            'max_orders_per_month' => ['nullable', 'integer', 'min:0'],
            'max_transactions_per_month' => ['nullable', 'integer', 'min:0'],
            'max_metals_per_month' => ['nullable', 'integer', 'min:0'],
            'price_monthly' => ['nullable', 'numeric', 'min:0'],
            'price_yearly' => ['nullable', 'numeric', 'min:0'],
            'is_active' => ['nullable', 'boolean'],
            'sort_order' => ['nullable', 'integer', 'min:0'],
        ]);

        $fillable = [
            'name', 'slug', 'description', 'features',
            'max_users', 'max_customers', 'max_orders_per_month',
            'max_transactions_per_month', 'max_metals_per_month',
            'price_monthly', 'price_yearly', 'is_active', 'sort_order',
        ];
        foreach ($fillable as $key) {
            if (array_key_exists($key, $data)) {
                $plan->{$key} = $data[$key];
            }
        }

        $plan->save();

        return response()->json([
            'success' => true,
            'data' => $plan->fresh(),
            'message' => 'پلن با موفقیت بروزرسانی شد',
        ]);
    }

    public function destroy(Plan $plan)
    {
        if ($plan->vendors()->exists()) {
            return response()->json([
                'success' => false,
                'message' => 'این پلن به وندورها اختصاص داده شده و قابل حذف نیست. ابتدا وندورها را به پلن دیگری منتقل کنید.',
            ], 422);
        }

        $plan->delete();

        return response()->json([
            'success' => true,
            'message' => 'پلن حذف شد',
        ]);
    }
}
