<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Mail\ReplyMail;
use App\Models\ManageContactus;

use Illuminate\Support\Facades\Mail;

class ManageContactUsController extends Controller
{
    /**
     * Created By : sayali parab
     * Created at : 05 June 2024
     * Use : To get contact us  page.
     */
    public function index(Request $request)
    {

        $isReply = $request->query('is_reply');

        if ($isReply == 1) {
            $queries = ManageContactUs::with('customer')->where('is_reply', 1)->orderBy('id','asc')->get();
        } elseif ($isReply == 0 && $isReply != null) {
            $queries = ManageContactUs::with('customer')->where('is_reply', 0)->orderBy('id','asc')->get();
        } else {
            $queries = ManageContactUs::with('customer')->orderBy('id','asc')->get();
        }
        return view('Admin.pages.manage_contact_us.manage_contact', compact('queries'));
    }

        /**
     * Created By : Sayli Raut
     * Created at : 10 June 2024
     * Use : To send reply.
     */
    public function sendReply(Request $request)
    {
        if (!$request->user_id ||  $request->user_id == null) {
            return response()->json(['error' => 'User not found'], 404);
        }
        $userId = $request->user_id;


        $query = ManageContactus::find($userId);
        if (!$query) {
            return response()->json(['error' => 'Query not found'], 404);
        }

        $request->validate([
            'reply_message' => 'required|string',
        ]);

        $query->reply_message = $request->input('reply_message');
        $query->is_reply = true;
        $query->save();

        try {
            Mail::to($query->email)->send(new \App\Mail\ReplyMail($query));
        } catch (\Exception $e) {
            return response()->json(['error' => 'Failed to send email', 'message' => $e->getMessage()], 500);
        }

        return response()->json(['message' => 'Reply sent successfully']);
    }



        /**
     * Created By : Sayli Raut
     * Created at : 10 June 2024
     * Use : To delete query.
     */
    public function delete_user($id)
    {
        $data = ManageContactUs::find($id)->delete();
        return redirect()->back()->with('success', '');
    }
}
