<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\LanguagesKeywords;

class LanguagesAPIController extends Controller
{
    /**
     * Show keysLists of settings.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function keysLists(Request $request)
    {
        try {
            $response = array();
            $lang_code = 'en';
            $lang_code = (isset($_GET['lang_code']))?$_GET['lang_code']:$lang_code;
            $translations = LanguagesKeywords::where('group','api')->where('lang_code',$lang_code)->get();
            foreach ($translations as $row) {
                $response[$row->keyword] = $row->value;
            }
            return $this->sendResponse($response, __('message_alerts.record_found'));
        } catch (\Exception $e) {
            return $this->sendError($e->getMessage(), 401);
        }
    }

    public function addNewKeys(Request $request)
    {
        try {            
            $post = $request->all();
            $lang_code = 'en';
            $lang_code = (isset($post['lang_code']))?$post['lang_code']:$lang_code;
            $group = (isset($post['group']))?$post['group']:'api';
            foreach ($post['data'] as $key => $value) {
                $translations = LanguagesKeywords::where('group',$group)->where('keyword',$key)->where('lang_code',$lang_code)->first();
                if($translations){
                    $inject = array(
                        'value' => $value
                    );
                    $inject['updated_at'] = date('Y-m-d h:i:s');
                    LanguagesKeywords::where('id',$translations->id)->update($inject);
                }else{
                    $inject = array(
                        'lang_code' => $lang_code,
                        'group' => $group,
                        'keyword' => $key,
                        'value' => $value
                    );
                    $inject['created_at'] = date('Y-m-d h:i:s');
                    $id = LanguagesKeywords::insertGetId($inject);
                }
            }
            return $this->sendResponse([], 'Record added successfully');
        } catch (\Exception $e) {
            return $this->sendError($e->getMessage(), 401);
        }
    }
}
