<?php

namespace App\Http\Controllers;

use App\Models\TestItem;
use App\Models\TestItemTemplate;
use Illuminate\Contracts\Session\Session;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class TestItemTemplateController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:test-item-template-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request, $id)
    {
        if($id){
            $item_id = $id;
            $data = TestItemTemplate::select([
                'id',
                'template_title',
                'template_text',
                'priority',
                'status',
                'default',
                'test_item_id',

                ])
                ->where('test_item_id', $id);
                // ->orderBy('genders.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('template_title', 'like', '%'.$search_query.'%');
                        })
                        ->where('test_item_id', $id)
                        ->paginate($sort_by);

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

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

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($id)
    {
        $test_name = TestItem::select('name')->find($id);
        $item_id = $id;
        $priority = TestItemTemplate::max('priority');
        $priority = $priority != '' ? $priority : 0;

        return view('test-item-templates.create', compact('item_id','priority','test_name'));
    }

    /**
     * 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);
        }

        $validator = \Validator::make($request->all(), [
            'template_title' => 'required'
        ]);

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

        $default_check = TestItemTemplate::where(['default' => 1,'status' => 1])->first();

        if (!$default_check) {
            $data['default'] = 1;
        }

        $data['test_item_id'] = $id;

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

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

            return redirect()->route('test-item-templates.index', $id)->with('success', 'Item Test Template created successfully');
            // return redirect()->back()->with('success', 'Item Test Template created successfully');
    }
    /**
     * 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)
    {
        $range = TestItemTemplate ::find($id);

        return view('test-item-templates.edit', compact('range'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'template_title' => 'required',
        ]);

        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 = TestItemTemplate::whereId($id)->update($data);
        $data = TestItemTemplate::find($id);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Test Item Template updated successfully',
                'data' => $data
            ]);
        }
        return redirect()->route('project-types.index')
            ->with('success', 'Test Item Template updated successfully');
    }

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

        if ($data->default == '1') {
            return response()->json([
                'success' => false,
                'message' => ['Default record can not be deleted.']
            ]);
        }

        $data->delete();

        $Redirect = 'test-item-templates.index';

        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 = TestItemTemplate ::where('id', '=', $request->id)->update($data);

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

   public function changeDefault(Request $request)
   {
        if ($request->ajax()) {
            $data   = array('default' => $request->status );
            $count  = TestItemTemplate::where(['default' => $request->status])->count();

            if ($count > 0 && $request->status == 1) {
                return response()->json([
                    'success' => false,
                    'message' => ['There is already a default Test Item Template!'],
                    'data'    => []
                ]);
            }

            $Update = TestItemTemplate::where('id', '=', $request->id)->update($data);

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

}
