<?php

namespace App\Http\Controllers;

use App\Models\Game;
use App\Models\ProductVariant;
use App\Models\AnalyticsEvent;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;

class AdminProductController extends Controller
{
    public function index(Request $request)
    {
        $query = trim((string) $request->query('q', ''));
        $status = (string) $request->query('status', '');
        $delivery = (string) $request->query('delivery_method', '');
        $stock = (string) $request->query('stock', '');
        $productsQuery = ProductVariant::query()
            ->with('game')
            ->when($query !== '', fn ($builder) => $builder
                ->where('name_ar', 'like', "%{$query}%")
                ->orWhere('name_en', 'like', "%{$query}%")
                ->orWhere('sku', 'like', "%{$query}%")
                ->orWhereHas('game', fn ($game) => $game->where('name_ar', 'like', "%{$query}%")->orWhere('name_en', 'like', "%{$query}%")))
            ->when($status, fn ($builder) => $builder->where('status', $status))
            ->when($delivery, fn ($builder) => $builder->where('delivery_method', $delivery))
            ->when($stock === 'low', fn ($builder) => $builder->whereColumn('stock_available', '<=', 'min_stock_alert'));

        return view('admin.products.index', [
            'products' => (clone $productsQuery)->latest()->paginate(20)->withQueryString(),
            'summary' => [
                'total' => ProductVariant::count(),
                'active' => ProductVariant::where('status', 'active')->count(),
                'inactive' => ProductVariant::where('status', 'inactive')->count(),
                'lowStock' => ProductVariant::whereColumn('stock_available', '<=', 'min_stock_alert')->count(),
                'storedCodes' => ProductVariant::where('delivery_method', 'stored_code')->count(),
                'avgMargin' => ProductVariant::where('price_minor', '>', 0)->selectRaw('avg((price_minor - cost_minor) * 100.0 / price_minor) as margin')->value('margin') ?? 0,
            ],
            'query' => $query,
            'status' => $status,
            'delivery' => $delivery,
            'stock' => $stock,
        ]);
    }

    public function create()
    {
        return view('admin.products.form', [
            'product' => new ProductVariant([
                'delivery_method' => 'manual',
                'currency_code' => 'EGP',
                'quantity' => 1,
                'unit_ar' => 'وحدة',
                'unit_en' => 'Unit',
                'status' => 'active',
                'stock_available' => 100,
                'min_stock_alert' => 5,
            ]),
            'games' => Game::where('is_active', true)->orderBy('name_ar')->get(),
        ]);
    }

    public function store(Request $request)
    {
        ProductVariant::create($this->validatedData($request));

        return redirect()->route('admin.products.index')->with('status', 'تم إنشاء المنتج.');
    }

    public function edit(ProductVariant $productVariant)
    {
        return view('admin.products.form', [
            'product' => $productVariant,
            'games' => Game::where('is_active', true)->orderBy('name_ar')->get(),
        ]);
    }

    public function show(ProductVariant $productVariant)
    {
        $productVariant->load(['game.category', 'stockCodes' => fn ($query) => $query->latest()->limit(20)]);

        $sales = $productVariant->orderItems()
            ->selectRaw('sum(quantity) as quantity, sum(total_minor) as revenue_minor, count(distinct order_id) as orders_count')
            ->first();

        $dailySales = $productVariant->orderItems()
            ->where('created_at', '>=', now()->subDays(13)->startOfDay())
            ->selectRaw('date(created_at) as day, sum(quantity) as quantity, sum(total_minor) as revenue_minor')
            ->groupBy('day')
            ->orderBy('day')
            ->get();

        return view('admin.products.show', [
            'product' => $productVariant,
            'sales' => $sales,
            'dailySales' => $dailySales,
            'views' => AnalyticsEvent::where('event_name', 'product_view')
                ->where('entity_type', 'product_variant')
                ->where('entity_id', $productVariant->id)
                ->count(),
            'recentItems' => $productVariant->orderItems()->with('order.user')->latest()->limit(12)->get(),
            'stockBreakdown' => $productVariant->stockCodes()
                ->select('status', DB::raw('count(*) as total'))
                ->groupBy('status')
                ->pluck('total', 'status'),
        ]);
    }

    public function quickUpdate(Request $request, ProductVariant $productVariant)
    {
        $payload = $request->validate([
            'stock_available' => ['required', 'integer', 'min:0'],
            'min_stock_alert' => ['required', 'integer', 'min:0'],
            'status' => ['required', Rule::in(['active', 'inactive'])],
            'is_featured' => ['nullable', 'boolean'],
            'is_best_seller' => ['nullable', 'boolean'],
        ]);

        $payload['is_featured'] = $request->boolean('is_featured');
        $payload['is_best_seller'] = $request->boolean('is_best_seller');

        $productVariant->update($payload);

        return back()->with('status', 'تم تحديث إعدادات المنتج السريعة.');
    }

    public function update(Request $request, ProductVariant $productVariant)
    {
        $productVariant->update($this->validatedData($request, $productVariant));

        return back()->with('status', 'تم تحديث المنتج.');
    }

    public function destroy(ProductVariant $productVariant)
    {
        $productVariant->update(['status' => 'inactive']);

        return back()->with('status', 'تم تعطيل المنتج بأمان.');
    }

    private function validatedData(Request $request, ?ProductVariant $product = null): array
    {
        $data = $request->validate([
            'game_id' => ['required', 'exists:games,id'],
            'sku' => ['required', 'string', 'max:80', Rule::unique('product_variants', 'sku')->ignore($product)],
            'name_ar' => ['required', 'string', 'max:140'],
            'name_en' => ['required', 'string', 'max:140'],
            'delivery_method' => ['required', 'in:manual,api,stored_code,hybrid'],
            'quantity' => ['required', 'integer', 'min:1'],
            'unit_ar' => ['required', 'string', 'max:40'],
            'unit_en' => ['required', 'string', 'max:40'],
            'cost_minor' => ['required', 'integer', 'min:0'],
            'price_minor' => ['required', 'integer', 'min:0'],
            'sale_price_minor' => ['nullable', 'integer', 'min:0'],
            'currency_code' => ['required', 'string', 'size:3'],
            'cashback_basis_points' => ['required', 'integer', 'min:0', 'max:10000'],
            'loyalty_points' => ['required', 'integer', 'min:0'],
            'stock_available' => ['required', 'integer', 'min:0'],
            'min_stock_alert' => ['required', 'integer', 'min:0'],
            'status' => ['required', 'in:active,inactive'],
            'is_featured' => ['nullable', 'boolean'],
            'is_best_seller' => ['nullable', 'boolean'],
            'instructions_ar' => ['nullable', 'string', 'max:1500'],
            'instructions_en' => ['nullable', 'string', 'max:1500'],
        ]);

        $data['is_featured'] = $request->boolean('is_featured');
        $data['is_best_seller'] = $request->boolean('is_best_seller');

        return $data;
    }
}
