<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Language;
use Exception;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\JsonResponse;
use Yajra\DataTables\Facades\DataTables;

class LanguageController extends Controller
{
    public function index()
    {
        $languages = Language::orderBy('created_at', 'desc')->get();

        return view('admin.languages.index', compact('languages'));
    }

    public function getLanguageList(Request $request)
    {
        $sqlBuilder = Language::select([
            'languages.id',
            'languages.name',
            'languages.name_ar',
            'languages.code',
            'languages.status',
        ]);

        return DataTables::of($sqlBuilder)
            ->filter(function ($query) use ($request) {
                if ($request->has('search') && !empty($request->search['value'])) {
                    $query->where('languages.name', 'ilike', "%" . $request->search['value'] . "%")
                    ->orWhere('languages.name_ar', 'ilike', "%" . $request->search['value'] . "%")
                    ->orWhere('languages.code', 'ilike', "%" . $request->search['value'] . "%");
                }
            })
            ->editColumn('status', function ($data) {
                return '<div class="status">
                <div class="form-check form-switch ">
                    <input class="form-check-input status-checkbox" type="checkbox" role="switch" id="SwitchCheck4" data-url="' . route('admin.languages.status', ['id' => $data->id]) . '" data-id="' . $data->id . '" ' . (!empty($data->status) && $data->status == 1 ? 'checked' : '') . ' />
                </div>
            </div>';
            })
            ->addColumn('action', function ($data) {
                $html = '<div class="dropdown">
                                        <a href="#" class="btn btn-soft-secondary btn-sm" role="button" id="dropdownMenuLink5" data-bs-toggle="dropdown" aria-expanded="false">
                                            <i class="ri-more-2-fill"></i>
                                        </a>
                                        <ul class="dropdown-menu" aria-labelledby="dropdownMenuLink5">
                                            <li><a class="dropdown-item" href="' . route('admin.languages.edit', ['id' => $data->id]) . '">Edit</a></li>
                                            <li><a class="dropdown-item delete-btn" data-url="' . route('admin.languages.destroy', ['id' => $data->id]) . '">Delete</a></li>
                                        </ul>
                                    </div>';
                return $html;
            })
            ->rawColumns(['status', 'action'])
            ->make(true);
    }

    public function create()
    {
        $language = "";

        return view('admin.languages.create', compact('language'));
    }

    public function store(Request $request)
    {
        $rules = [
            'name' => 'required|string|max:255',
            'name_ar' => 'required|string|max:255',
            'code' => 'required|string|max:10',
            'status' => 'required|in:0,1',
        ];

        $validator = Validator::make($request->all(), $rules);

        if ($validator->fails()) {
            return response()->json([
                'status' => 'error',
                'errors' => $validator->errors(),
            ], 422);
        }

        if ($request->id) {
            $language = Language::find($request->id);

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

            $language->name = $request->name;
            $language->name_ar = $request->name_ar;
            $language->code = $request->code;
            $language->status = $request->status;
            $language->save();

            return response()->json(['status' => 'success', 'message' => 'Language updated successfully']);
        } else {
            $existingLanguage = Language::where('code', $request->code)->first();
            if ($existingLanguage) {
                return response()->json([
                    'status' => 'error',
                    'errors' => [
                        'code' => ['The language code already exists.']
                    ]
                ], 422);
            }
            
            $language = Language::create([
                'name' => $request->name,
                'name_ar' => $request->name_ar,
                'code' => $request->code,
                'status' => $request->status,
            ]);

            return response()->json(['status' => 'success', 'message' => 'Language added successfully', 'language' => $language]);
        }
    }

    public function edit($id)
    {
        $language = Language::findOrFail($id);

        return view('admin.languages.create', compact('language'));
    }

    public function destroy($id): JsonResponse
    {
        try {
            $language = Language::findOrFail($id);
            $language->delete();
            return response()->json([
                'status' => 'success',
                'message' => 'Language deleted successfully.'
            ], 200);
        } catch (ModelNotFoundException $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'Language not found.'
            ], 404);
        } catch (Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => 'An error occurred while deleting the language.'
            ], 500);
        }
    }

    public function statusChange(Request $request, $id)
    {
        $language = Language::find($id);

        if (!$language) {
            return response()->json([
                'status' => 'error',
                'message' => 'Language not found.'
            ], 404);
        }

        $language->status = $request->status;
        $language->save();

        return response()->json([
            'status' => 'success',
            'message' => 'Language status updated successfully.'
        ]);
    }
}
