<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Extra;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;

class ExtraController extends Controller
{
    /**
     * extras tablosu yoksa oluşturur. Elle migration/SQL çalıştırmaya gerek kalmaz.
     */
    private function ensureExtrasTableExists(): void
    {
        if (Schema::hasTable('extras')) {
            return;
        }
        Schema::create('extras', function (Blueprint $table) {
            $table->id();
            $table->enum('type', ['extra', 'merchandise'])->default('extra');
            $table->json('title')->nullable();
            $table->json('description')->nullable();
            $table->decimal('price', 10, 2)->default(0);
            $table->string('image', 500)->nullable();
            $table->unsignedSmallInteger('sort_order')->default(0);
            $table->boolean('is_active')->default(true);
            $table->timestamps();
        });
        Log::info('extras table created automatically by ExtraController');
    }

    /**
     * List all extras (filter by type: extra | merchandise)
     */
    public function index(Request $request): JsonResponse
    {
        $this->ensureExtrasTableExists();
        try {
            $query = Extra::query();

            if ($request->filled('type')) {
                $type = $request->type;
                if (in_array($type, ['extra', 'merchandise'], true)) {
                    $query->where('type', $type);
                }
            }

            $items = $query->orderBy('sort_order')->orderBy('id')->get();

            return response()->json(['data' => $items]);
        } catch (\Exception $e) {
            Log::error('Extras index error: ' . $e->getMessage());
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    /**
     * Get single extra by ID
     */
    public function show(int $id): JsonResponse
    {
        $this->ensureExtrasTableExists();
        try {
            $extra = Extra::findOrFail($id);
            return response()->json(['data' => $extra]);
        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 404);
        }
    }

    /**
     * Normalize title/description to always have tr, de, en keys.
     */
    private function normalizeTitle(array $title): array
    {
        return [
            'tr' => $title['tr'] ?? '',
            'de' => $title['de'] ?? '',
            'en' => $title['en'] ?? '',
        ];
    }

    private function normalizeDescription(?array $description): array
    {
        if (!is_array($description)) {
            return ['tr' => '', 'de' => '', 'en' => ''];
        }
        return [
            'tr' => $description['tr'] ?? '',
            'de' => $description['de'] ?? '',
            'en' => $description['en'] ?? '',
        ];
    }

    /**
     * Create new extra or merchandise
     */
    public function store(Request $request): JsonResponse
    {
        $this->ensureExtrasTableExists();
        try {
            $validated = $request->validate([
                'type' => 'required|in:extra,merchandise',
                'title' => 'required|array',
                'title.tr' => 'nullable|string|max:255',
                'title.de' => 'nullable|string|max:255',
                'title.en' => 'nullable|string|max:255',
                'description' => 'nullable|array',
                'description.tr' => 'nullable|string',
                'description.de' => 'nullable|string',
                'description.en' => 'nullable|string',
                'price' => 'required|numeric|min:0',
                'image' => 'nullable|string|max:500',
                'sort_order' => 'nullable|integer|min:0',
                'is_active' => 'nullable|boolean',
            ]);

            $title = $this->normalizeTitle($validated['title']);
            $description = $this->normalizeDescription($validated['description'] ?? null);

            $extra = Extra::create([
                'type' => $validated['type'],
                'title' => $title,
                'description' => $description,
                'price' => (float) $validated['price'],
                'image' => !empty($validated['image']) ? (string) $validated['image'] : null,
                'sort_order' => (int) ($validated['sort_order'] ?? 0),
                'is_active' => $validated['is_active'] ?? true,
            ]);

            return response()->json([
                'data' => $extra,
                'message' => 'Extra created successfully'
            ], 201);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json(['error' => $e->getMessage(), 'errors' => $e->errors()], 422);
        } catch (\Exception $e) {
            Log::error('Extra create error: ' . $e->getMessage());
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    /**
     * Update extra
     */
    public function update(Request $request, int $id): JsonResponse
    {
        $this->ensureExtrasTableExists();
        try {
            $extra = Extra::findOrFail($id);

            $validated = $request->validate([
                'type' => 'sometimes|in:extra,merchandise',
                'title' => 'sometimes|array',
                'title.tr' => 'nullable|string|max:255',
                'title.de' => 'nullable|string|max:255',
                'title.en' => 'nullable|string|max:255',
                'description' => 'nullable|array',
                'description.tr' => 'nullable|string',
                'description.de' => 'nullable|string',
                'description.en' => 'nullable|string',
                'price' => 'sometimes|numeric|min:0',
                'image' => 'nullable|string|max:500',
                'sort_order' => 'nullable|integer|min:0',
                'is_active' => 'nullable|boolean',
            ]);

            $update = [];
            if (array_key_exists('type', $validated)) {
                $update['type'] = $validated['type'];
            }
            if (array_key_exists('title', $validated)) {
                $update['title'] = $this->normalizeTitle($validated['title']);
            }
            if (array_key_exists('description', $validated)) {
                $update['description'] = $this->normalizeDescription($validated['description']);
            }
            if (array_key_exists('price', $validated)) {
                $update['price'] = (float) $validated['price'];
            }
            if (array_key_exists('image', $validated)) {
                $update['image'] = !empty($validated['image']) ? (string) $validated['image'] : null;
            }
            if (array_key_exists('sort_order', $validated)) {
                $update['sort_order'] = (int) $validated['sort_order'];
            }
            if (array_key_exists('is_active', $validated)) {
                $update['is_active'] = (bool) $validated['is_active'];
            }

            $extra->update($update);

            return response()->json([
                'data' => $extra->fresh(),
                'message' => 'Extra updated successfully'
            ]);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return response()->json(['error' => $e->getMessage(), 'errors' => $e->errors()], 422);
        } catch (\Exception $e) {
            Log::error('Extra update error: ' . $e->getMessage());
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    /**
     * Delete extra
     */
    public function destroy(int $id): JsonResponse
    {
        $this->ensureExtrasTableExists();
        try {
            $extra = Extra::findOrFail($id);
            $extra->delete();
            return response()->json(['message' => 'Extra deleted successfully']);
        } catch (\Exception $e) {
            Log::error('Extra delete error: ' . $e->getMessage());
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }
}
