<?php

namespace App\Http\Controllers\TestManager;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\TestPackage;
use App\Models\TestPackageGroup;
use App\Models\TestPackageGroupTestItem;
use App\Models\TestPackageGroupNote;
use App\Models\TestPackageNote;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Validator;
use App\Models\TestItem;
use App\Models\TestUnit;
use App\Models\Department;
use App\Models\TestMethod;
use Illuminate\Validation\Rule;
use App\Models\TestItemOption;
use App\Models\TestItemNormalRange;

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

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index($id = 0)
    {
        if(!$id || $id < 1){
            return abort(404);
        }else{
            $groups = TestPackageGroup::select([
                'test_package_groups.id',
                'test_package_groups.priority',
                'test_package_groups.test_package_id',
                'test_package_groups.group_name',
                'test_package_groups.priority',
                'test_package_groups.show_in_report',
                'test_package_groups.page_break',
                'test_package_groups.status',
                'test_packages.name as package_name',
            ])

            ->leftjoin('test_packages', 'test_packages.id', 'test_package_groups.test_package_id')
            ->where('test_package_groups.test_package_id', $id)
            ->with('test_package_group_test_items', 'test_package_group_notes')
            ->orderBy('test_package_groups.priority', 'ASC')
            ->get();

            $packages = TestPackage::select([
                'test_packages.id',
                'test_packages.name',
            ])
            ->with('package_notes')
            ->find($id);

            $package_id = $id;

            $test_units = TestUnit::select(['id', 'name'])
                ->where('status', '1')
                ->get();
            return view('test-package-groups.index', compact('groups', 'packages', 'package_id'));
        }
    }

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

            return view('test-package-groups.create-group', compact('id'));
        }else{
            return redirect()->route('test-package-groups.index')
            ->with('error','Test Package Not Found!');
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $package_id = $request->test_package_id;

        $validator = \Validator::make($request->all(), [
            'group_name' => [
                'required',
                Rule::unique('test_package_groups')->where(function ($query) use ($package_id) {
                    return $query->where('test_package_id', $package_id)
                        ->where('deleted_at', NULL);
                }),
            ],
        ]);

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

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

        $latest_priority = TestPackageGroup::where('test_package_id', $package_id)->max('priority');
        $priority = ($latest_priority ?? 0) + 1;

        $data['priority'] = $priority;

        $package_group = TestPackageGroup::create($data);

        // Create group note
        $note['test_package_id']       = $package_group->test_package_id;
        $note['test_package_group_id'] = $package_group->id;
        $note['group_note']            = '-';

        $group_note = TestPackageGroupNote::create($note);

        return redirect()->route('test-package-groups.index', $package_group->test_package_id)
            ->with('success','Test Package Group 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)
    {
        $data = TestPackageGroup::find($id);

        return view('test-package-groups.edit-group', compact('data'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $package_group = TestPackageGroup::select('test_package_id')->where('id', $id)->first();

        $package_id = $package_group->test_package_id;

        $validator = \Validator::make($request->all(), [
            'group_name' => [
                'required',
                Rule::unique('test_package_groups')->where(function ($query) use ($package_id, $id) {
                    return $query->where('test_package_id', $package_id)
                        ->where('id', '!=', $id)
                        ->where('deleted_at', NULL);
                }),
            ],
        ]);

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

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

        if(isset($data['page_break']) && $data['page_break'] == 'on'){
            $data['page_break'] = 1;
        }else{
            $data['page_break'] = 0;
        }

        if(isset($data['show_in_report']) && $data['show_in_report'] == 'on'){
            $data['show_in_report'] = 1;
        }else{
            $data['show_in_report'] = 0;
        }

        $group = TestPackageGroup::find($id);

        if (!$group) {
            return redirect()->route('test-package-groups.index')
                ->with('error','Test Packages Group not found!');
        }

        $group->update($data);

        return redirect()->route('test-package-groups.index', $group->test_package_id)
            ->with('success','Test Package Group updated successfully');
    }

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

            $Redirect = 'test-package-groups';

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

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request, $id)
    {
        if($id){
            $item = TestPackageGroupTestItem::select('test_item_id')->where('test_package_group_id', $request->id)->get();

            // DELETE OPTION AND RANGE
            // TestItemOption::whereIn('test_item_id', $item)->delete();
            // TestItemNormalRange::whereIn('test_item_id', $item)->delete();

            // DELETE OPTION AND RANGE
            // TestItem::whereIn('id', $item)->delete();

            // DELETE GROUP, TESTITEM AND NOTE
            TestPackageGroupNote::where('test_package_group_id', $request->id)->delete();
            TestPackageGroupTestItem::where('test_package_group_id', $request->id)->delete();
            TestPackageGroup::find($request->id)->delete();

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

    public function testDestroy(Request $request, $id)
    {
        if($id){
            $item = TestPackageGroupTestItem::select('test_item_id')->find($request->id);

            // DELETE TESTITEM
            // TestItem::find($item->test_item_id)->delete();
            TestPackageGroupTestItem::find($request->id)->delete();

            // DELETE OPTION AND RANGE
            // TestItemOption::where('test_item_id', $item->test_item_id)->delete();
            // TestItemNormalRange::where('test_item_id', $item->test_item_id)->delete();

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

    public function reorderTestItems(Request $request)
    {
        foreach ($request->order as $order) {
            TestPackageGroupTestItem::where(['id' => $order['id']])->orderBy('priority','ASC')->update(['priority' => $order['position']]);
        }

        return response()->json([
                'status' => true,
                'message' => ['Priority updated successfully'],
            ]);
    }

    public function noteEdit($id)
    {
        $note = TestPackageGroupNote::where('test_package_group_id', $id)->first();

        return view('test-package-groups.edit-note', compact('note'));
    }

    public function noteUpdate(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'group_note' => 'required',
        ]);

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

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

        if(isset($data['position']) && $data['position'] == 'on'){
            $data['position'] = 1;
        }else{
            $data['position'] = 0;
        }

        if(isset($data['is_default']) && $data['is_default'] == 'on'){
            $data['is_default'] = 1;
        }else{
            $data['is_default'] = 0;
        }

        $note = TestPackageGroupNote::find($id);

        if (!$note) {
            return redirect()->route('test-package-groups.index', $note->test_package_id)
                ->with('error','Group Note not found!');
        }

        $note->update($data);

        return redirect()->route('test-package-groups.index', $note->test_package_id)
            ->with('success','Group Note updated successfully');
    }

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

            $Redirect = 'test-package-groups';

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

    public function packageNoteEdit($id)
    {
        $note = TestPackageNote::where('test_package_id', $id)->first();

        return view('test-package-groups.edit-package-note', compact('note','id'));
    }

    public function packageNoteUpdate(Request $request, $id)
    {
        // $validator = \Validator::make($request->all(), [
        //     'package_note' => 'required',
        // ]);

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

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

        if(isset($data['position']) && $data['position'] == 'on'){
            $data['position'] = 1;
        }else{
            $data['position'] = 0;
        }

        if(isset($data['is_default']) && $data['is_default'] == 'on'){
            $data['is_default'] = 1;
        }else{
            $data['is_default'] = 0;
        }

        $note = TestPackageNote::find($id);

        if (!$note) {
            return redirect()->route('test-package-groups.index', $note->test_package_id)
                ->with('error','Package Note not found!');
        }

        $note->update($data);

        return redirect()->route('test-package-groups.index', $note->test_package_id)
            ->with('success','Package Note updated successfully');
    }

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

            $Redirect = 'test-package-groups';

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