<?php

namespace App\Http\Controllers\LibrarySetting;

use App\Exports\ExportLibraryPublisherFormate;
use App\Http\Controllers\Controller;
use App\Http\Requests\LibrarySetting\PublishersRequest;
use App\Imports\ImportLibraryPublisher;
use App\Models\LibrarySetting\LibrarianPublishers;
use App\Models\LibrarySetting\Places;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Maatwebsite\Excel\Facades\Excel;

class LibrarianPublishersController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:library-publisher-list|library-publisher-create|library-publisher-edit|library-publisher-delete', ['only' => ['index', 'store', 'list']]);
    }
    public function index(Request $request)
    {
        $datas = LibrarianPublishers::select(['id', 'name', 'place_id', 'phone', 'isfeatured', 'status', 'website_view'])->with('getPlaceName');
        $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.publishers.table', compact('data'));
        } else {
            return view('library-setting.publishers.index', compact('data'));
        }
    }

    public function create()
    {
        $data['places'] = Places::all();
        return view('library-setting.publishers.create', $data);
    }


    public function store(Request $request)
    {
        $validator =  \Validator::make($request->all(), [
            'name' => 'required|unique:librarian_publishers',
        ]);
        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json(['success' => false, 'message' => $validator->errors()->all()]);
            }

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

        $input = $request->all();
        /***** Logo Upload *****/
        $path = "library/publishers/logos";
        if (isset($request->logo)) {
            $input['logo'] = uploadImage($path, $request->logo);
        } else {
            $input['logo'] = "";
        }
        $input['isfeatured'] = ($request->isfeatured == "on") ? '1' : '0';
        $input['website_view'] = ($request->website_view == "on") ? '1' : '0';
        $data = LibrarianPublishers::create($input);

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

        return redirect('library/publishers/')->with('success', 'Publishers created successfully.');
    }
    public function edit($id)
    {
        $publishers = LibrarianPublishers::find($id);
        $data['publishers'] = $publishers;
        $data['places'] = Places::all();
        return view('library-setting.publishers.edit', $data);
    }

    public function update($id, Request $request)
    {
        $input = $request->all();
        $publishers = LibrarianPublishers::find($id);

        /***** Logo Upload *****/
        $path = "library/publishers/logos";
        if (isset($request->logo)) {
            $input['logo'] = uploadImage($path, $request->logo);
        } else {
            $input['logo'] = $publishers->logo;
        }
        $input['isfeatured'] = ($request->isfeatured == "on") ? '1' : '0';
        $input['website_view'] = ($request->website_view == "on") ? '1' : '0';

        $publishers->update($input);
        return redirect('library/publishers/')->with('success', 'Publishers updated successfully');
    }


    public function destroy(Request $request)
    {
        $publishers = LibrarianPublishers::find($request->id);
        $publishers->delete();
        $Redirect = '/library/publishers/';
        return response()->json([
            'success' => true,
            'message' => ['Deleted successfully'],
            'data' => [
                'redirect' => $Redirect,
            ]
        ]);
    }
    public function changestatus(Request $request)
    {
        if ($request->ajax()) {
            $data = array('status' => $request->status);
            $Update = LibrarianPublishers::where('id', '=', $request->id)->update($data);

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

        if ($data) {

            foreach ($data as $row) {

                $publisher = ([
                    'name'            => $row[0],
                    'phone'           => $row[1] ?? '',
                    'email'           => $row[2] ?? '',
                    'status'          => ($row[2] == 'Inactive') ? '0' : '1',
                ]);

                $exist_publisher = LibrarianPublishers::where('name', $row[0])->exists();

                if (!$exist_publisher) {

                    $data = LibrarianPublishers::create($publisher);
                }
            }

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

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