<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\TreatmentType;

class TreatmentTypeController extends Controller
{

   public function index(Request $request)
    {
        $data = TreatmentType::orderBy('priority', 'ASC')->paginate(10);

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = TreatmentType::when(!empty($search_query), function ($query) use ($search_query) {
                            return $query->where('title', 'like', '%'.$search_query.'%');
                        })
                        ->orderBy('priority', 'ASC')->paginate($sort_by);
            return view('treatment-types.table', compact('data'));
        }
        else
        {
            return view('treatment-types.index',compact('data'));
        }
    }



    public function create()
    {
        $priority = TreatmentType::max('priority');
        $priority = $priority != '' ? $priority : 0;
        return view('treatment-types.create', compact('priority'));
    }

	public function edit($id)
    {
        $type = TreatmentType::find($id);
        return view('treatment-types.edit',compact('type'));
    }

    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
           'title'     => 'unique:treatment_types,title,'.$id,
            'priority' => 'required',
            'code' => 'required',
        ]);

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

        $data['code'] = strtoupper($data['code']);
        $division = TreatmentType::find($id);

        if (!$division) {
            return redirect()->route('treatment-types.index')
                ->with('error','Treatment Type not found!');
        }

        $division->update($data);

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

        return redirect()->route('treatment-types.index')
            ->with('success','Treatment Type updated successfully');
    }

    public function changedefault(Request $request)
    {
       if ($request->ajax())
       {
            $data  = array('is_default' => $request->status );
            $count = TreatmentType::where(['is_default' => $request->status])->count();

            if ($count > 0 && $request->status == 1) {
                return response()->json([
                    'success' => false,
                    'message' => ['There is already a default Treatment Type!'],
                    'data'    => []
                ]);
            }

           $Update = TreatmentType::where('id', '=', $request->id)->update($data);

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

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

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

        $default_check = TreatmentType::where(['is_default' => '1','status' => '1'])->first();

        if (!$default_check) {
            $data['is_default'] = "1";
        }

        $data['code'] = strtoupper($data['code']);

        $quality = TreatmentType::create($data);

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

        return redirect()->route('treatment-types.index')
            ->with('success','Treatment Type created successfully');
    }

    public function destroy(Request $request)
    {
        $account = TreatmentType::find($request->id);

        if ($account->is_default == '1') {
            return response()->json([
                'success' => false,
                'message' => ['Default record can not be deleted.']
            ]);
        }

        $account->delete();
        $Redirect = 'treatment-types';

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

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

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