<?php

namespace App\Http\Controllers\AdminAuth;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Session;
use Yajra\Datatables\Datatables;
use Illuminate\Support\Facades\Auth;
use App\Model\PreviousPaper;

class PreviouspaperController extends Controller
{

    private $data = array(
        'route' => 'admin.previouspaper.',
        'title' => 'Previouspaper',
        'menu' => 'previouspaper',
        'submenu' => '',
    );

    public function __construct() {
        $this->middleware(['permission:publish |previouspaper view|previouspaper add|previouspaper edit|previouspaper delete']);
    }

    private function _validate($request, $id = null)
    {
        $this->validate($request, [
            /*'papertype_id' => 'required',*/
            'date' => 'required',
            'pdf' => (!empty($id) ? 'mimes:pdf' : 'required|mimes:pdf'),
        ]);
    }

    public function index(Request $request)
    {
        abort_unless(Auth::guard('admin')->user()->hasAnyPermission(['previouspaper view']), 403);

        if ($request->ajax()) {
            $records = Previouspaper::with(['papertype', 'standard', 'medium', 'subject'])->select('previous_papers.*');

            return Datatables::of($records)
                ->addColumn('pdf', function ($record) {
                    if (!empty($record['pdf'])) {
                        return '<a href= "' . url("public/storage/" . $record->pdf) . '" target="_blank" >Pdf View</a>';
                    } else {
                        return '';
                    }
                })
                ->editColumn('created_at', function ($record) {
                    return $record->created_at->format(config('app.display_date'));
                })
                ->addColumn('status', function ($record) {
                    return '<input id="toggle-demo" value="' . $record->id . '" class="chk_status" data-toggle="toggle" data-on="Active" data-off="Inactive" data-size="small" data-onstyle="success"  type="checkbox" ' . ($record->status == "Active" ? " checked" : "") . ' >';
                })
                ->addColumn('action', function ($record) {
                    return '<a href="' . route($this->data['route'] . 'show', ['id' => $record->id]) . '" class="btn btn-primary btn-sm" title="" data-toggle="tooltip" data-original-title="View"><i class="fa fa-eye-slash"></i></a>' .
                        '&nbsp;<a href="' . route($this->data['route'] . 'edit', ['id' => $record->id]) . '" class="btn btn-info btn-sm" title="" data-toggle="tooltip" data-original-title="Edit"><i class="fa fa-pencil"></i></a>' .
                        '&nbsp;<button class="btn btn-danger btn-sm data-delete" data-id="' . $record->id . '" data-toggle="tooltip" data-original-title="Delete"><i class="fa fa-trash"></i></button>';
                })
                ->rawColumns(['status', 'action', 'pdf'])
                ->make(true);
        }
        return view('admin.previouspaper.index', $this->data);
    }

    public function create()
    {
        abort_unless(Auth::guard('admin')->user()->hasAnyPermission(['previouspaper add']), 403);

        $medium = \App\Model\Medium::with('standard')->where('status', '=', 'Active')->get();
        $medium_array = [];
        foreach ($medium as $key => $m) {
            $medium_array[$m['name']] = $m['standard']->pluck('name', 'id')->toArray();
        }
        $this->data['dropdown'] = $medium_array;
        return view('admin.previouspaper.create', $this->data);
    }

    public function store(Request $request)
    {
        abort_unless(Auth::guard('admin')->user()->hasAnyPermission(['previouspaper add']), 403);

        $this->_validate($request);
        $input = $request->all();
        $main_medium = \App\Model\Standard::where('id', $input['standard_id'])->first();
        $input['medium_id'] = $main_medium->medium_id;
        $input['pdf'] = $this->uploadFile($request, null, 'pdf', 'pdf', false);
        $record = new Previouspaper($input);
        $record->save();

        Session::flash('success', $this->data['title'] . ' inserted successfully.');
        return redirect()->route($this->data['route'] . 'index');
    }

    public function show($id)
    {
        abort_unless(Auth::guard('admin')->user()->hasAnyPermission(['previouspaper view']), 403);

        $this->data['record'] = Previouspaper::findOrFail($id);
        return view('admin.previouspaper.show', $this->data);
    }

    public function edit($id)
    {
        abort_unless(Auth::guard('admin')->user()->hasAnyPermission(['previouspaper edit']), 403);

        $this->data['record'] = $record = Previouspaper::findOrFail($id);
        $medium = \App\Model\Medium::with('standard')->where('status', '=', 'Active')->get();
        $medium_array = [];
        foreach ($medium as $key => $m) {
            $medium_array[$m['name']] = $m['standard']->pluck('name', 'id')->toArray();
        }
        $subject = \App\Model\Subject::where('standard_id',$record->standard_id)->pluck('name','id')->toArray();
        $this->data['dropdown'] = $medium_array;
        $this->data['subject'] = $subject;
        return view('admin.previouspaper.create', $this->data);
    }

    public function update(Request $request, $id)
    {
        abort_unless(Auth::guard('admin')->user()->hasAnyPermission(['previouspaper edit']), 403);

        $record = Previouspaper::findOrFail($id);
        /* Change Status Block */
        if ($request->ajax()) {
            $record->update($request->all());
            return \Illuminate\Support\Facades\Response::json(['result' => 'success']);
        }
        $this->_validate($request, $id);
        $input = $request->all();
        $main_medium = \App\Model\Standard::where('id', $input['standard_id'])->first();
        $input['medium_id'] = $main_medium->medium_id;
        $input['pdf'] = $this->uploadFile($request, $record, 'pdf', 'pdf', false);
        if (empty($input['pdf'])) {
            unset($input['pdf']);
        }
        $record->update($input);

        Session::flash('info', $this->data['title'] . ' updated successfully.');
        return redirect()->route($this->data['route'] . 'index');
    }

    public function destroy($id)
    {
        abort_unless(Auth::guard('admin')->user()->hasAnyPermission(['previouspaper delete']), 403);

        $record = Previouspaper::findOrFail($id);
        $this->deleteFile($record, 'pdf', false);
        $record->delete();
        return \Illuminate\Support\Facades\Response::json([
            'result' => 'success',
            'message' => 'Deleted Data successfully!'
        ]);
    }
}
