<?php

namespace Wave\Http\Controllers\CMS;

use App\Http\Controllers\Controller;
use App\Models\UserEnquiry;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

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

    public function index()
    {
        $companySecretaryEnquiries = UserEnquiry::where('category', 'company_secretary')->get();
        $generalEnquiries = UserEnquiry::where('category', 'general')->get();
        return view('theme::cms.enquiries.index', [
            'companySecretaryEnquiries' => $companySecretaryEnquiries,
            'generalEnquiries' => $generalEnquiries,
        ]);
    }

    public function show(UserEnquiry $enquiry)
    {
        $enquiry->company_name = isset($enquiry->user->company->name) ? $enquiry->user->company->name : '-';
        $enquiry->submitted_date = $enquiry->created_at->format('d/m/Y H:i');
        return response()->json([
            'success' => true,
            'message' => '',
            'enquiry' => $enquiry,
        ]);
    }

    public function updateReply(UserEnquiry $enquiry, Request $request)
    {
        $validator = Validator::make($request->all(), [
            'reply' => 'required|string',
        ]);
        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => __('Fill up all required fields!')
            ], 200);
        }
        else {
            $enquiry->reply = $request->reply;
            $enquiry->save();
    
            return response()->json([
                'success' => true,
                'message' => __("Reply have been saved!"),
            ]);
        }
    }
}
