<?php

namespace App\Http\Controllers;

use App\Reminder;
use App\CoiUsers;
use Carbon\Carbon;
use App\Jobs\SendReminderMails;
use Illuminate\Http\Request;
// use Mail;
use Illuminate\Support\Facades\Mail;
use App\Mail\MtnCoiReminder;
use Illuminate\Support\Facades\Log;

class ReminderController extends Controller
{

    public function sendmail($subj, $mailto, $msg)
    {
        Mail::send('emails.MtnCoiReminder', ['data' => ['name' => $mailto, 'reminder' => $msg]], function ($message) use ($subj, $mailto) {
            $message->to($mailto)
                ->subject($subj);
        });

        Log::channel('coi')->info('Email sent to: ' . $mailto);
    }






    public function sendmailOld($subj, $mailto, $msg)
    {
        $curl = curl_init();
        $mailurl = env('MAIL_URL');
        $mailauth = env('MAIL_AUTH');
        curl_setopt_array($curl, array(
            CURLOPT_URL => $mailurl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => '{
      "subject":"' . $subj . '",
      "recipient":"' . $mailto . '",
      "msg":"' . $msg . '"
    }',
            CURLOPT_HTTPHEADER => array(
                $mailauth,
                'Content-Type: application/json'
            ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        Log::channel('coi')->info('curl executed and closed.');
        // echo $response;
        Log::channel('coi')->info('curl response: ' . $response);
    }



    public function index()
    {
        $rem = Reminder::first();

        return view('admin.reminder.index', compact('rem'));
    }


    public function post(Request $r)
    {
        $now = Carbon::now();

        $save = Reminder::updateOrCreate(['id' => 1], [
            'reminder' => $r->reminder,
            'freq' => $r->freq,
            'freq' => $r->group,
            'nextout' => $r->freq == 'None' ? null : $now,
        ]);

        if ($r->freq !== 'None') {
            $group = $r->group;

            if ($group == 'coe') {
                $users = CoiUsers::query()->whereDoesntHave('CoeForm')->get();
                // $emailSubject = 'MTN CODE OF ETHICS REMINDER';
                $emailSubject = 'SCANCOM PLC (MTN Ghana) Conflict of Interest Policy & Code of Ethics '.'REMINDER';
                $emailBody = $r->reminder;
            } else {
                $users = CoiUsers::whereNull('coi_status')->orWhere('status', 'Pending')->get();
                // $emailSubject = 'MTN CONFLICT OF INTEREST REMINDER';
                $emailSubject = 'SCANCOM PLC (MTN Ghana) Conflict of Interest Policy & Code of Ethics '.'REMINDER';
                $emailBody = $r->reminder;
            }

            foreach ($users as $user) {
                if ($user->email !== null) {
                    Mail::raw($emailBody, function ($message) use ($emailSubject, $user) {
                        $message->to($user->email)
                            ->subject($emailSubject);
                    });
                }
            }

            // Update nextout based on frequency
            if ($save->freq == 'Daily') {
                $newnext = Carbon::parse($save->nextout)->addDays(1)->format('d-m-Y');
                $addtime = $newnext . 'T' . $r->timeblastdaily;
                $save->update([
                    'nextout' => Carbon::parse($addtime),
                ]);
            } elseif ($save->freq == 'Weekly') {
                $newnxtday = $now->next($r->weeklydayblast)->format('d-m-Y');
                $addtime = $newnxtday . 'T' . $r->timeblastweeklytime;
                $save->update([
                    'nextout' => Carbon::parse($addtime),
                ]);
            } elseif ($save->freq == 'Monthly') {
                $save->update([
                    'nextout' => Carbon::parse($r->timeblastmonthly)->addMonth(),
                ]);
            } elseif ($save->freq == 'Yearly') {
                $save->update([
                    'nextout' => Carbon::parse($r->timeSblast)->addYear(),
                ]);
            } elseif ($save->freq == 'None') {
                $save->update([
                    'nextout' => null,
                ]);
            }
        } else {
            $group = $r->group;

            if ($group == 'coe') {
                $users = CoiUsers::query()->whereDoesntHave('CoeForm')->get();
                $emailSubject = 'SCANCOM PLC (MTN Ghana) Conflict of Interest Policy & Code of Ethics REMINDER';
                $emailBody = $r->reminder;
            } else {
                $users = CoiUsers::whereNull('coi_status')->orWhere('status', 'Pending')->get();
                $emailSubject = 'SCANCOM PLC (MTN Ghana) Conflict of Interest Policy & Code of Ethics REMINDER';
                $emailBody = $r->reminder;
            }

            foreach ($users as $user) {
                if ($user->email !== null) {
                    Mail::raw($emailBody, function ($message) use ($emailSubject, $user) {
                        $message->to($user->email)
                            ->subject($emailSubject);
                    });
                }
            }
        }

        return back()->with('success', 'Reminder Added and scheduled to go out');
    }



    // public function post(Request $r)
    // {

    //     $now = Carbon::now();

    //     $save = Reminder::updateOrCreate(['id' => 1], [
    //         'reminder' => $r->reminder,
    //         'freq' => $r->freq,
    //         'freq' => $r->group,

    //         'nextout' => $r->freq == 'None' ? null : $now,
    //     ]);

    //     if ($r->freq !== 'None') {
    //         $group = $r->group;

    //         if ($group == 'coe') {
    //             $users = CoiUsers::query()->whereDoesntHave('CoeForm')->get();
    //             $emailSubject = 'MTN CODE OF ETHICS REMINDER';
    //             $emailBody = $r->reminder;
    //         } else {
    //             $users = CoiUsers::whereNull('coi_status')->orWhere('status', 'Pending')->get();
    //             $emailSubject = 'MTN CONFLICT OF INTEREST';
    //             $emailBody = $r->reminder;
    //         }

    //         foreach ($users as $user) {
    //             if ($user->email !== null) {
    //                 $data = [
    //                     'email' => $user,
    //                 ];

    //                 $this->sendmail($emailSubject, $user->email, $emailBody);
    //             }
    //         }

    //         // Update nextout based on frequency
    //         if ($save->freq == 'Daily') {

    //             $newnext =  Carbon::parse($save->nextout)->addDays(1)->format('d-m-Y');
    //             $addtime = $newnext . 'T' . $r->timeblastdaily;

    //             $save->update([
    //                 'nextout' => Carbon::parse($addtime),
    //             ]);
    //         } elseif ($save->freq == 'Weekly') {
    //             $newnxtday =  $now->next($r->weeklydayblast)->format('d-m-Y');
    //             $addtime = $newnxtday . 'T' . $r->timeblastweeklytime;

    //             $save->update([
    //                 'nextout' => Carbon::parse($addtime),
    //             ]);
    //         } elseif ($save->freq == 'Monthly') {

    //             $save->update([
    //                 'nextout' => Carbon::parse($r->timeblastmonthly)->addMonth(),
    //             ]);
    //         } elseif ($save->freq == 'Yearly') {
    //             $save->update([
    //                 'nextout' => Carbon::parse($r->timeSblast)->addYear(),
    //             ]);
    //         } elseif ($save->freq == 'None') {
    //             $save->update([
    //                 'nextout' => null,
    //             ]);
    //         }
    //     } else {
    //         $group = $r->group;

    //         if ($group == 'coe') {
    //             $users = CoiUsers::query()->whereDoesntHave('CoeForm')->get();
    //             $emailSubject = 'MTN CODE OF ETHICS REMINDER';
    //             $emailBody = $r->reminder;
    //         } else {
    //             $users = CoiUsers::whereNull('coi_status')->orWhere('status', 'Pending')->get();
    //             $emailSubject = 'MTN CONFLICT OF INTEREST';
    //             $emailBody = $r->reminder;
    //         }

    //         foreach ($users as $user) {
    //             if ($user->email !== null) {
    //                 $data = [
    //                     'email' => $user,
    //                 ];

    //                 $this->sendmail($emailSubject, $user->email, $emailBody);
    //             }
    //         }
    //     }

    //     return back()->with('success', 'Reminder Added and scheduled to go out');
    // }



    public function postOld(Request $r)
    {
        dd($r->all());
        $now = Carbon::now();

        $save = Reminder::updateOrCreate(['id' => 1], [
            'reminder' => $r->reminder,
            'freq' => $r->freq,
            'nextout' => $r->freq == 'None' ? null : $now,
        ]);

        if ($r->freq !== 'None') {
            $users = CoiUsers::whereNull('coi_status')->orWhere('status', 'Pending')->get();
            foreach ($users as $key) {
                if ($key->email !== null) {
                    $data = [

                        'email' => $users,
                    ];

                    $this->sendmail('SCANCOM PLC (MTN Ghana) Conflict of Interest Policy & Code of Ethics', $key->email, "Y’ello MTNer,\\n Kindly note that you are receiving this message because you either have not started or completed your 2023 Conflict of Interest Declarations. In accordance with the Conflict of Interest Policy, kindly be reminded to complete and submit your declarations via https://mtncoi.com/. \\n\\n\\n NB:  WINDOW HAS BEEN EXTENDED TO FRIDAY 23rd SEPTEMBER, 2023 TO ALLOW YOU COMPLETE AND SUBMIT YOUR COI DECLARATIONS SINCE IT IS A MANDATORY EXERCISE FOR ALL STAFF.\\n\\n\\n For any further assistance, kindly reach out to  conflictofInterest.GH@mtn.com \\n\\nThank you");
                }
                //
            }

            // update nextout
            if ($save->freq == 'Daily') {

                $newnext =  Carbon::parse($save->nextout)->addDays(1)->format('d-m-Y');
                $addtime = $newnext . 'T' . $r->timeblastdaily;

                $save->update([
                    'nextout' => Carbon::parse($addtime),
                ]);
            } elseif ($save->freq == 'Weekly') {
                $newnxtday =  $now->next($r->weeklydayblast)->format('d-m-Y');
                $addtime = $newnxtday . 'T' . $r->timeblastweeklytime;

                $save->update([
                    'nextout' => Carbon::parse($addtime),
                ]);
            } elseif ($save->freq == 'Monthly') {

                $save->update([
                    'nextout' => Carbon::parse($r->timeblastmonthly)->addMonth(),
                ]);
            } elseif ($save->freq == 'Yearly') {
                $save->update([
                    'nextout' => Carbon::parse($r->timeSblast)->addYear(),
                ]);
            } elseif ($save->freq == 'None') {
                $save->update([
                    'nextout' => null,
                ]);
            }
        } else {



            $users = CoiUsers::whereNull('coi_status')->orWhere('status', 'Pending')->get();
            // return $users;
            foreach ($users as $key) {
                if ($key->email !== null) {
                    $data = [
                        // 'name'=>$key->name,
                        // 'reminder'=>$r->reminder,
                        'email' => $users,
                    ];

                    $this->sendmail('SCANCOM PLC (MTN Ghana) Conflict of Interest Policy & Code of Ethics', $key->email, "Y’ello MTNer,\\n Kindly note that you are receiving this message because you either have not started or completed your 2023 Conflict of Interest Declarations. In accordance with the Conflict of Interest Policy, kindly be reminded to complete and submit your declarations via https://mtncoi.com/. \\n\\n\\n NB:  WINDOW HAS BEEN EXTENDED TO FRIDAY 23rd SEPTEMBER, 2023 TO ALLOW YOU COMPLETE AND SUBMIT YOUR COI DECLARATIONS SINCE IT IS A MANDATORY EXERCISE FOR ALL STAFF.\\n\\n\\n For any further assistance, kindly reach out to  conflictofInterest.GH@mtn.com \\n\\nThank you");
                }
                //
            }
        }

        return back()->with('success', 'Reminder Added and scheduled to go out');
    }
}
