<?php

namespace App\Http\Controllers\Api\Seller;

use App\Http\Controllers\Controller;
use App\Models\Store;
use App\Models\StoreImage;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class StoreController extends Controller
{
    public function show(Request $request): JsonResponse
    {
        $store = $request->user()->store;

        if (!$store) {
            return response()->json(['message' => 'Mağazanız bulunamadı.'], 404);
        }

        $store->load(['images', 'province', 'city', 'products' => function ($q) {
            $q->where('is_active', true);
        }]);

        return response()->json([
            'data' => $store,
            'stats' => [
                'total_products' => $store->products()->count(),
                'active_products' => $store->products()->where('is_active', true)->count(),
                'total_stock' => $store->products()->where('is_active', true)->sum('stock_quantity'),
            ],
        ]);
    }

    public function store(Request $request): JsonResponse
    {
        if ($request->user()->store) {
            return response()->json(['message' => 'Zaten bir mağazanız var.'], 422);
        }

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string|max:2000',
            'phone' => 'nullable|string|max:20',
            'whatsapp' => 'nullable|string|max:20',
            'latitude' => 'nullable|numeric|between:-90,90',
            'longitude' => 'nullable|numeric|between:-180,180',
            'address' => 'nullable|string|max:500',
            'province_id' => 'nullable|exists:provinces,id',
            'city_id' => 'nullable|exists:cities,id',
            'working_hours' => 'nullable|array',
        ]);

        $validated['user_id'] = $request->user()->id;
        $validated['slug'] = Store::generateUniqueSlug($validated['name']);
        $validated['is_approved'] = false;

        $store = Store::create($validated);
        $store->load(['province', 'city']);

        return response()->json([
            'message' => 'Mağazanız başarıyla oluşturuldu. Admin onayı bekleniyor.',
            'data' => $store,
        ], 201);
    }

    public function update(Request $request): JsonResponse
    {
        $store = $request->user()->store;

        if (!$store) {
            return response()->json(['message' => 'Mağazanız bulunamadı.'], 404);
        }

        $validated = $request->validate([
            'name' => 'sometimes|required|string|max:255',
            'description' => 'nullable|string|max:2000',
            'phone' => 'nullable|string|max:20',
            'whatsapp' => 'nullable|string|max:20',
            'latitude' => 'nullable|numeric|between:-90,90',
            'longitude' => 'nullable|numeric|between:-180,180',
            'address' => 'nullable|string|max:500',
            'province_id' => 'nullable|exists:provinces,id',
            'city_id' => 'nullable|exists:cities,id',
            'working_hours' => 'nullable|array',
        ]);

        if (isset($validated['name']) && $validated['name'] !== $store->name) {
            $validated['slug'] = Store::generateUniqueSlug($validated['name'], $store->id);
        }

        $store->update($validated);
        $store->load(['images', 'province', 'city']);

        return response()->json([
            'message' => 'Mağaza bilgileri güncellendi.',
            'data' => $store,
        ]);
    }

    public function toggleOpen(Request $request): JsonResponse
    {
        $store = $request->user()->store;

        if (!$store) {
            return response()->json(['message' => 'Mağazanız bulunamadı.'], 404);
        }

        $store->update(['is_open' => !$store->is_open]);

        return response()->json([
            'message' => $store->is_open ? 'Mağaza açıldı.' : 'Mağaza kapatıldı.',
            'data' => ['is_open' => $store->is_open],
        ]);
    }

    public function uploadLogo(Request $request): JsonResponse
    {
        $store = $request->user()->store;

        if (!$store) {
            return response()->json(['message' => 'Mağazanız bulunamadı.'], 404);
        }

        $request->validate([
            'logo' => 'required|image|mimes:jpeg,png,jpg,webp|max:2048',
        ]);

        if ($store->logo) {
            Storage::disk('public')->delete($store->logo);
        }

        $path = $request->file('logo')->store('stores/logos', 'public');
        $store->update(['logo' => $path]);

        return response()->json([
            'message' => 'Logo yüklendi.',
            'data' => ['logo' => $path],
        ]);
    }

    public function uploadCover(Request $request): JsonResponse
    {
        $store = $request->user()->store;

        if (!$store) {
            return response()->json(['message' => 'Mağazanız bulunamadı.'], 404);
        }

        $request->validate([
            'cover_image' => 'required|image|mimes:jpeg,png,jpg,webp|max:4096',
        ]);

        if ($store->cover_image) {
            Storage::disk('public')->delete($store->cover_image);
        }

        $path = $request->file('cover_image')->store('stores/covers', 'public');
        $store->update(['cover_image' => $path]);

        return response()->json([
            'message' => 'Kapak görseli yüklendi.',
            'data' => ['cover_image' => $path],
        ]);
    }

    public function uploadImages(Request $request): JsonResponse
    {
        $store = $request->user()->store;

        if (!$store) {
            return response()->json(['message' => 'Mağazanız bulunamadı.'], 404);
        }

        $request->validate([
            'images' => 'required|array|max:10',
            'images.*' => 'image|mimes:jpeg,png,jpg,webp|max:4096',
        ]);

        $uploaded = [];
        $maxSort = $store->images()->max('sort_order') ?? 0;

        foreach ($request->file('images') as $image) {
            $path = $image->store('stores/images', 'public');
            $maxSort++;
            $uploaded[] = $store->images()->create([
                'image_path' => $path,
                'sort_order' => $maxSort,
            ]);
        }

        return response()->json([
            'message' => count($uploaded) . ' görsel yüklendi.',
            'data' => $uploaded,
        ]);
    }

    public function deleteImage(Request $request, StoreImage $image): JsonResponse
    {
        $store = $request->user()->store;

        if (!$store || $image->store_id !== $store->id) {
            return response()->json(['message' => 'Bu görseli silme yetkiniz yok.'], 403);
        }

        Storage::disk('public')->delete($image->image_path);
        $image->delete();

        return response()->json(['message' => 'Görsel silindi.']);
    }
}
