<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Apptitle;
use App\Models\User;
use App\Entities\Cannedmessages;
use Auth;
use Spatie\Permission\Models\Role;
use Illuminate\Support\Facades\Crypt;

use App\Services\EncryptionService;
use Illuminate\Support\Facades\Schema;
use Jenssegers\Agent\Agent;
use Torann\GeoIP\Facades\GeoIP;
use App\Models\EmployeeActivity;

class CannedmessagesController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Renderable
     */
    public function index(Request $request)
    {
        $this->authorize('Canned Response Access');
        $cannedmessages = Cannedmessages::latest();

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

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

        $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 details()
    {
        $this->authorize('Canned Response Access');
        $data['setting'] = response()->json([]);

        return  $data;
    }

    /**
     * Show the form for creating a new resource.
     * @return Renderable
     */
    public function create()
    {
        $this->authorize('Canned Response Create');
        $title = Apptitle::first();
        $data['title'] = $title;

        return $data;
    }

    /**
     * Store a newly created resource in storage.
     * @param Request $request
     * @return Renderable
     */
    public function store(Request $request)
    {
        $request->validate([

            'title' => 'required|max:255',
            'message' => 'required',

        ]);

        $this->validate($request, [
            'message' => ['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 spaces and check if the result is empty
                if (trim($normalizedValue) === '') {
                    $fail('The comment must contain valid text, not just spaces or HTML.');
                }
            }]
        ]);

        $comment = $request->input('message');

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

        Cannedmessages::create([
            'title' => $request->title,
            'messages' => $comment,
            'status' => $request->statuscanned ? 1 : 0,
            'responsetype' => $request->responsetype == 'livechat' ? 'livechat' : null,
        ]);

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

        return response()->json(['success' => 'Update Successfully']);
    }


    /**
     * Show the form for editing the specified resource.
     * @param int $id
     * @return Renderable
     */
    public function edit($id)
    {
        $this->authorize('Canned Response Edit');

        $cannedmessages = Cannedmessages::findOrFail($id);
        $data['cannedmessage'] = $cannedmessages;

        return $data;
    }

    /**
     * Update the specified resource in storage.
     * @param Request $request
     * @param int $id
     * @return Renderable
     */
    public function update(Request $request, $id)
    {
        $cannedmessages = Cannedmessages::findOrFail($id);
        $this->validate($request, [
            'message' => ['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 spaces and check if the result is empty
                if (trim($normalizedValue) === '') {
                    $fail('The comment must contain valid text, not just spaces or HTML.');
                }
            }]
        ]);

        $comment = $request->input('message');

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

        $cannedmessages->title = $request->title;
        $cannedmessages->messages = $comment;
        $cannedmessages->status = $request->statuscanned ? 1 : 0;
        $cannedmessages->responsetype = $request->responsetype == 'livechat' ? 'livechat' : null;
        $cannedmessages->update();

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

        return response()->json(['success' => 'Update Successfully']);
    }

    /**
     * Remove the specified resource from storage.
     * @param int $id
     * @return Renderable
     */
    public function destroy($id)
    {
        $this->authorize('Canned Response Delete');
        $cannedmessages = Cannedmessages::findOrFail($id);
        $cannedmessages->delete();

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

        return response()->json(['success' => 'Canned Response Deleted Successfully']);
    }

    /// Status changing method
    public function status(Request $request)
    {
        $cannedmessages = Cannedmessages::findOrFail($request->id);
        $cannedmessages->status = $request->status;
        $cannedmessages->update();

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

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

    // Delete Selected Canned Messages
    public function destroyall(Request $request)
    {
        $id_array = $request->input('id');
        $cannedmessages = Cannedmessages::findOrFail($id_array);
        foreach ($cannedmessages as $cannedmessage) {

            $cannedmessage->delete();
        }

        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Deleted multiple canned messages.';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        return response()->json(['success' => 'Canned Response Deleted Successfully']);
    }
}
