master_template/app/Http/Controllers/FormsController.php
2024-06-10 18:06:58 +05:45

375 lines
14 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Mail\CustomMailer;
use App\Models\Enquiries;
use App\Models\Forms;
use App\Models\Formsubmissions;
use App\Models\Settings;
use App\Service\CommonModelService;
use Exception;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Validator;
use Log;
class FormsController extends Controller
{
protected $modelService;
public function __construct(Forms $model)
{
$this->modelService = new CommonModelService($model);
}
public function index(Request $request)
{
createActivityLog(FormsController::class, 'index', ' Forms index');
$data = Forms::where('status', '<>', -1)->orderBy('display_order')->get();
return view("crud.generated.forms.index", compact('data'));
}
public function create(Request $request)
{
createActivityLog(FormsController::class, 'create', ' Forms create');
$TableData = Forms::where('status', '<>', -1)->orderBy('display_order')->get();
return view("crud.generated.forms.create", compact('TableData'));
}
public function store(Request $request)
{
createActivityLog(FormsController::class, 'store', ' Forms store');
$validator = Validator::make($request->all(), [
//ADD REQUIRED FIELDS FOR VALIDATION
]);
if ($validator->fails()) {
return response()->json([
'error' => $validator->errors(),
], 500);
}
$request->request->add(['alias' => slugify($request->title)]);
$request->request->add(['display_order' => getDisplayOrder('tbl_forms')]);
$requestData = $request->all();
array_walk_recursive($requestData, function (&$value) {
$value = str_replace(env('APP_URL') . '/', '', $value);
});
array_walk_recursive($requestData, function (&$value) {
$value = str_replace(env('APP_URL'), '', $value);
});
// dd($requestData);
$fieldNames = $_POST['fieldNames'];
$fieldTypes = $_POST['fieldTypes'];
$fieldDefaults = $_POST['fieldDefaults'];
$fieldCss = $_POST['fieldCss'];
$fieldData = [];
// Loop through the arrays and create an associative array for each field
for ($i = 0; $i < count($fieldNames); $i++) {
$fieldData[] = [
'fieldName' => $fieldNames[$i],
'fieldType' => $fieldTypes[$i],
'fieldDefault' => $fieldDefaults[$i],
'fieldCss' => $fieldCss[$i],
];
}
// Convert the field data array to JSON string
$requestData["form_fields"] = json_encode($fieldData);
DB::beginTransaction();
try {
$operationNumber = getOperationNumber();
$this->modelService->create($operationNumber, $operationNumber, null, $requestData);
} catch (\Exception $e) {
DB::rollBack();
Log::info($e->getMessage());
return response()->json(['status' => false, 'message' => $e->getMessage()], 500);
}
DB::commit();
if ($request->ajax()) {
return response()->json(['status' => true, 'message' => 'The Forms Created Successfully.'], 200);
}
return redirect()->route('forms.index')->with('success', 'The Forms created Successfully.');
}
public function sort(Request $request)
{
$idOrder = $request->input('id_order');
foreach ($idOrder as $index => $id) {
$companyArticle = Forms::find($id);
$companyArticle->display_order = $index + 1;
$companyArticle->save();
}
return response()->json(['status' => true, 'content' => 'The articles sorted successfully.'], 200);
}
public function updatealias(Request $request)
{
$articleId = $request->input('articleId');
$newAlias = $request->input('newAlias');
$companyArticle = Forms::find($articleId);
if (!$companyArticle) {
return response()->json(['status' => false, 'content' => 'Company article not found.'], 404);
}
$companyArticle->alias = $newAlias;
$companyArticle->save();
return response()->json(['status' => true, 'content' => 'Alias updated successfully.'], 200);
}
public function show(Request $request, $id)
{
createActivityLog(FormsController::class, 'show', ' Forms show');
$data = Forms::findOrFail($id);
return view("crud.generated.forms.show", compact('data'));
}
public function edit(Request $request, $id)
{
createActivityLog(FormsController::class, 'edit', ' Forms edit');
$TableData = Forms::where('status', '<>', -1)->orderBy('display_order')->get();
$data = Forms::findOrFail($id);
if ($request->ajax()) {
$html = view("crud.generated.forms.ajax.edit", compact('data'))->render();
return response()->json(['status' => true, 'content' => $html], 200);
}
return view("crud.generated.forms.edit", compact('data', 'TableData'));
}
public function update(Request $request, $id)
{
createActivityLog(FormsController::class, 'update', ' Forms update');
$validator = Validator::make($request->all(), [
//ADD VALIDATION FOR REQIRED FIELDS
]);
if ($validator->fails()) {
return response()->json([
'error' => $validator->errors(),
], 500);
}
$requestData = $request->all();
array_walk_recursive($requestData, function (&$value) {
$value = str_replace(env('APP_URL') . '/', '', $value);
});
array_walk_recursive($requestData, function (&$value) {
$value = str_replace(env('APP_URL'), '', $value);
});
$fieldNames = $_POST['fieldNames'];
$fieldTypes = $_POST['fieldTypes'];
$fieldDefaults = $_POST['fieldDefaults'];
$fieldCss = $_POST['fieldCss'];
$fieldData = [];
// Loop through the arrays and create an associative array for each field
for ($i = 0; $i < count($fieldNames); $i++) {
$fieldData[] = [
'fieldName' => $fieldNames[$i],
'fieldAlias' => slugify($fieldNames[$i]),
'fieldType' => $fieldTypes[$i],
'fieldDefault' => $fieldDefaults[$i],
'fieldCss' => $fieldCss[$i],
];
}
// Convert the field data array to JSON string
$requestData["form_fields"] = json_encode($fieldData);
DB::beginTransaction();
try {
$OperationNumber = getOperationNumber();
$this->modelService->update($OperationNumber, $OperationNumber, null, $requestData, $request->input('form_id'));
} catch (Exception $e) {
DB::rollBack();
Log::info($e->getMessage());
createErrorLog(FormsController::class, 'update', $e->getMessage());
return response()->json(['status' => false, 'message' => $e->getMessage()], 500);
}
DB::commit();
if ($request->ajax()) {
return response()->json(['status' => true, 'message' => 'The Forms updated Successfully.'], 200);
}
// return redirect()->route('forms.index')->with('success','The Forms updated Successfully.');
return redirect()->back()->with('success', 'The Forms updated successfully.');
}
public function destroy(Request $request, $id)
{
createActivityLog(FormsController::class, 'destroy', ' Forms destroy');
DB::beginTransaction();
try {
$OperationNumber = getOperationNumber();
$this->modelService->destroy($OperationNumber, $OperationNumber, $id);
} catch (Exception $e) {
DB::rollBack();
Log::info($e->getMessage());
createErrorLog(FormsController::class, 'destroy', $e->getMessage());
return response()->json(['status' => false, 'message' => $e->getMessage()], 500);
}
DB::commit();
return response()->json(['status' => true, 'message' => 'The Forms Deleted Successfully.'], 200);
}
// public function submitenquiry(Request $r)
// {
// // dd($r->all());
// $validator = Validator::make($r->all(), [
// 'g-recaptcha-response' => 'required',
// ]);
// if ($validator->fails()) {
// return redirect()
// ->route('register')
// ->withErrors($validator)
// ->withInput();
// }
// $r = $r->all();
// $captcha = $r['g-recaptcha-response'];
// // dd($captcha);
// $response = Http::get("https://www.google.com/recaptcha/api/siteverify", [
// 'secret' => env('RECAPTCHA_SECRET_KEY'),
// 'secret' => SITEVARS->recaptcha_secret_key,
// 'response' => $captcha,
// ]);
// $response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=" . env("RECAPTCHA_SECRET_KEY") . "&response=" . $captcha . "&remoteip=" . $_SERVER['REMOTE_ADDR']), true);
// dd($response);
// $response = $response->json(); //['success'];
// if ($response['success'] == false) {
// return response()->json(['success' => false, 'message' => 'Captcha Validation Error. Refresh and submit the form again']);
// }
// $FormData = array(
// "name" => isset($r['name']) ? $r['name'] : "",
// "email" => isset($r['email']) ? $r['email'] : "",
// "phone" => isset($r['phone']) ? $r['phone'] : "",
// "preparationclassoffers_id" => isset($r['preparationclassoffers_id']) ? $r['preparationclassoffers_id'] : "",
// );
// dd($FormData);
// DB::table('enquiries')->insert($FormData);
// $mailer = new CustomMailer($FormData);
// Mail::to("deepakstha123321@gmail.com")->send($mailer->enquiryform());
// if (!empty(SITEVARS->email)) {
// Mail::to(SITEVARS->email)->send($mailer->enquiryform());
// }
// Mail::to($r['email'])->send($mailer->enquiryresponse());
// // Respond back to the customer
// return response()->json(['success' => true, 'message' => 'Form submitted successfully!']);
// }
public function submitEnquiry(Request $r)
{
$validator = Validator::make($r->all(), [
'name' => 'required',
'email' => 'required|email',
'phone' => 'required',
'preparationclassoffers_id' => 'required_if:enquiry_type,class',
'message' => 'required_if:enquiry_type,contact',
'g-recaptcha-response' => 'required',
'agree' => 'required',
], [
'name' => 'Name is required.',
'preparationclassoffers_id' => 'Select at least one classs.',
'g-recaptcha-response.required' => 'Please complete the security verification.',
'email.required' => 'Email is required.',
'email.email' => 'Must be a valid email address.',
'phone.required' => 'Phone number is required.',
'agree.required' => 'You must agree to the terms and conditions.',
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 422);
}
$setting = Settings::where('status', 1)->first();
// Validate reCAPTCHA response
$captcha = $r['g-recaptcha-response'];
$response = Http::get("https://www.google.com/recaptcha/api/siteverify", [
'secret' => $setting->recaptcha_secret_key,
'response' => $captcha,
]);
$responseData = $response->json();
if (!$responseData['success']) {
return response()->json(['error' => false, 'message' => 'Captcha validation failed'], 422);
}
$FormData = [
"name" => $r->input('name'),
"email" => $r->input('email'),
"phone" => $r->input('phone'),
"enquiry_type" => $r->input('enquiry_type'),
];
if ($r->enquiry_type == "contact") {
$FormData['message'] = $r->input('message');
} else {
$FormData['preparationclassoffers_id'] = $r->input('preparationclassoffers_id');
}
Enquiries::create($FormData);
$mailer = new CustomMailer($FormData);
if (!empty(SITEVARS->email)) {
Mail::to(SITEVARS->email)->send($mailer->enquiryform());
} else {
Mail::to("info@access-skills.com")->send($mailer->enquiryform());
}
Mail::to($r['email'])->send($mailer->enquiryresponse());
return response()->json(['success' => true, 'message' => 'Your registeration form submitted successfully']);
}
public function handleFormSubmission(Request $r)
{
$r = $r->all();
$FormID = $r['form_id'];
$FormFields = Forms::where("form_id", $FormID)->pluck('form_fields')[0];
$tableName = 'formsubmissions';
if (!Schema::hasTable($tableName)) {
Schema::create($tableName, function (Blueprint $table) {
$table->increments('formsubmission_id');
$table->integer('forms_id')->unsigned();
$table->json('submitted_values');
$table->integer('display_order')->default(0);
$table->integer('status')->default(1);
$table->timestamps();
$table->integer('createdby')->nullable();
$table->integer('updatedby')->nullable();
});
}
$FormFields = json_decode($FormFields);
$FilledForm = array();
foreach ($FormFields as $FormField) {
$fieldData = new \stdClass;
$fieldData->fieldName = $FormField->fieldName;
$fieldData->fieldType = $FormField->fieldType;
$fieldData->fieldValue = isset($r[strtolower($FormField->fieldAlias)]) ? $r[strtolower($FormField->fieldAlias)] : "";
$FilledForm[] = $fieldData;
}
$FilledForm = json_encode($FilledForm);
$formSubmission = new FormSubmissions();
$formSubmission->forms_id = $FormID;
$formSubmission->submitted_values = $FilledForm;
$formSubmission->save();
return redirect()->back()->with('success', 'Form submitted successfully!');
}
}