<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Customer;
use App\Models\Sendmail;
use App\Models\senduserlist;
use Auth;
use App\Notifications\CustomerCustomNotifications;
use Illuminate\Support\Facades\Schema;
use Spatie\Permission\Models\Role;
use laravelLara\infoinst\Jobs\MailSend;
use Torann\GeoIP\Facades\GeoIP;
use Jenssegers\Agent\Agent;
use App\Models\EmployeeActivity;
use App\Jobs\BulkMails;

class MailboxController extends Controller
{
    public function index(Request $request)
    {

        $this->authorize('Custom Notifications Access');


        $customnotifyList = Sendmail::with('touser')->latest();

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

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

        $customnotify = Sendmail::with('touser')->latest()->get();


        $catlist = [];
        foreach ($customnotify as $customnot) {
            foreach ($customnot->touser()->get() as $cc) {
                if ($cc->touser) {
                    array_push($catlist, $cc->touser);
                } else {
                    array_push($catlist, $cc->tocust);
                }
            }
        }
        $data['catlist'] = [...array_unique($catlist)];

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

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

        $users = User::with('roles')->whereNotIn('id', [1])->get();
        $data['users'] = $users;

        $customer = Customer::where('userType', 'Customer')->get();
        $data['customer'] = $customer;


        return $data;
    }
    public function customnotificationlist()
    {

        $this->authorize('Custom Notifications Access');

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

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

        $users = User::with('roles')->whereNotIn('id', [1])->where('status', 1)->get();
        $data['users'] = $users;

        $customer = Customer::where('userType', 'Customer')->get();
        $data['customer'] = $customer;


        return $data;
    }

    public function customercompose()
    {
        $this->authorize('Custom Notifications Customer');

        $user = Customer::where('userType', 'Customer')->get();
        $data['users'] = $user;

        return $data;
    }

    public function customercomposesend(Request $request)
    {
        $this->authorize('Custom Notifications Customer');
        $request->validate([
            'message' => 'required|max:60000',
            'subject' => 'required|max:255',
            'users' => 'required',
            'tag' => 'required|max:255',
            'selecttagcolor' => 'required',
        ]);
        $mailsend = new Sendmail();
        $mailsend->user_id = Auth::id();
        $mailsend->mailsubject = trim($request->input('subject'));
        $mailsend->mailtext = $request->input('message');
        $mailsend->tag = $request->input('tag');
        $mailsend->selecttagcolor = $request->input('selecttagcolor');
        $mailsend->save();
        $usersString = explode(',', $request->users);
        foreach ($usersString as $value) {
            senduserlist::create([
                'mail_id' => $mailsend->id,
                'tocust_id' => $value,
            ]);
        }

        $cust = Customer::find($usersString);

        foreach ($cust as $value) {

            $value->notify(new CustomerCustomNotifications($mailsend));
        }

        $ticketData = [
            'notification_subject' => $mailsend->mailsubject,
            'notification_message' => $mailsend->mailtext,
            'notification_tag' => $mailsend->tag,
        ];
        // foreach ($cust as $value) {
        //     try {
        //         dispatch((new MailSend($value->email, 'when_send_customnotify_email_to_selected_member', $ticketData)));
        //     } catch (\Exception $e) {
        //         return response()->json(['success' => 'A custom notification was successfully sent to the customer.']);
        //     }
        // }
        try {
            $batchSize = $request->batchSize ?? 50;
            $delayBetweenBatches = $request->batchDelay ?? 5;
            $chunks = $cust->chunk($batchSize);
            foreach ($chunks as $batchIndex => $batch) {
                $batchDelay = $batchIndex * $delayBetweenBatches;
                $emails = $batch->pluck('email')->toArray();
                dispatch((new BulkMails($emails, $mailsend))->delay(now()->addMinutes($batchDelay)));
            }
        } catch (\Throwable $th) {

            return  response()->json(['error' => 'An error occurred while sending emails.']);
        }

        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Sends a custom notification to customer';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();
        return response()->json(['success' => 'A custom notification was successfully sent to the customer.']);
    }

    public function employeecompose()
    {
        $this->authorize('Custom Notifications Employee');

        $user = User::get();
        $data['users'] = $user;

        return $data;
    }


    public function employeecomposesend(Request $request)
    {
        $this->authorize('Custom Notifications Employee');
        $request->validate([
            'message' => 'required|max:60000',
            'subject' => 'required|max:255',
            'users' => 'required',
            'tag' => 'required|max:255',
            'selecttagcolor' => 'required',
        ]);
        $mailsend = new Sendmail();
        $mailsend->user_id = Auth::id();
        $mailsend->mailsubject = $request->input('subject');
        $mailsend->mailtext = $request->input('message');
        $mailsend->tag = $request->input('tag');
        $mailsend->selecttagcolor = $request->input('selecttagcolor');
        $mailsend->save();

        
        $usersString = explode(',', $request->users);
        foreach ($usersString as $value) {
            senduserlist::create([
                'mail_id' => $mailsend->id,
                'touser_id' => $value,
            ]);
        }

        $cust = User::find($usersString);
        foreach ($cust as $value) {

            $value->notify(new CustomerCustomNotifications($mailsend));
        }


        $ticketData = [
            'notification_subject' => $mailsend->mailsubject,
            'notification_message' => $mailsend->mailtext,
            'notification_tag' => $mailsend->tag,
        ];
        foreach ($cust as $value) {
            try {
                dispatch((new MailSend($value->email, 'when_send_customnotify_email_to_selected_member', $ticketData)));
            } catch (\Exception $e) {

                $geolocation = GeoIP::getLocation(request()->getClientIp());
                $agent = new Agent();
                $activity = new EmployeeActivity();
                $activity->user_id = Auth::user()->id;
                $activity->activity_type = 'Sends a custom notification to employee';
                $activity->ip_address = $geolocation->ip;
                $activity->browser = $agent->browser();
                $activity->device = $agent->device();
                $activity->save();
                return response()->json(['success' => 'A custom notification was successfully sent to the employee.']);
            }
        }


        $geolocation = GeoIP::getLocation(request()->getClientIp());
        $agent = new Agent();
        $activity = new EmployeeActivity();
        $activity->user_id = Auth::user()->id;
        $activity->activity_type = 'Sends a custom notification to employee';
        $activity->ip_address = $geolocation->ip;
        $activity->browser = $agent->browser();
        $activity->device = $agent->device();
        $activity->save();

        return response()->json(['success' => 'A custom notification was successfully sent to the employee.']);
    }

    public function mailsent()
    {

        $sendmails = Sendmail::latest()->get();
        $data['sendmails'] = $sendmails;

        return $data;
    }

    public function show($id)
    {
        $this->authorize('Custom Notifications View');
        $custom = Sendmail::find($id);

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

    public function destroy($id)
    {
        $this->authorize('Custom Notifications Delete');
        $customdelete = Sendmail::find($id);
        $customdelete->touser()->delete();
        $customdelete->delete();

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

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

    public function allnotifydelete(Request $request)
    {
        $id_array = $request->input('id');

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

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