<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Language;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class LanguageController extends Controller
{
    /**
     * Display a listing of languages
     */
    public function index(Request $request)
    {
        $query = Language::query();

        // Search functionality
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function($q) use ($search) {
                $q->where('code', 'like', "%{$search}%")
                  ->orWhere('name', 'like', "%{$search}%")
                  ->orWhere('native_name', 'like', "%{$search}%");
            });
        }

        // Get paginated results (10 per page) with ordering
        $languages = $query->ordered()->paginate(10)->withQueryString();
        
        return view('admin.languages.index', compact('languages'));
    }

    /**
     * Store a newly created language
     */
    public function store(Request $request)
    {
        $request->validate([
            'code' => 'required|string|max:5|unique:languages,code',
            'name' => 'required|string|max:255',
            'native_name' => 'required|string|max:255',
            'order' => 'nullable|integer|min:0',
            'status' => 'required|in:draft,active',
            'is_default' => 'nullable|boolean',
        ]);

        DB::beginTransaction();
        try {
            // If this is set as default, remove default from others
            if ($request->boolean('is_default')) {
                Language::where('is_default', true)->update(['is_default' => false]);
            }

            $language = Language::create([
                'code' => $request->code,
                'name' => $request->name,
                'native_name' => $request->native_name,
                'order' => $request->order ?? 0,
                'status' => $request->status,
                'is_default' => $request->boolean('is_default'),
            ]);

            DB::commit();
            flash_success(admin_trans('language_created_successfully'));
            return redirect()->route('admin.languages.index');
        } catch (\Exception $e) {
            DB::rollBack();
            flash_error(admin_trans('error_creating_language'));
            return back()->withInput();
        }
    }

    /**
     * Update the specified language
     */
    public function update(Request $request, Language $language)
    {
        $request->validate([
            'code' => 'required|string|max:5|unique:languages,code,' . $language->id,
            'name' => 'required|string|max:255',
            'native_name' => 'required|string|max:255',
            'order' => 'nullable|integer|min:0',
            'status' => 'required|in:draft,active',
            'is_default' => 'nullable|boolean',
        ]);

        DB::beginTransaction();
        try {
            // If this is set as default, remove default from others
            if ($request->boolean('is_default')) {
                Language::where('id', '!=', $language->id)
                        ->where('is_default', true)
                        ->update(['is_default' => false]);
            }

            $language->update([
                'code' => $request->code,
                'name' => $request->name,
                'native_name' => $request->native_name,
                'order' => $request->order ?? 0,
                'status' => $request->status,
                'is_default' => $request->boolean('is_default'),
            ]);

            DB::commit();
            flash_success(admin_trans('language_updated_successfully'));
            return redirect()->route('admin.languages.index');
        } catch (\Exception $e) {
            DB::rollBack();
            flash_error(admin_trans('error_updating_language'));
            return back()->withInput();
        }
    }

    /**
     * Remove the specified language
     */
    public function destroy(Language $language)
    {
        // Prevent deleting default language
        if ($language->is_default) {
            flash_error(admin_trans('cannot_delete_default_language'));
            return back();
        }

        // Check if language has related records
        if ($language->locales()->count() > 0) {
            flash_error(admin_trans('cannot_delete_language_with_locales'));
            return back();
        }

        try {
            $language->delete();
            flash_success(admin_trans('language_deleted_successfully'));
        } catch (\Exception $e) {
            flash_error(admin_trans('error_deleting_language'));
        }

        return redirect()->route('admin.languages.index');
    }

    /**
     * Update languages order
     */
    public function updateOrder(Request $request)
    {
        $request->validate([
            'orders' => 'required|array',
            'orders.*' => 'required|integer|exists:languages,id',
        ]);

        DB::beginTransaction();
        try {
            foreach ($request->orders as $order => $id) {
                Language::where('id', $id)->update(['order' => $order]);
            }

            DB::commit();
            return response()->json(['success' => true]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['success' => false], 500);
        }
    }

    /**
     * Toggle language status
     */
    public function toggleStatus(Language $language)
    {
        try {
            $newStatus = $language->status === 'active' ? 'draft' : 'active';
            $language->update(['status' => $newStatus]);
            
            flash_success(admin_trans('language_status_updated'));
        } catch (\Exception $e) {
            flash_error(admin_trans('error_updating_status'));
        }

        return back();
    }

    /**
     * Set language as default
     */
    public function setDefault(Language $language)
    {
        DB::beginTransaction();
        try {
            // Remove default from all
            Language::where('is_default', true)->update(['is_default' => false]);
            
            // Set this as default
            $language->update(['is_default' => true]);

            DB::commit();
            flash_success(admin_trans('default_language_updated'));
        } catch (\Exception $e) {
            DB::rollBack();
            flash_error(admin_trans('error_setting_default'));
        }

        return back();
    }
}