<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Controller;
use App\Models\Store;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class StoreController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = Store::with(['user:id,name,email', 'province', 'city']);

        if ($request->has('is_approved')) {
            $query->where('is_approved', filter_var($request->is_approved, FILTER_VALIDATE_BOOLEAN));
        }

        if ($request->has('is_active')) {
            $query->where('is_active', filter_var($request->is_active, FILTER_VALIDATE_BOOLEAN));
        }

        if ($request->has('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhereHas('user', function ($uq) use ($search) {
                      $uq->where('name', 'like', "%{$search}%")
                         ->orWhere('email', 'like', "%{$search}%");
                  });
            });
        }

        $stores = $query->withCount('products')->orderByDesc('created_at')->paginate(20);

        return response()->json($stores);
    }

    public function show(Store $store): JsonResponse
    {
        $store->load([
            'user:id,name,email,phone,avatar',
            'province',
            'city',
            'images',
            'products' => function ($q) {
                $q->with('category')->orderByDesc('created_at');
            },
        ]);

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

    public function approve(Store $store): JsonResponse
    {
        $store->update(['is_approved' => true]);

        return response()->json([
            'message' => 'Mağaza onaylandı.',
            'data' => $store,
        ]);
    }

    public function reject(Store $store): JsonResponse
    {
        $store->update(['is_approved' => false]);

        return response()->json([
            'message' => 'Mağaza onayı kaldırıldı.',
            'data' => $store,
        ]);
    }

    public function toggleActive(Store $store): JsonResponse
    {
        $store->update(['is_active' => !$store->is_active]);

        return response()->json([
            'message' => $store->is_active ? 'Mağaza aktif edildi.' : 'Mağaza devre dışı bırakıldı.',
            'data' => $store,
        ]);
    }

    public function destroy(Store $store): JsonResponse
    {
        $store->delete();

        return response()->json(['message' => 'Mağaza silindi.']);
    }
}
