<?php

namespace App\Http\Controllers;

use App\Models\LanguageTranslation;
use App\Models\Language;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Validator;

class LanguageTranslationController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): JsonResponse
    {
        try {
            $query = LanguageTranslation::with('language');

            // Filter by language code
            if ($request->has('language_code')) {
                $query->byLanguage($request->get('language_code'));
            }

            // Filter by page section
            if ($request->has('page_section')) {
                $query->bySection($request->get('page_section'));
            }

            // Search by translation key or value
            if ($request->has('search')) {
                $search = $request->get('search');
                $query->where(function($q) use ($search) {
                    $q->where('translation_key', 'like', "%{$search}%")
                      ->orWhere('translation_value', 'like', "%{$search}%");
                });
            }

            // Order by
            $orderBy = $request->get('order_by', 'translation_key');
            $orderDirection = $request->get('order_direction', 'asc');
            $query->orderBy($orderBy, $orderDirection);

            // Pagination
            $perPage = $request->get('per_page', 10);
            $translations = $query->paginate($perPage);

            return response()->json([
                'success' => true,
                'data' => $translations->items(),
                'pagination' => [
                    'current_page' => $translations->currentPage(),
                    'per_page' => $translations->perPage(),
                    'total' => $translations->total(),
                    'last_page' => $translations->lastPage(),
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch translations',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Get all translations without pagination
     */
    public function getAll(Request $request): JsonResponse
    {
        try {
            $query = LanguageTranslation::with('language');

            // Filter by language code
            if ($request->has('language_code')) {
                $query->byLanguage($request->get('language_code'));
            }

            // Filter by page section
            if ($request->has('page_section')) {
                $query->bySection($request->get('page_section'));
            }

            // Search by translation key or value
            if ($request->has('search')) {
                $search = $request->get('search');
                $query->where(function($q) use ($search) {
                    $q->where('translation_key', 'like', "%{$search}%")
                      ->orWhere('translation_value', 'like', "%{$search}%");
                });
            }

            // Order by
            $orderBy = $request->get('order_by', 'translation_key');
            $orderDirection = $request->get('order_direction', 'asc');
            $query->orderBy($orderBy, $orderDirection);

            // Get all data without pagination
            $translations = $query->get();

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

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch all translations',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'language_code' => 'required|string|max:10|exists:languages,language_code',
                'translation_key' => 'required|string|max:255',
                'translation_value' => 'required|string',
                'page_section' => 'nullable|string|max:100'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            // Check if translation already exists for this language and key
            $existingTranslation = LanguageTranslation::where('language_code', $request->language_code)
                ->where('translation_key', $request->translation_key)
                ->first();

            if ($existingTranslation) {
                return response()->json([
                    'success' => false,
                    'message' => 'Translation already exists for this language and key'
                ], 422);
            }

            $translation = LanguageTranslation::create($validator->validated());
            $translation->load('language');

            return response()->json([
                'success' => true,
                'message' => 'Translation created successfully',
                'data' => $translation
            ], 201);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to create translation',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(Request $request, string $id): JsonResponse
    {
        try {
            $translation = LanguageTranslation::with('language')->find($id);

            if (!$translation) {
                return response()->json([
                    'success' => false,
                    'message' => 'Translation not found'
                ], 404);
            }

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

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch translation',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id): JsonResponse
    {
        try {
            $translation = LanguageTranslation::find($id);

            if (!$translation) {
                return response()->json([
                    'success' => false,
                    'message' => 'Translation not found'
                ], 404);
            }

            $validator = Validator::make($request->all(), [
                'language_code' => 'sometimes|string|max:10|exists:languages,language_code',
                'translation_key' => 'sometimes|string|max:255',
                'translation_value' => 'sometimes|string',
                'page_section' => 'nullable|string|max:100'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            $validated = $validator->validated();

            // Check if translation key already exists for this language (if key is being updated)
            if (isset($validated['translation_key']) && $validated['translation_key'] !== $translation->translation_key) {
                $existingTranslation = LanguageTranslation::where('language_code', $validated['language_code'] ?? $translation->language_code)
                    ->where('translation_key', $validated['translation_key'])
                    ->where('translation_id', '!=', $id)
                    ->first();

                if ($existingTranslation) {
                    return response()->json([
                        'success' => false,
                        'message' => 'Translation key already exists for this language'
                    ], 422);
                }
            }

            $translation->update($validated);
            $translation->load('language');

            return response()->json([
                'success' => true,
                'message' => 'Translation updated successfully',
                'data' => $translation
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to update translation',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Request $request, string $id): JsonResponse
    {
        try {
            $translation = LanguageTranslation::find($id);

            if (!$translation) {
                return response()->json([
                    'success' => false,
                    'message' => 'Translation not found'
                ], 404);
            }

            $translation->delete();

            return response()->json([
                'success' => true,
                'message' => 'Translation deleted successfully'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to delete translation',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Get translations by language code
     */
    public function getByLanguage(Request $request, string $languageCode): JsonResponse
    {
        try {
            $language = Language::where('language_code', $languageCode)->active()->first();

            if (!$language) {
                return response()->json([
                    'success' => false,
                    'message' => 'Language not found or inactive'
                ], 404);
            }

            $groupBySection = $request->boolean('group_by_section', false);

            if ($groupBySection) {
                $translations = LanguageTranslation::getTranslationsBySection($languageCode);
            } else {
                $translations = LanguageTranslation::getAllTranslations($languageCode);
            }

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

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch translations by language',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Get translation by key and language
     */
    public function getByKey(Request $request, string $languageCode, string $key): JsonResponse
    {
        try {
            $translation = LanguageTranslation::with('language')
                ->where('language_code', $languageCode)
                ->where('translation_key', $key)
                ->first();

            if (!$translation) {
                return response()->json([
                    'success' => false,
                    'message' => 'Translation not found'
                ], 404);
            }

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

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch translation',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Get translations by section
     */
    public function getBySection(Request $request, string $languageCode, string $section): JsonResponse
    {
        try {
            $translations = LanguageTranslation::with('language')
                ->where('language_code', $languageCode)
                ->where('page_section', $section)
                ->orderBy('translation_key', 'asc')
                ->get();

            return response()->json([
                'success' => true,
                'data' => [
                    'language_code' => $languageCode,
                    'section' => $section,
                    'translations' => $translations
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch translations by section',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Bulk create/update translations
     */
    public function bulkUpdate(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'language_code' => 'required|string|max:10|exists:languages,language_code',
                'translations' => 'required|array',
                'translations.*.key' => 'required|string|max:255',
                'translations.*.value' => 'required|string',
                'translations.*.section' => 'nullable|string|max:100'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            $validated = $validator->validated();
            $created = 0;
            $updated = 0;

            foreach ($validated['translations'] as $translationData) {
                $translation = LanguageTranslation::where('language_code', $validated['language_code'])
                    ->where('translation_key', $translationData['key'])
                    ->first();

                if ($translation) {
                    // Update existing translation
                    $translation->update([
                        'translation_value' => $translationData['value'],
                        'page_section' => $translationData['section'] ?? $translation->page_section
                    ]);
                    $updated++;
                } else {
                    // Create new translation
                    LanguageTranslation::create([
                        'language_code' => $validated['language_code'],
                        'translation_key' => $translationData['key'],
                        'translation_value' => $translationData['value'],
                        'page_section' => $translationData['section'] ?? null
                    ]);
                    $created++;
                }
            }

            return response()->json([
                'success' => true,
                'message' => 'Translations processed successfully',
                'data' => [
                    'created' => $created,
                    'updated' => $updated,
                    'total' => $created + $updated
                ]
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to process bulk translations',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Get available page sections
     */
    public function getSections(Request $request): JsonResponse
    {
        try {
            $sections = LanguageTranslation::distinct()
                ->whereNotNull('page_section')
                ->orderBy('page_section', 'asc')
                ->pluck('page_section');

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

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch sections',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }
}
