<?php

namespace App\Http\Controllers\MedicalSetting;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Operation;
use App\Models\OperationCategory;
use App\Imports\ImportOperation;
use Session;
use Maatwebsite\Excel\Facades\Excel;

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

    public function index(Request $request)
    {
        $data = Operation::select([
                    'operations.id',
                    'operations.operation',
                    'operations.status',
                    'operations.priority',
                    'operation_categories.category',
                ])
        		->leftjoin('operation_categories', 'operation_categories.id', 'operations.category_id')
                ->orderBy('priority', '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('operations.operation', 'like', '%'.$search_query.'%')
                    ->orWhere('operation_categories.category', 'like', '%'.$search_query.'%');
            })
            ->paginate($sort_by);

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

            return view('operations.index', compact('data'));
        }
    }

    public function create()
    {
    	$priority = Operation::max('priority')+1;
    	$operation_categories = OperationCategory::select(['id', 'category'])->where('status', 1)->get();

        return view('operations.create', compact('priority', 'operation_categories'));
    }

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

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

        $priority = Operation::max('priority')+1;
        $data['priority'] = $priority;

        $operation = Operation::create($data);

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

    public function edit($id)
    {
        $data = Operation::find($id);
        $operation_categories = OperationCategory::select(['id', 'category'])->where('status', 1)->get();

        return view('operations.edit', compact('data', 'operation_categories'));
    }

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

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

        $operation = Operation::find($id);

        if (!$operation) {
            return redirect()->back()
                ->with('error','Operation not found!');
        }

        $operation->update($data);

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

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

            $Redirect = 'operations';

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

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

        $Redirect = 'operations';

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

    public function importCreate()
    {
       return view('operations.import');
    }

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

        Session::put('OperationsData', $operations_data);

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

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

            return view('operations.preview', compact('data'));

        } catch (\Exception $e) {

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

    public function importSessionDestroy(Request $request)
    {
        $operations_data = Session::get('OperationsData');

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

        Session::put('OperationsData', $operations_data);

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

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

        if($data){

            foreach ($data as $row){

                $category = OperationCategory::select('id')->where('category', $row[1])->first();

                if(!$category) {
                    $priority = OperationCategory::max('priority')+1;
                    $operation_category = ([
                        'category' => $row[1],
                        'priority' => $priority,
                    ]);

                    $category = OperationCategory::create($operation_category);
                }

                $priority = Operation::max('priority')+1;

                $operations = ([
                    'operation'   => $row[0],
                    'category_id' => $category->id,
                    'priority'    => $priority,
                ]);

                $exist_operations = Operation::where('operation', $row[0])->exists();

                if(!$exist_operations){
                    Operation::create($operations);
                }
            }

            return redirect()->route('operations.index')
                ->with('success','Operations uploaded successfully');
        }else{
           return redirect()->back()
                ->with('error','Empty file uploaded');
        }
    }
}
