<?php

namespace App\Http\Controllers\TestManager;

use App\Http\Controllers\Controller;
use App\Models\TestItem;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use PHPUnit\Util\Test;
use Illuminate\Http\Response;
use App\Models\TestPackageGroupTestItem;
use App\Models\TestPackageGroup;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Illuminate\Validation\Rule;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\ImportTestItem;
use App\Exports\ExportTestItemFormat;
use Session;
use App\Models\Department;
use App\Models\TestUnit;
use App\Models\TestMethod;
use App\Models\MachineAndEquipment;

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

    public function create($id)
    {
        $test_name = TestPackageGroup::select('id','group_name')->where('id',$id)->with('testPackage')->first();
        if($id){
            $group_id = $id;

            $test_units = TestUnit::select(['id', 'name'])
                ->where('status', '1')
                ->get();

            $test_methods = TestMethod::select(['id', 'name'])
                ->where('status', '1')
                ->get();

            $machines = MachineAndEquipment::select(['id', 'device_model_name'])
                ->where('status', '1')
                ->get();

            return view('test-items.create', compact('test_units', 'test_methods', 'machines', 'group_id','test_name'));
        }else{
            return redirect()->back('test-items.index')
                ->with('error','Group not found!');
        }
    }

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

        $group_id = $id;

        $item_name = $request->name;

        $item_exist = TestPackageGroupTestItem::leftjoin('test_items', 'test_items.id', 'test_package_group_test_items.test_item_id')
                ->where('test_items.name', $item_name)
                ->where('test_package_group_test_items.test_package_group_id', $group_id)
                ->exists();

        if($item_exist){
            return redirect()->back()->with('error', 'Test name already Exist!');
        }

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

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

        if (!$id) {
            return redirect()->back('test-items.index')
                ->with('error','Group not found!');
        }

        $data['code'] = strtoupper(str_replace(' ', '_', $request->name));
        $test_item = TestItem::create($data);

        // Store ids in pivot table
        $package_id = TestPackageGroup::select('test_package_id')->find($id);

        $group_test['test_package_group_id'] = $id;
        $group_test['test_item_id']          = $test_item->id;
        $group_test['test_package_id']       = $package_id->test_package_id;

        $priority = TestPackageGroupTestItem::max('priority');
        $max_priority = ($priority ?? 0) + 1;

        $group_test['priority'] = $max_priority;

        $test_id_in_pivot_table = TestPackageGroupTestItem::create($group_test);

        return redirect()->route('test-package-groups.index', $package_id->test_package_id)
            ->with('success','Test Item created successfully');
    }

    public function show($id)
    {
        $item = TestItem::select([
                    'test_items.id',
                    'test_items.name',
                    'test_items.short_name',
                    'test_items.formula_code',
                    'test_items.input_type',
                    'test_items.code',
                    'test_items.item_type',
                    'test_items.test_number',
                    'test_items.default_result',
                    'test_items.result_source',
                    'test_items.result_guide',
                    'test_items.details',
                    'test_items.is_read_only',
                    'test_items.status',
                    'test_units.name as unit',
                    'test_methods.name as test_method',
                    'machine_and_equipments.device_model_name as machine',
                ])
                ->leftjoin('test_units', 'test_items.primary_unit_id', 'test_units.id')
                ->leftjoin('test_methods', 'test_items.test_method_id', 'test_methods.id')
                ->leftjoin('machine_and_equipments', 'test_items.machine_id', 'machine_and_equipments.id')
                ->find($id);

        return view('test-items.detail',compact('item'));
    }

    public function edit($id)
    {
        $test_units = TestUnit::select(['id', 'name'])
            ->where('status', '1')
            ->get();

        $test_methods = TestMethod::select(['id', 'name'])
            ->where('status', '1')
            ->get();

        $machines = MachineAndEquipment::select(['id', 'device_model_name'])
            ->where('status', '1')
            ->get();

        $data = TestItem::find($id);

        return view('test-items.edit',compact('data', 'test_units', 'test_methods', 'machines'));
    }

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

        $group = TestPackageGroupTestItem::select('test_package_group_id')->where('test_item_id', $id)->first();

        $group_id = $group->test_package_group_id;

        $item_name = $request->name;

        $item_exist = TestPackageGroupTestItem::leftjoin('test_items', 'test_items.id', 'test_package_group_test_items.test_item_id')
                ->where('test_items.name', $item_name)
                ->where('test_package_group_test_items.test_package_group_id', $group_id)
                ->where('test_items.id', '!=', $id)
                ->exists();

        if($item_exist){
            return redirect()->back()->with('error', 'Test name already Exist!');
        }

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

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

        $data['code'] = strtoupper(str_replace(' ', '_', $request->name));
        $test_item = TestItem::find($id);

        if (!$test_item) {
            return redirect()->back()
                ->with('error','Test Item not found!');
        }

        $test_item->update($data);

        $package_id = TestPackageGroupTestItem::select('test_package_id')->where('test_item_id', $test_item->id)->first();

        return redirect()->route('test-package-groups.index', $package_id->test_package_id)
            ->with('success','Test Item Updated successfully');
    }

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

            $Redirect = 'test-items';

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

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

            $Redirect = 'test-items';

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

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

            $Redirect = 'test-items';

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

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

        $Redirect = 'test-items';

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

    public function importCreate($id)
    {
        if ($id) {
            $group_id = $id;

            $group = TestPackageGroup::select('group_name')->where('id', $group_id)->first();

            return view('test-items.import', compact('group_id', 'group'));
        }
    }

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

        Session::put('TestItemsData', $test_items_data);

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

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

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

        } catch (\Exception $e) {

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

    public function importSessionDestroy(Request $request)
    {
        $test_items_data = Session::get('TestItemsData');

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

        Session::put('TestItemsData', $test_items_data);

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

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

        if ($data){

            $group_id = $id;

            $package = TestPackageGroup::select('test_package_id')->find($group_id);

            $package_id = $package->test_package_id;

            foreach ($data as $row){

                $unit = TestUnit::select('id')->where('name', $row[2])->first();

                if (!$unit) {
                    $unit = TestUnit::create(['name' => $row[2]]);
                }

                $test_item = ([
                    'name'            => $row[0],
                    'item_type'       => $row[1],
                    'primary_unit_id' => $unit->id,
                    'input_type'      => $row[3],
                    'status'          => ($row[4] == 'Inactive') ? '0' : '1',
                ]);

                $exist_item = TestItem::where('name', $row[0])
                    ->leftjoin('test_package_group_test_items', 'test_package_group_test_items.test_item_id', 'test_items.id')
                    ->where('test_package_group_test_items.test_package_group_id', $group_id)
                    ->exists();

                if (!$exist_item){

                    $test_item_create = TestItem::create($test_item);

                    $max_priority = TestPackageGroupTestItem::max('priority');
                    $priority = ($priority ?? 0) + 1;

                    $test_package_group_test_item = ([
                        'test_package_id'       => $package_id,
                        'test_package_group_id' => $group_id,
                        'status'                => ($row[4] == 'Inactive') ? '0' : '1',
                        'priority'              => $priority,
                        'test_item_id'          => $test_item_create->id,
                    ]);

                    TestPackageGroupTestItem::create($test_package_group_test_item);

                }
            }

            return redirect()->route('test-package-groups.index', $package_id)
                ->with('success','Test Items uploaded successfully');
        }else{
            return redirect()->back()
                ->with('error','Empty file uploaded');
        }
    }

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