<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admin\Language;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class LanguageController extends Controller
{
    /*
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = Language::get();
        return view("admin.language.index", compact('data'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $languages = getLanguages();
        return view("admin.language.create", compact('languages'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(LanguageFiles $langFile, Request $request)
    {
        $validator = Validator::make($request->all(), [
            'abbr' => 'required|unique:languages',
            'name' => 'required',
            'direction' => 'required',
        ]);
        
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();

        } else {
            
            $language = new Language;
            $language->abbr = $request->abbr;
            $language->name = $request->name;
            $language->flag = $request->flag;
            $language->date_format = $request->date_format;
            $language->datetime_format = $request->datetime_format;
            $language->direction = $request->direction;
            $language->status = $request->has('status') ? '1': '0';
            $language->is_default = $request->has('default') ? '1': '0';

            if ($language->save()) {
                if ($request->default) {
                    Language::where("id", "!=", $language->id)->update(['is_default' => '0']);
                }

                $langFile->copyFiles('en', $request->abbr);
                return redirect()->back()->with('successMsg','New Language Added Successfully');

            }else{
                return redirect()->back()->with('errorMsg','Internal Server Error');
            }
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\admin\Language  $language
     * @return \Illuminate\Http\Response
     */
    public function show(Language $language)
    {
        
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\admin\Language  $language
     * @return \Illuminate\Http\Response
     */
    public function edit(Language $language, $id)
    {
        $language = Language::findOrFail($id);
        $languages = getLanguages();
        return view("admin.language.edit", compact('languages', 'language'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\admin\Language  $language
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $id = intval($request->id);
        
        $language = Language::findOrFail($id);

        $niceNames = array(
            'abbr' => "language"
        );
        $validator = Validator::make($request->all(), [
            'abbr' => ['required', Rule::unique('languages')->ignore($id)],
            'name' => 'required',
            'direction' => 'required',
        ]);
        $validator->setAttributeNames($niceNames); 
        
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();

        } else {
            
            $language->abbr = $request->abbr;
            $language->name = $request->name;
            $language->flag = $request->flag;
            $language->date_format = $request->date_format;
            $language->datetime_format = $request->datetime_format;
            $language->direction = $request->direction;
            $language->status = $request->has('status') ? '1': '0';
            $language->is_default = $request->has('default') ? '1': '0';

            if ($language->update()) {
                if ($request->default) {
                    Language::where("id", "!=", $id)->update(['is_default' => '0']);
                }
                
                return redirect()->back()->with('successMsg','Record Updated Successfully');

            }else{
                return redirect()->back()->with('errorMsg','Internal Server Error');
            }
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\admin\Language  $language
     * @return \Illuminate\Http\Response
     */
    public function destroy(Language $language)
    {
        //
    }


    public function showTexts(LanguageFiles $langFile, $lang = '', $file = 'site')
	{
		// SECURITY
		// Check if that file isn't forbidden in the config file
		// if (in_array($file, (array)config('folder.folder.file'))) {
		// 	abort('403', trans('admin.cant_edit_online'));
		// }
		
		if ($lang) {
			$langFile->setLanguage($lang);
		}
		
		// Set language file & Get its content
		$langFile->setFile($file);
        $langFiles = $langFile->getLangFiles();
		$translation = $langFile->getFileContent();
		
		// Check if the server can handle all input variables
		if (is_array($translation)) {
			$guaranteedMaxInputVars = count($translation) * 2;
			if (!$langFile->checkIfAllInputsCanBeHandled($guaranteedMaxInputVars)) {
				return redirect()->back();
			}
		}
		
		$languages = Language::all();
		return view('admin.language.translation', compact('translation', 'languages', 'langFile', 'langFiles'));
	}

    public function updateTexts(LanguageFiles $langFile, Request $request, $lang = '', $file = 'site')
	{
		// SECURITY
		// Check if that file isn't forbidden in the config file
		// if (in_array($file, (array)config('folder.folder.file'))) {
		// 	abort('403', trans('admin.cant_edit_online'));
		// }
		
		$message = trans('error.error_general');
		$status = false;
		
		if ($lang) {
			$langFile->setLanguage($lang);
		}
		
		$langFile->setFile($file);
		
		// Check if the server can handle all input variables
		$guaranteedMaxInputVars = is_array($request->all()) ? count($request->all()) : 0;
		if (!$langFile->checkIfAllInputsCanBeHandled($guaranteedMaxInputVars)) {
			return redirect()->back();
		}
		
		$fields = $langFile->testFields($request->all());
		if (empty($fields)) {
			if ($langFile->setFileContent($request->all())) {
                return redirect()->back()->with('successMsg', 'Record Updated Successfully');
				// Alert::success(trans('admin.saved'))->flash();
				$status = true;
			}
		} else {
			$message = trans('All fields are required');
            return redirect()->back()->with('errorMsg', $message);
			// Alert::error(trans('admin.please_fill_all_fields'))->flash();
		}
		
		return redirect()->back();
	}
    
}
