<?php

namespace App\Http\Controllers\LibrarySetting;

use App\Exports\ExportLibraryAuthorFormate;
use App\Http\Controllers\Controller;
use App\Http\Requests\LibrarySetting\AuthorsRequest;
use App\Imports\ImportLibraryAuthor;
use App\Models\LibrarySetting\LibrarianAuthors;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Maatwebsite\Excel\Facades\Excel;

class LibrarianAuthorsController extends Controller
{
  function __construct()
    {
        $this->middleware('permission:library-author-list|library-author-create|library-author-edit|library-author-delete', ['only' => ['index','store','list']]);
    }
    public function index(Request $request)
    {
      $datas = LibrarianAuthors::select(['id','first_name','authors_prfile_picture','website_view','status','isfeatured']);

      $sort_by    = $request->get('sortby') ?? 10;
      $sort_type  = $request->get('sorttype');
      $query      = $request->get('query');
      if(!empty($query) && !empty($sort_by) && $query!=" ")
      {
         $datas->where('first_name', 'like', '%'.$query.'%');
      }
      $data =$datas->orderBy('id','desc')->paginate($sort_by);

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

    }

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

    public function store(AuthorsRequest $request)
    {
        $request->validated();
        $input = $request->all();

        $path="assets/author_profile";
        if(!empty($request->authors_prfile_picture))
        {
            $response = uploadImage($path,$request->authors_prfile_picture);
          $input['authors_prfile_picture']=$response['file_name'];
        }
        else
        {
          $input['authors_prfile_picture']='';
        }

        /***** Small Cover Image Upload *****/
        $path="library/authors/cover_image_small";
          if(isset($request->cover_image_small))
          {
            $response = uploadImage($path,$request->cover_image_small);
            $input['cover_image_small']=$response['file_name'];
          }
          else
          {
            $input['cover_image_small']="";
          }
          /************Large Cover Image Upload ******/
          $path1="library/authors/cover_image_large";
          if(isset($request->cover_image_large))
          {
            $response = uploadImage($path,$request->cover_image_large);
            $input['cover_image_large']=$response['file_name'];
          }
          else
          {
            $input['cover_image_large']="";
          }
        $input['isfeatured']=($request->isfeatured=="on")?'1':'0';
        $input['website_view']=($request->website_view=="on")?'1':'0';
        $input['company_id']= auth()->user()->company_id;
        $data = LibrarianAuthors::create($input);

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

        return redirect('library/authors/')->with('success','Authors created successfully.');
    }
   public function edit($id)
   {
        $authors=LibrarianAuthors::find($id);
        $data['authors']=$authors;
        return view('library-setting.authors.edit',$data);
   }

   public function update($id,Request $request)
   {
      $input = $request->all();
      $authors=LibrarianAuthors::find($id);
      $path="assets/author_profile";
        if(!empty($request->authors_prfile_picture))
        {
          $input['authors_prfile_picture']=uploadImage($path,$request->authors_prfile_picture);
        }
        else
        {
          $input['authors_prfile_picture']=$authors->authors_prfile_picture;
        }

        /***** Small Cover Image Upload *****/
      $path="library/authors/cover_image_small";
      if(isset($request->cover_image_small))
      {
        $input['cover_image_small']=uploadImage($path,$request->logo);
      }
      else
      {
        $input['cover_image_small']=$authors->cover_image_small;
      }
      /************Large Cover Image Upload ******/
      $path1="library/authors/cover_image_large";
      if(isset($request->cover_image_large))
      {
        $input['cover_image_large']=uploadImage($path1,$request->logo);
      }
      else
      {
        $input['cover_image_large']=$authors->cover_image_large;
      }
      $input['isfeatured']=($request->isfeatured=="on")?'1':'0';
      $input['website_view']=($request->website_view=="on")?'1':'0';
      $input['company_id']= auth()->user()->company_id;
      $authors->update($input);
      return redirect('library/authors/')->with('success','Authors updated successfully');
   }


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

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

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

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


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

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


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

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

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

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

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

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

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

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

    public function importSessionDestroy(Request $request)
    {
        $author_data = Session::get('AuthorData');

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

        Session::put('AuthorData', $author_data);

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

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

        if ($data) {

            foreach ($data as $row) {

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

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

                if (!$exist_authors) {

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

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

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