<?php

namespace App\Http\Controllers\TestManager;

use App\Http\Controllers\Controller;
use App\Models\TestUnit;
use App\Models\TestItem;
use App\Models\TestItemNormalRange;
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\ImportTestUnit;
use App\Exports\ExportTestUnitFormat;
use Session;

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

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

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

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

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

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

        $unit = TestUnit::create($data);

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

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

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

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

        if ($validator->fails()) {
            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method'
        ]);

        $unit = TestUnit::find($id);

        if (!$unit) {
            return redirect()->route('test-units.index')
                ->with('error','Test Unit not found!');
        }

        $unit->update($data);

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

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

            $Redirect = 'test-units';

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

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

        $Redirect = 'test-units';

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

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

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

        Session::put('TestUnitsData', $test_units_data);

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

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

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

        } catch (\Exception $e) {

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

    public function importSessionDestroy(Request $request)
    {
        $test_units_data = Session::get('TestUnitsData');

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

        Session::put('TestUnitsData', $test_units_data);

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

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

        if($data){

            foreach ($data as $row){

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

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

                if(!$exist_test_units){
                    TestUnit::create($test_units);
                }
            }

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

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