<?php

namespace App\Http\Controllers\TestManager;

use App\Http\Controllers\Controller;
use App\Models\TestMethod;
use App\Models\PrimaryUnit;
use App\Models\StyleType;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\ImportTestMethod;
use App\Exports\ExportTestMethodFormat;
use Session;

class TestMethodsController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:test-method-list', ['only' => ['index']]);
    }

    public function index(Request $request)
    {
        $data = TestMethod::select([
                    'test_methods.id',
                    'test_methods.name',
                    'test_methods.code',
                    'test_methods.details',
                    'test_methods.status',
                    'test_methods.show_in_report',
                ])
                ->orderBy('test_methods.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_methods.name', 'like', '%'.$search_query.'%')
                    ->orWhere('test_methods.details', 'like', '%'.$search_query.'%');
            })
            ->paginate($sort_by);

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

            return view('test-methods.index', compact('data'));
        }
    }

    public function create()
    {
        return view('test-methods.create');
    }

    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'name' => 'required|unique:test_methods,name,NULL,id,deleted_at,NULL',
        ]);

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

        $method = TestMethod::create($data);

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

    public function edit($id)
    {
        $data = TestMethod::find($id);

        return view('test-methods.edit',compact('data'));
    }

    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'name' => 'required|unique:test_methods,name,'.$id.',id,deleted_at,NULL',
        ]);

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

        $method = TestMethod::find($id);

        if (!$method) {
            return redirect()->route('test-methods.index')
                ->with('error','Test Method not found!');
        }

        $method->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Test Method Updated successfully.',
                'data'    => $method
            ]);
        }
    }

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

            $Redirect = 'test-methods';

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

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

            $Redirect = 'test-methods';

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

    public function destroy(Request $request)
    {
        TestMethod::find($request->id)->delete();

        $Redirect = 'test-methods';

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

    public function importCreate()
    {
       return view('test-methods.import');
    }

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

        Session::put('TestMethodData', $test_method_data);

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

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

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

        } catch (\Exception $e) {

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

    public function importSessionDestroy(Request $request)
    {
        $test_method_data = Session::get('TestMethodData');

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

        Session::put('TestMethodData', $test_method_data);

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

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

        if($data){

            foreach ($data as $row){

                $test_methods = ([
                    'name'    => $row[0],
                    'details' => $row[1],
                    'status'  => ($row[2] == 'Inactive') ? '0' : '1',
                ]);

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

                if(!$exist_test_methods){
                    TestMethod::create($test_methods);
                }
            }

            return redirect()->route('test-methods.index')
                ->with('success','Test Methods uploaded successfully');
        }else{
           return redirect()->back()
                ->with('error','Empty file uploaded');
        }
    }

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