<?php

namespace App\Http\Controllers\Api\School;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Mail;
use Illuminate\Mail\Message;
use App\Models\HelpSupport;
use Exception;

class HelpSupportController extends Controller
{
    public function store(Request $request)
    {
        try {
            // Validate request
            $validation = Validator::make($request->all(), [
                'name' => 'required|string|max:255',
                'number' => 'required|string|max:20',
                'email' => 'required|email|max:255',
                'message' => 'nullable|string',
            ]);

            if ($validation->fails()) {
                return response()->json([
                    'validation_errors' => $validation->messages(),
                    'response_status' => 400,
                ], 200);
            }

            // Prepare email data
            $emailData = [
                'name' => $request->name,
                'number' => $request->number,
                'email' => $request->email,
                'message' => $request->message ?? 'No message provided',
            ];
            
            $support_email = env('SUPPORT_EMAIL');

            // Send email with the request data
            Mail::send('help_support', ['data' => $emailData], function (Message $message) use ($support_email) {
                $message->subject('Help Support Request From School');
                $message->to($support_email);  // Support email address from .env file
                $message->from(env('MAIL_FROM_ADDRESS'), env('MAIL_FROM_NAME'));
            });

            return response()->json([
                'response_message' => ['success' => ['Help support request submitted successfully!']],
                'response_status' => 200,
            ], 200);
        } catch (\Exception $exception) {
            return response()->json([
                'validation_errors' => $exception->getMessage(),
                'response_status' => 400,
            ], 200);
        }
    }
}
