<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\Models\FAQ;
use App\Models\Apptitle;
use Auth;
use App\Models\FaqCategory;
use App\Models\User;
use Illuminate\Support\Facades\Schema;
use Spatie\Permission\Models\Role;
use Illuminate\Support\Str;
use Jenssegers\Agent\Agent;
use Torann\GeoIP\Facades\GeoIP;
use App\Models\EmployeeActivity;

class FAQController extends Controller
{
	public function index(Request $request)
	{
		$this->authorize('FAQs Access');
		$faq = FAQ::with('faqcategory');

		$searchTerm = $request['filter'] ?? null;
		$perPage    = $request['per_page'] ?? 15;
		$page       = $request['page'] ?? 1;

		if ($searchTerm) {
			$faq->where(function ($query) use ($searchTerm) {
				$columns = Schema::getColumnListing('faq_list');
				foreach ($columns as $column) {
					$query->orWhere($column, 'LIKE', "%{$searchTerm}%");
				}
			});
		}
		$items = $faq->paginate($perPage);
		$data['queryList'] = $items;

		$basic = Apptitle::first();
		$data['basic'] = $basic;

		$faqcategory = FaqCategory::where('status', 1)->latest()->get();
		$data['faqcategorys'] = $faqcategory;

		$faqcategorylist = FaqCategory::where('status', '1')->get();
		$data['faqcategoryList'] = $faqcategorylist;
		$user = User::with('usetting')->findOrFail(Auth::user()->id);
		$role = Role::where('name', $user->getRoleNames()[0])->get();
		foreach ($role as $roles) {
			$data['permissions'] = $roles->getPermissionNames();
		}
		return $data;
	}


	public function store(Request $request)
	{
		$this->authorize('FAQs Create');
		$request->validate([
			'question' => 'required|max:255',
			'answer' => 'required',
			'faqcatsname' => 'required',

		]);
        $answer = $request->input('answer');

		$this->validate($request, [
			'answer' => ['required',  function ($attribute, $value, $fail) {
				// Remove all HTML tags and decode entities like &nbsp;
				$decodedValue = html_entity_decode(strip_tags($value));

				// Replace non-breaking spaces (\u{A0}) with regular spaces
				$normalizedValue = str_replace("\u{A0}", ' ', $decodedValue);

				// Trim unwanted tags from the start and end
				$normalizedValue = preg_replace('/^(<(p|div)><br><\/(p|div)>)+|(<(p|div)><br><\/(p|di	v)>)+$/', '', $normalizedValue);
				// Trim spaces and check if the result is empty
				if (trim($normalizedValue) === '') {
					$fail('The answer must contain valid text, not just spaces or HTML.');
				}
			}]
		]);

        // Trim unwanted tags from the start and end
        $answer = preg_replace('/^(<(p|div)><br><\/(p|div)>)+|(<(p|div)><br><\/(p|div)>)+$/', '', $answer);

		$faq = FAQ::updateOrCreate(['id' => $request->id], ['question' => $request->question, 'answer' => $answer, 'faqcat_id' => $request->faqcatsname, 'privatemode' => $request->privatemode, 'status' => $request->status]);

		$geolocation = GeoIP::getLocation(request()->getClientIp());
		$agent = new Agent();
		$activity = new EmployeeActivity();
		$activity->user_id = Auth::user()->id;
		$activity->activity_type = $request->faq_id ? ' Updated FAQ' : 'Created FAQ';
		$activity->ip_address = $geolocation->ip;
		$activity->browser = $agent->browser();
		$activity->device = $agent->device();
		$activity->save();

		return response()->json(['code' => 200, 'success' => 'The FAQ has been successfully updated.', 'data' => $faq], 200);
	}

	public function destroy($id)
	{
		$this->authorize('FAQs Delete');
		$this->authorize('FAQs Delete');
		$faq = FAQ::find($id);
		$faq->delete();


		$geolocation = GeoIP::getLocation(request()->getClientIp());
		$agent = new Agent();
		$activity = new EmployeeActivity();
		$activity->user_id = Auth::user()->id;
		$activity->activity_type = 'Deleted a faq';
		$activity->ip_address = $geolocation->ip;
		$activity->browser = $agent->browser();
		$activity->device = $agent->device();
		$activity->save();
		return response()->json(['success' => 'The FAQ has been successfully deleted.', 'data' => $faq]);
	}


	public function allfaqdelete(Request $request)
	{
		$this->authorize('FAQs Delete');
		$id_array = $request->input('id');

		$sendmails = FAQ::whereIn('id', $id_array)->get();

		foreach ($sendmails as $sendmail) {
			$sendmail->delete();
		}
		$geolocation = GeoIP::getLocation(request()->getClientIp());
		$agent = new Agent();
		$activity = new EmployeeActivity();
		$activity->user_id = Auth::user()->id;
		$activity->activity_type = 'Deleted multiple faqs';
		$activity->ip_address = $geolocation->ip;
		$activity->browser = $agent->browser();
		$activity->device = $agent->device();
		$activity->save();
		return response()->json(['success' => 'The FAQ has been successfully deleted.']);
	}

	public function faq(Request $request)
	{
		$this->authorize('FAQs Edit');
		$request->validate([
			'faqtitle' => 'required|max:255',
		]);

		if ($request->faqsub) {
			$request->validate([
				'faqsub' => 'max:255'
			]);
		}
		$calID = ['id' => $request->id];
		$calldetails = [

			'faqtitle'  => $request->faqtitle,
			'faqsub'    => $request->faqsub,
			'faqcheck'  => $request->has('faqcheck') ? 'on' : 'off',

		];

		$callaction = Apptitle::updateOrCreate(
			['id' => $calID],
			$calldetails
		);

		$geolocation = GeoIP::getLocation(request()->getClientIp());
		$agent = new Agent();
		$activity = new EmployeeActivity();
		$activity->user_id = Auth::user()->id;
		$activity->activity_type = $calID ? ' updated faq' : 'Created faq';
		$activity->ip_address = $geolocation->ip;
		$activity->browser = $agent->browser();
		$activity->device = $agent->device();
		$activity->save();

		$message = $calID ? lang('FAQ updated successfully.', 'alerts') : lang('FAQ created successfully.', 'alerts');
		return response()->json(['success' => $message]);
	}

	public function status(Request $request, $id)
	{
		$this->authorize('FAQs Edit');
		$calID = FAQ::find($id);
		$calID->status = $request->status;
		$calID->save();

		$geolocation = GeoIP::getLocation(request()->getClientIp());
		$agent = new Agent();
		$activity = new EmployeeActivity();
		$activity->user_id = Auth::user()->id;
		$activity->activity_type = 'Changed Faq status';
		$activity->ip_address = $geolocation->ip;
		$activity->browser = $agent->browser();
		$activity->device = $agent->device();
		$activity->save();

		return response()->json(['code' => 200, 'success' => 'Updated Successfully'], 200);
	}

	public function privatestatus(Request $request, $id)
	{
		$this->authorize('FAQs Edit');
		$calID = FAQ::find($id);
		$calID->privatemode = $request->privatemode;

		$calID->save();

		$geolocation = GeoIP::getLocation(request()->getClientIp());
		$agent = new Agent();
		$activity = new EmployeeActivity();
		$activity->user_id = Auth::user()->id;
		$activity->activity_type = 'Changed private status of faq';
		$activity->ip_address = $geolocation->ip;
		$activity->browser = $agent->browser();
		$activity->device = $agent->device();
		$activity->save();

		return response()->json(['code' => 200, 'success' => 'Updated Successfully'], 200);
	}
}
