<?php

namespace App\Http\Controllers\TestManager;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\TestItemOption;
use App\Models\TestItem;
use App\Models\StyleType;
use Illuminate\Validation\Rule;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\ImportTestItemOption;
use App\Exports\ExportTestItemOptionFormat;
use Session;

class TestItemOptionsController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:test-item-option-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, $id)
    {
        if($id){

            $test_name = TestItem::select('name')->find($id);

            $item_id = $id;

            $data = TestItemOption::select([
                        'test_item_options.id',
                        'test_item_options.test_item_id',
                        'test_item_options.name',
                        'style_types.name as style',
                        'test_item_options.status',
                    ])
                    ->leftjoin('style_types', 'style_types.id', 'test_item_options.style_type_id')
                    ->where('test_item_id', $id)
                    ->orderBy('test_item_options.name', 'ASC');

            if ($request->ajax()) {
                $sort_by      = $request->get('sortby') ?? 10;
                $sort_type    = $request->get('sorttype');
                $search_query = $request->get('query');

                $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                    return $query->where('test_item_options.name', 'like', '%'.$search_query.'%')
                        ->orWhere('style_types.name', 'like', '%'.$search_query.'%');
                })
                ->where('test_item_id', $id)
                ->paginate($sort_by);

                return view('test-item-options.table', compact('data', 'item_id'));
            }
            else
            {
                $data = $data->paginate(10);

                return view('test-item-options.index', compact('data', 'item_id', 'test_name'));
            }
        }else{
            return abort(404);
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($id)
    {
        $item_id = $id;

        $style_types = StyleType::select(['id', 'name'])
                ->where('status', '1')
                ->whereNull('deleted_at')
                ->get();

        return view('test-item-options.create', compact('item_id', 'style_types'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request, $id)
    {
        if(!$id){
            return abort(404);
        }

        $item_id = $id;

        $validator = \Validator::make($request->all(), [
            'name' => [
                'required',
                Rule::unique('test_item_options')->where(function ($query) use ($item_id) {
                    return $query->where('test_item_id', $item_id);
                }),
            ],
        ]);

        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['test_item_id'] = $item_id;

        $TestItemOption = TestItemOption::create($data);

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

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $option = TestItemOption::find($id);

        $style_types = StyleType::select(['id', 'name'])
                ->where('status', '1')
                ->whereNull('deleted_at')
                ->get();

        return view('test-item-options.edit', compact('option', 'style_types'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        if(!$id){
            return abort(404);
        }

        $item = TestItemOption::select('test_item_id')->where('id', $id)->first();

        $item_id = $item->test_item_id;

        $validator = \Validator::make($request->all(), [
            'name' => [
                'required',
                Rule::unique('test_item_options')->where(function ($query) use ($item_id, $id) {
                    return $query->where('test_item_id', $item_id)
                        ->where('id', '!=', $id);
                }),
            ],
        ]);

        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'
        ]);

        $option = TestItemOption::find($id);

        $TestItemOptionUpdate = $option->update($data);

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

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        TestItemOption::find($request->id)->delete();

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

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

            if($Update){
                return response()->json([
                    'success' => true,
                    'message' => ['Option status successfully change'],
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                ]);
            }
        }
    }

    public function importCreate($id)
    {
        if ($id) {
            $item_id = $id;

            $item_name = TestItem::select('name')->where('id', $item_id)->first();

            return view('test-item-options.import', compact('item_id', 'item_name'));
        }
    }

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

        Session::put('TestItemOptionsData', $test_item_options_data);

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

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

            return view('test-item-options.preview', compact('data'));

        } catch (\Exception $e) {

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

    public function importSessionDestroy(Request $request)
    {
        $test_item_options_data = Session::get('TestItemOptionsData');

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

        Session::put('TestItemOptionsData', $test_item_options_data);

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

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

        if ($data){

            $item_id = $id;

            foreach ($data as $row){

                $style_type = StyleType::select('id')->where('name', $row[1])->first();

                if ($style_type) {
                    $style_type_id = $style_type->id;
                } else {
                    return redirect()->back()
                        ->with('error','Style Type not found.');
                }

                $test_item_options = ([
                    'test_item_id'  => $item_id,
                    'name'          => $row[0],
                    'style_type_id' => $style_type_id,
                    'status'        => ($row[2] == 'Inactive') ? '0' : '1',
                ]);

                $exist_option = TestItemOption::where('name', $row[0])->where('test_item_id', $item_id)->exists();

                if (!$exist_option){

                    TestItemOption::create($test_item_options);
                }
            }

            return redirect()->route('test-item-options.index', $item_id)
                ->with('success','Test Item Options uploaded successfully');
        }else{
            return redirect()->back()
                ->with('error','Empty file uploaded');
        }
    }

    public function exportFormat()
    {
        return Excel::download(new ExportTestItemOptionFormat, 'test-item-option-format.xlsx');
    }
}
