<?php

namespace App\Http\Controllers;

use App\query;
use App\query_reply;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class QueryReplyController extends Controller
{
    public function index($id)
    {
//        $query_reply = query_reply::where('query_id','=',$id)->get();
        $query_reply = DB::table('query_reply as qr')
            ->join('users as us', 'qr.replied_by', '=', 'us.id')
            ->join('user_type as ut', 'us.user_type_id', '=', 'ut.id')
            ->select('qr.*', 'ut.user_type')
            ->where('qr.query_id', '=', $id)
            ->orderby('qr.id','desc')
            ->get();
       if ($query_reply) {
            $data['query_reply'] = $query_reply;
            $data['status'] = 1;
            $data['message'] = "Query replies retrieved successfully";
            return response($data, 200);
        } else {
            $data['status'] = 0;
            $data['message'] = "Query reply retrieval failed";
            return response($data, 400);
        }
    }

    public function store(Request $request)
    {
        $input = $request->all();
        $validator = \Validator::make($input, [
            'query_id' => 'required|integer',
            'query_reply' => 'required|string',
        ]);
        if ($validator->passes()) {
            $query_reply = new query_reply();
            $query_reply->query_id = $request->input('query_id');
            $query_reply->query_reply = $request->input('query_reply');
            if($request->input('replied_by'))
            $query_reply->replied_by =  $request->input('replied_by');
            else
                $query_reply->replied_by = 0;
            $query_reply->save();
            $toUpdate = array('reply_status' => 1);
            $result = query::where('id', $query_reply->query_id)->update($toUpdate);
            $data['status'] = 1;
            $data['message'] = 'Query replied successfully';
            $data['id'] = $query_reply->id;
            return response($data, 200);
        } else {
            $data['message'] = $validator->errors(0);
            $data['status'] = 0;
            return response($data, 400);
        }
    }
}
