<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Announcement;
use App\Models\User;
use Auth;
use Illuminate\Support\Facades\Schema;
use Spatie\Permission\Models\Role;
use App\Models\EmployeeActivity;
use Torann\GeoIP\Facades\GeoIP;
use Jenssegers\Agent\Agent;

class AdminAnnouncementController extends Controller
{

    public function index(Request $request)
    {

        $this->authorize('Announcements Access');

        $setting = response()->json(['ANNOUNCEMENT_USER' => setting('ANNOUNCEMENT_USER'), 'date_format' => setting('date_format'),  'start_week' => setting('start_week')]);
        $data['setting'] = $setting;

        $user = User::with('usetting')->findOrFail(Auth::user()->id);

        $role = Role::where('name', $user->getRoleNames()[0])->get();
        foreach ($role as $roles) {
            $data['permissions'] = $roles->getPermissionNames();
        }

        $announcements = Announcement::latest();

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

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

        // announcement date exceeds today date, the status of the announcement will inactive
        $now = now();
        $announcementsupdate = Announcement::whereDate('enddate', '<', $now->toDateString())->get();
        if ($announcementsupdate != null) {
            foreach ($announcementsupdate as $announcementsupdates) {
                $announcementsupdates->status = 0;
                $announcementsupdates->update();
            }
        }
        return $data;
    }
    public function create(Request $request)
    {


        $normalDay = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
        $data['normalDay'] = $normalDay;


        return $data;
    }


    public function store(Request $request)
    {
        if (count($request->announcementday) == 0 && $request->startdate == null) {
            return response()->json(['code' => 500, 'error' => lang('Please select Date or Day for Announcement.', 'alerts')], 500);
        }
        $this->validate($request, [
            'notice' => ['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|div)>)+$/', '', $normalizedValue);
                // Trim spaces and check if the result is empty
                if (trim($normalizedValue) === '') {
                    $fail('The comment must contain valid text, not just spaces or HTML.');
                }
            }]
        ]);

        if (count($request->announcementday)) {
            $request->validate([
                'title' => 'required|max:255',
                'notice' => 'required',
                'announcementday' => 'required'
            ]);

            $announcementdayData = $request->announcementday;
            $ancData = [];
            foreach ($announcementdayData as $announcementdayDatas) {
                $ancData[] = $announcementdayDatas;
            }
            $ancDataFinal = implode(',',  $ancData);
        } else {

            $request->validate([
                'title' => 'required|max:255',
                'notice' => 'required',
                'startdate' => 'required',
                'enddate' => 'required',
            ]);
            $ancDataFinal = null;
        }


        if ($request->buttonurl != null) {
            $request->validate([
                'buttonurl' => 'required|url',
            ]);
        }

        $comment = $request->input('notice');
        $comment = preg_replace('/^(<(p|div)><br><\/(p|div)>)+|(<(p|div)><br><\/(p|div)>)+$/', '', $comment);
        $testi =  [
            'title' => $request->title,
            'notice' => $comment,
            'buttonlable' => $request->buttonlable,
            'buttonurl' => $request->buttonurl,
            'startdate' => $request->startdate,
            'enddate' => $request->enddate,
            'primary_color' => $request->primary_color,
            'secondary_color' => $request->secondary_color,
            'status' => $request->status,
            'announcementday' => $ancDataFinal
        ];

        $testimonial = Announcement::Create($testi);

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

        return response()->json(['code' => 200, 'success' => 'An announcement has been created successfully.', 'data' => $testimonial], 200);
    }

    public function edit($id)
    {

        $announcementData = Announcement::findOrFail($id);
        $data['announcementData'] = $announcementData;

        $normalDay = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
        $data['normalDay'] = $normalDay;

        $announceDay = explode(',', $announcementData->announcementday);
        $data['announceDay'] = $announceDay;

        return $data;
    }

    public function update(Request $request)
    {
        if ($request->announcementday == null && $request->startdate == null) {
            return response()->json(['code' => 500, 'error' => lang('Please select Date or Day for Announcement.', 'alerts')], 500);
        }

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

        // Trim unwanted tags from the start and end
        $notice = preg_replace('/^(<(p|div)><br><\/(p|div)>)+|(<(p|div)><br><\/(p|div)>)+$/', '', $notice);
        if ($request->announcementday) {
            $request->validate([
                'title' => 'required|max:255',
                'notice' => 'required',
                'announcementday' => 'required'
            ]);

            $announcementdayData = $request->announcementday;
            $ancData = [];
            foreach ($announcementdayData as $announcementdayDatas) {
                $ancData[] = $announcementdayDatas;
            }
            $ancDataFinal = implode(',',  $ancData);
        } else {
            $request->validate([
                'title' => 'required|max:255',
                'notice' => 'required',
                'startdate' => 'required',
                'enddate' => 'required',
            ]);
            $ancDataFinal = null;
        }

        if ($request->buttonurl != null) {
            $request->validate([
                'buttonurl' => 'required|url',
            ]);
        }

        if ($request->startdate != null && $request->enddate != null) {
            $ancDataFinal = null;
        }

        $testimonial = Announcement::findOrFail($request->testimonialId);
        $testimonial->title = $request->title;
        $testimonial->notice = $notice;
        $testimonial->buttonlable = $request->buttonlable;
        $testimonial->buttonurl = $request->buttonurl;
        $testimonial->startdate = $request->startdate;
        $testimonial->enddate = $request->enddate;
        $testimonial->primary_color = $request->primary_color;
        $testimonial->secondary_color = $request->secondary_color;
        $testimonial->status = $request->status;
        $testimonial->announcementday = $ancDataFinal;
        $testimonial->save();


        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Edited an announcement' . ' ' . $testimonial->title;
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

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

    public function show($id)
    {


        $post = Announcement::find($id);

        return response()->json($post);
    }


    public function destroy($id)
    {


        $announcement = Announcement::find($id);
        $announcement->delete();

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

        return response()->json(['success' => 'The announcement was successfully deleted.']);
    }

    public function allannouncementdelete(Request $request)
    {


        $id_array = $request->input('id');

        $sendmails = Announcement::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 announcement';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();
        return response()->json(['success' => 'The announcement was successfully deleted.']);
    }

    public function status(Request $request, $id)
    {

        $calID = Announcement::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 announcement status of' . ' ' . $calID->title;
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

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