<?php

namespace App\Http\Controllers\LibrarySetting;

use App\Exports\ExportLibraryCategoryFormate;
use App\Http\Controllers\Controller;
use App\Http\Requests\LibrarySetting\GenresRequest;
use App\Imports\ImportLibraryCategory;
use App\Models\LibrarySetting\LibrarianGernes;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Maatwebsite\Excel\Facades\Excel;

class LibrarianGenresController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:library-category-list|library-category-create|library-category-edit|library-category-delete', ['only' => ['index', 'store', 'list']]);
    }
    public function index(Request $request)
    {
        $datas      = LibrarianGernes::select(['id', 'name', 'isfeatured', 'status', 'website_view','code']);
        $sort_by    = $request->get('sortby') ?? 10;
        $sort_type  = $request->get('sorttype');
        $query      = $request->get('query');
        if (!empty($query) && !empty($sort_by) && $query != " ") {
            $datas->where('name', 'like', '%' . $query . '%');
        }
        $data = $datas->orderBy('id', 'desc')->paginate($sort_by);
        if ($request->ajax()) {
            return view('library-setting.genres.table', compact('data'));
        } else {
            return view('library-setting.genres.index', compact('data'));
        }
    }

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


    public function store(GenresRequest $request)
    {
        $request->validated();
        $input = $request->all();
        /***** Small Cover Image Upload *****/
        $path = "library/genres/cover_image_small";
        if (isset($request->cover_image_small)) {
            $input['cover_image_small'] = uploadImage($path, $request->cover_image_small);
        } else {
            $input['cover_image_small'] = "";
        }
        /************Large Cover Image Upload ******/
        $path1 = "library/genres/cover_image_large";
        if (isset($request->cover_image_large)) {
            $input['cover_image_large'] = uploadImage($path1, $request->cover_image_large);
        } else {
            $input['cover_image_large'] = "";
        }
        $input['isfeatured'] = ($request->isfeatured == "on") ? '1' : '0';
        $input['website_view'] = ($request->website_view == "on") ? '1' : '0';
        $data = LibrarianGernes::create($input);

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

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

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


    public function update($id, Request $request)
    {
        $input = $request->all();
        $genres = LibrarianGernes::find($id);
        /***** Small Cover Image Upload *****/
        $path = "library/genres/cover_image_small";
        if (isset($request->cover_image_small)) {
            $input['cover_image_small'] = uploadImage($path, $request->cover_image_small);
        } else {
            $input['cover_image_small'] = $genres->cover_image_small;
        }
        /************Large Cover Image Upload ******/
        $path1 = "library/genres/cover_image_large";
        if (isset($request->cover_image_large)) {
            $input['cover_image_large'] = uploadImage($path1, $request->cover_image_large);
        } else {
            $input['cover_image_large'] = $genres->cover_image_large;
        }
        $input['isfeatured'] = ($request->isfeatured == "on") ? '1' : '0';
        $input['website_view'] = ($request->website_view == "on") ? '1' : '0';
        $genres->update($input);
        return redirect('library/genres/')->with('success', 'Genres updated successfully');
    }

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

            if ($Update) {
                return response()->json([
                    'success' => true,
                    'message' => ['Genres status successfully change'],
                    'data' => [
                        'redirect' => '/library/genres/',
                        '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 = LibrarianGernes::where('id', '=', $request->id)->update($data);

            if ($Update) {
                return response()->json([
                    'success' => true,
                    'message' => ['Genres isfeatured successfully change'],
                    'data' => [
                        'redirect' => '/library/genres/',
                        '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 = LibrarianGernes::where('id', '=', $request->id)->update($data);

            if ($Update) {
                return response()->json([
                    'success' => true,
                    'message' => ['Genres Website view successfully change'],
                    'data' => [
                        'redirect' => '/library/genres/',
                        'reload' => true,
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                    'data' => [
                        'redirect' => '',
                    ]
                ]);
            }
        }
    }
    public function destroy(Request $request)
    {
        $genres = LibrarianGernes::find($request->id);
        $genres->delete();
        $Redirect = '/library/genres/';
        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data' => [
                'redirect' => $Redirect,
            ]
        ]);
    }


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

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

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

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

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

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

    public function importSessionDestroy(Request $request)
    {
        $category_data = Session::get('CategoryData');

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

        Session::put('CategoryData', $category_data);

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

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

        if ($data) {

            foreach ($data as $row) {

                if($row[0]==Null)
                {
                    $name="N/A";
                }
                else
                {
                    $name=$row[0];
                }
                $catgory = ([
                    'name'            => $name,
                    'description'     => $row[1] ?? '',
                    'status'          => ($row[2] == 'Inactive') ? '0' : '1',
                ]);

                $exist_catgory = LibrarianGernes::where('name', $name)->exists();

                if (!$exist_catgory) {

                    $data = LibrarianGernes::create($catgory);
                }
            }

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

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