<?php

namespace App\Http\Controllers\LibrarySetting;

use App\Exports\ExportLibraryEditorFormate;
use App\Http\Controllers\Controller;
use App\Http\Requests\LibrarySetting\EditorRequest;
use App\Imports\ImportLibraryEditor;
use App\Models\LibrarySetting\Editor;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Maatwebsite\Excel\Facades\Excel;

class EditorController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:library-editors-list|library-editors-create|library-editors-edit|library-editors-delete', ['only' => ['index','store','list']]);
    }
    public function index(Request $request)
    {
      $datas     = Editor::select(['id','editor_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('editor_name', 'like', '%'.$query.'%');
      }

      $data =$datas->orderBy('id','desc')->paginate($sort_by);

      if ($request->ajax()) {
        return view('library-setting.editors.table', compact('data'));
      }
      else
      {
          return view('library-setting.editors.index',compact('data'));
      }
    }

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

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

        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 = Editor::create($data);

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

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



    }

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

   public function update($id,Request $request)
   {
      $validator = \Validator::make($request->all(), ['editor_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 = Editor::whereId($id)->update($data);
      $data = Editor::find($id);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        if ($data) {

            foreach ($data as $row) {

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

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

                if (!$exist_authors) {

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

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

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