<?php

namespace App\Http\Controllers\LibrarySetting;

use App\Exports\ExportLibraryTranslatorFormate;
use App\Http\Controllers\Controller;
use App\Http\Requests\LibrarySetting\TranslatorsRequest;
use App\Imports\ImportLibraryTranslators;
use App\Models\LibrarySetting\Translators;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Maatwebsite\Excel\Facades\Excel;

class TranslatorController extends Controller
{

    function __construct()
    {
        $this->middleware('permission:library-translators-list|library-translators-create|library-translators-edit|library-translators-delete', ['only' => ['index','store','list']]);
    }

    public function index(Request $request)
    {
      $datas = Translators::select(['id','translator_name','status']);
      $sort_by    = $request->get('sortby') ?? 10;
      $sort_type  = $request->get('sorttype');
      $query      = $request->get('query');
      if(!empty($query) && !empty($sort_by) && $query!=" ")
      {
         $datas->where('translator_name', 'like', '%'.$query.'%');
      }
      $data =$datas->orderBy('id','desc')->paginate($sort_by);
        if ($request->ajax()) {
          return view('library-setting.translators.table', compact('data'));
        }
        else
        {
            return view('library-setting.translators.index',compact('data'));
        }

    }

    public function create()
    {
        return view('library-setting.translators.create');
    }


    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), ['translator_name' => 'required']);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except(['_token']);

        $data = Translators::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Translator created successfully',
                'data' => $data
            ]);
        }

        return redirect()->route('translators.index')
            ->with('success', 'Translator created successfully');


    }
   public function edit($id)
   {
        $translators=Translators::find($id);
        $data['translators']=$translators;
        return view('library-setting.translators.edit',$data);
   }

   public function update($id,Request $request)
   {

      $validator = \Validator::make($request->all(), ['translator_name' => 'required']);

      if ($validator->fails()) {
          if ($request->ajax()) {
              return response()->json([
                  'success' => false,
                  'message' => $validator->getMessageBag()->first(),
                  'data'    => []
              ]);
          }

          return redirect()->back()->with('error', $validator->getMessageBag()->first());
      }

      $data = $request->except(['_token', '_method']);
      $data = Translators::whereId($id)->update($data);
      $data = Translators::find($id);

      if ($request->ajax()) {
          return response()->json([
              'success' => true,
              'message' => 'Translators updated successfully',
              'data' => $data
          ]);
      }
      return redirect()->route('translators.index')
          ->with('success', 'Translators updated successfully');
   }

   public function changestatus(Request $request)
   {
       if ($request->ajax())
       {
           $data = array('status' => $request->status );
           $Update = Translators::where('id', '=', $request->id)->update($data);

           if($Update){
               return response()->json([
                   'success'=>true,
                   'message'=>['Translator status successfully change'],
                   'data'=>[
                       'redirect'=>'/library/translators/',
                       'reload'=>true,
                   ]
               ]);
           }
           else{
               return response()->json([
                   'success'=>false,
                   'message'=>['Error for change status'],
                   'data'=>[
                       'redirect'=>'',
                   ]
               ]);
           }
       }
   }


  public function destroy(Request $request)
  {
        $translators=Translators::find($request->id);
        $translators->delete();
       $Redirect = '/library/translators/';
        return response()->json([
            'success'=>true,
            'message'=>['Deleted successfully'],
            'data'=>[
            'redirect'=>$Redirect,
            ]
        ]);
  }


  public function importcreate(Request $request)
  {
      return view('library-setting.translators.import');
  }

  public function importPreview(Request $request)
    {
        $package_data = [];

        Session::put('TranslatorsData', $package_data);

        try {
            Excel::import(new ImportLibraryTranslators, $request->file('trasnlators'));

            $data = Session::get('TranslatorsData');

            return view('library-setting.translators.preview', compact('data'));
        } catch (\Exception $e) {

            return response()->json([
                'success' => false,
                'message' => [$e->getMessage()],
            ]);
        }
    }

    public function importSessionDestroy(Request $request)
    {
        $editor_data = Session::get('TranslatorsData');

        unset($editor_data[$request->id]);

        Session::put('TranslatorsData', $editor_data);

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

    public function importStore(Request $request)
    {
        $data = Session::get('TranslatorsData');

        if ($data) {

            foreach ($data as $row) {

                $authors = ([
                    'translator_name'      => $row[0],
                    'status'          => ($row[1] == 'Inactive') ? '0' : '1',
                ]);

                $exist_authors = Translators::where('translator_name', $row[0])->exists();

                if (!$exist_authors) {

                    $data = Translators::create($authors);
                }
            }

            return redirect()->route('translators.index')
                ->with('success', 'Translator uploaded successfully');
        } else {
            return redirect()->back()
                ->with('error', 'Empty file uploaded');
        }
    }

    public function exportFormat()
    {
        return Excel::download(new ExportLibraryTranslatorFormate, 'library-translator-format.xlsx');
    }
}
