<?php

namespace App\Http\Controllers\TestManager;

use App\Http\Controllers\Controller;
use App\Models\SampleType;
use App\Models\Department;
use App\Models\SampleCollectionTube;
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 Session;
use App\Imports\ImportSampleType;
use App\Exports\ExportSampleTypeFormat;

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

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

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

            return view('sample-types.index', compact('data'));
        }
    }

    public function create()
    {
        $sampleTubes = SampleCollectionTube::select(['id', 'tube_name'])->whereNull('deleted_at')
            ->where('status', 1)->get();

        return view('sample-types.create', compact('sampleTubes'));
    }

    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'name' => 'required|unique:sample_types,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'
        ]);

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

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

    public function edit($id)
    {
        $data = SampleType::find($id);
        $sampleTubes = SampleCollectionTube::select(['id', 'tube_name'])->whereNull('deleted_at')->where('status', 1)->get();

        return view('sample-types.edit', compact('data', 'sampleTubes'));
    }

    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'name' => 'required|unique:sample_types,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'
        ]);

        $SampleType = SampleType::find($id);

        if (!$SampleType) {
            return redirect()->route('sample-types.index')
                ->with('error','Sample Type not found!');
        }

        $SampleType->update($data);

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

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

            $Redirect = 'sample-types';

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

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

        $Redirect = 'sample-types';

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

    public function importCreate()
    {
       return view('sample-types.import');
    }

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

        Session::put('SampleTypeData', $sample_type_data);

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

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

            return view('sample-types.preview', compact('data'));

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

    public function importSessionDestroy(Request $request)
    {
        $sample_type_data = Session::get('SampleTypeData');

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

        Session::put('SampleTypeData', $sample_type_data);

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

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

        if($data){

            foreach ($data as $row){

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

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

                if(!$exist_sample_types){
                    SampleType::create($sample_types);
                }
            }

            return redirect()->route('sample-types.index')
                ->with('success','Sample Types uploaded successfully');
        }else{
           return redirect()->back()
                ->with('error','Empty file uploaded');
        }
    }

    public function exportFormat()
    {
        return Excel::download(new ExportSampleTypeFormat, 'sample-type-format.xlsx');
    }
}
