<?php

namespace App\Http\Controllers\Physician;
 
use Illuminate\Http\Request;
use App\Models\CheifComplainTypes;
use App\Models\Clinics;
use App\Models\Roles;
use App\Models\FormEnteries;
use App\Models\QuestionCategories;
use DateTime;
use App\Http\Controllers\Controller;
use Auth;
use App\User;
use App\Helpers\CommonHelper;
use Illuminate\Support\Facades\Config;
use DB;
use Validator;


class QuestionCategoriesController extends Controller
{
	/**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable 
     */

    public function index()
    {   
    	
        return view('physician.questions.categories.listing');
    }

    public function ajaxListing(Request $request)
    {   
      $_getParams             = $_GET;
      $params                 = CommonHelper::_processDataTableRequest($_getParams);
      
      $draw                   = $params['draw'];      
      $offset                 = $params['offset'];
      $status                 = @$_GET['status'];
      $searchKeyword          = $params['search_keyword'];
      $sortColumn             = $params['sort_column'];
      $sortOrderDirection     = $params['sort_direction'];
      $recordsPerPage         = $params['records_per_page'];

  	 
      $objQuestionCategories  = new QuestionCategories();
      $recordsTotal           = $objQuestionCategories->count();
      $recordsFiltered        = $recordsTotal;
      if($searchKeyword)
      {           
          $objQuestionCategories = $objQuestionCategories->where(function($query) use ($searchKeyword) 
          {
              $query->orWhere('title', 'like', '%'.$searchKeyword.'%');
              
          });
      }
      if($status!='')
      {   
          $objQuestionCategories = $objQuestionCategories->where('status', $status);
      }
      $objQuestionCategories = $objQuestionCategories->offset($offset)->limit($recordsPerPage);
      $recordsFiltered        = $objQuestionCategories->count();
      $objQuestionCategories  = $objQuestionCategories->orderby('question_order', 'ASC')->get();
      $listData = array(); 
      //dd($objUsers);die;         
      foreach ($objQuestionCategories as $row) 
      { 
        $deletePath = route('questions_categories_delete', $row->id);
        $editPath   = route('questions_categories_save', $row->id);
        // ACTIVE AND QUESTION CATAGORIES
            $statusIcon = "ti-close";
            $statusText = "Inactive Now";
            $status = 'Active';
            if($row->status==config('constants.CONSTANT_STATUS_INACTIVE'))
            {   
                $statusIcon = "ti-check";
                $status = 'Inactive';
                $statusText = "Active Now";
            }
        $tplActions  = <<<EOT
            <a title="Edit" class="la la-pencil" href="$editPath" value="edit" style="margin:5px;><i class="" aria-hidden="true"></i></a>
            <small><a title="$statusText" class="$statusIcon" onclick="return confirm('Are you sure want to change the status of this record?')" href="$deletePath"><i class="" aria-hidden="true"></i></a></small>
EOT;
        $tempArray  = array();
        // $tempArray[]    = $row->id;
        if ($row->status == config('constants.CONSTANT_STATUS_INACTIVE')) 
        {
          $status = "Inactive";
        }
        else
        {
          $status = "Active";
        }
        $tempArray[]    = $row->title;
        $tempArray[]    = $row->question_order;
        $tempArray[]    = $status;
        $tempArray[]    = $tplActions;
        $listData[]     = $tempArray;
      }
      $data = array(
          "draw"            => $draw,
          "recordsTotal"    => $recordsTotal,
          "recordsFiltered" => $recordsFiltered,
          "data"            => $listData
      );
      
      return response()->json($data);
    }

    public function add(Request $request)
    {   
      if($request->input('btn-submit')) 
      {
        //Add validation here  

        $questionCategories = new QuestionCategories();
        $this->save($request,$questionCategories);  
        return redirect(route('questions_categories'))->with('success', 'Question Category has been saved successfully!');
      }
      return view('physician.questions.categories.form');
    }

    public function save(Request $request,$id=0)
    {   
      
      $heading = "Add New Question Category";
      $route = route('questions_categories_save');
      $categoryData = new QuestionCategories();

      $questionCategoriesOrder = QuestionCategories::select('question_order')->get();
      foreach ($questionCategoriesOrder as  $value) 
        {
          $question_order[] =  $value->question_order;
        }
        $question_order = max($question_order);
        $question_order ++ ;
        $question_order = $question_order;
        // dd($question_order );
        $suggestedSortOrder = $question_order;
      if($id)
      {
          $heading = "Edit Question Category";
          $categoryData = QuestionCategories::find($id);
          // $sortOrder = $categoryData;
          $route = route('questions_categories_save',$id);

      }
      if($request->input('btn-submit')) 
      {
        $currentQuestionCategoryId = $request->input('questionCatagoryId');
        $categoryTitle = $request->input('title');
        $sameChiefComplain = QuestionCategories::where('title',$categoryTitle)->where('id','<>',$currentQuestionCategoryId)->first();
        // dd($sameChiefComplain);
        if ($sameChiefComplain)
         {
          $sameChiefComplainName = $sameChiefComplain->name;
         }
        $question_order = $request->input('question_order');
        $currentUserSortOrders = QuestionCategories::select('question_order')->where('question_order',$question_order)->where('id','<>',$currentQuestionCategoryId)->first();
        if ($currentUserSortOrders) 
            {
                $sortOrderExist = "";

                $sortOrderExistInDb = $currentUserSortOrders->question_order;
            }
        else
        {
            $sortOrderExistInDb = "";
            $sortOrderExist = 1;
        }
        if ($sameChiefComplain) 
            {
                $sameChiefComplainNameExist = "";

                $sameChiefComplainName = $sameChiefComplain->name;
            }
        else
        {
            $sameChiefComplainName = "";
            $sameChiefComplainNameExist = 1;
        }
        $rules = array('title' => 'required|max:255', 'question_order' => 'required|numeric|min:1','sortOrderExist' => 'required','sameChiefComplainNameExist' => 'required');
        $messages['title.required']            =  'Title is required';
        $messages['question_order.required']   =  'Question is Order required';
        $messages['question_order.numeric']   =  'Question Order must be a numeric value';
        $messages['sameChiefComplainNameExist.required']   =  'This title is already exists, please choose another one';
        $messages['sortOrderExist.required']   =  'Question category is already exists for sort order "'.$sortOrderExistInDb.'". It should be "'.$suggestedSortOrder.'"';

        $request_all = $request->all();

        $request_all['sameChiefComplainNameExist'] =  $sameChiefComplainNameExist;
        $request_all['sortOrderExist'] =  $sortOrderExist;
        
        $validator = Validator::make($request_all, $rules,$messages);

        if ($validator->fails()) 
        {   
            return redirect(route('questions_categories_save',$currentQuestionCategoryId))->withErrors($validator)->withInput();
        }
        //Add validation here  
        $categoryData->title          = $request->input('title');
        $categoryData->question_order = $request->input('question_order');
        $categoryData->department_id  = Auth::user()->department_id;
        $categoryData->added_by_id    = Auth::user()->id;
        $categoryData->save();
          
        return redirect(route('questions_categories'))->with('success', 'Question Category has been saved successfully!');
      }
      //dd($categoryData->title);die;
      return view('physician.questions.categories.form',['categoryData'=>$categoryData,'route'=>$route, 'heading'=>$heading, 'suggestedSortOrder'=>$suggestedSortOrder ]);
    }

    public function deleteCategories($id)
    {
      if($id)
      {   
        $questionCategories   = QuestionCategories::find($id);
         if(!$questionCategories)
            {
                // Redirect to base
                return redirect(route('admin_users_listing'));
            }
            if(config('constants.CONSTANT_STATUS_INACTIVE')==$questionCategories->status)
            {
                $status = "active";
                $questionCategories->status = config('constants.CONSTANT_STATUS_ACTIVE');
            }
            else
            {
                $status = "inactive";
                $questionCategories->status = config('constants.CONSTANT_STATUS_INACTIVE');
            }
            // if(!$CheifComplainData)
            // {
            //     // Redirect to base
            //     return redirect(route('admin_users_listing'));
            // }
            $questionCategories->save();
        // if(!$questionCategories)
        // {
        //     // Redirect to base
        //     return redirect(route('questions_categories'));
        // }
        // $questionCategories->where('id', $id)->delete();
        return redirect(route('questions_categories'))->with('success', 'Question Category has been '.$status.' successfully!');
          
      }
    }

}