<?php

namespace App\Http\Controllers;

use App\HelpDesk;
use App\PreLoginHelpDesk;
use Mail;
use App\DataTables\AdminHelpDesk;
use App\DataTables\AccessRequest;
use App\CoiUsers;
use Illuminate\Support\Facades\Session;
use App\AuditTrail;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Jobs\AccessRequestResponseNotification;
use App\Jobs\HelpDeskNoticeMail;
use App\Jobs\HelpDeskReponse;
use App\Jobs\SendAdminHelpRequest;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

class HelpdeskController extends Controller
{


    public function sendmail($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()
    {
        $sessionUser = session()->get('user');
        $userid = $sessionUser['userid'];


        $helpdesk = HelpDesk::where('userid', $userid)->get();
        return view('helpdesk.index', compact('helpdesk', 'userid'));
    }

    public function posthelp(Request $r)
    {
        $sessionUser = session()->get('user');
        $userid = $sessionUser['userid'];
        $user = CoiUsers::where('id', $userid)->first();
        $checkifexists = HelpDesk::where('userid', $userid)->first();

        if ($checkifexists == null) {
            $random = Str::random(4) . '_' . $user->name;
            HelpDesk::create([
                'userid' => $userid,
                'name' => $user->name,
                'comment' => $r->enquiry,
                'response' => $random,
            ]);

            $data = [
                'name' => $user->name,
                'email' => $user->email,
                'dept' => $user->dept,
                'division' => $user->division,
                'helpid' => $random
            ];

            $this->sendmail('SCANCOM PLC (MTN Ghana) Conflict of Interest Policy & Code of Ethics', $user->email, "Hello " . $user->name . ",\\n Your enquiry request has been received and the Administrator would respond to you shortly.\\n Help Desk id: " . $random . "\\n\\n Best Regards,\\n MTN CoI-CoE 2023");

            $adminmail = env('AdminEmail');
            $this->sendmail('SCANCOM PLC (MTN Ghana) Conflict of Interest Policy & Code of Ethics', $adminmail, "Hello Admin,\\n " . $user->name . " from " . $user->dept . "  department and " . $user->division . " division  is requesting for assistance in completing their COI.\\n Kindly visit the Help Desk section at the Administrative Portal to assist " . $user->name . " \\n with the appropriate assistance needed. \\n Help Desk id: " . $random . "\\n\\n Best Regards,\\n MTN CoI-CoE " . Carbon::now()->year);

            // SendAdminHelpRequest::dispatch($data);
            // HelpDeskNoticeMail::dispatch($data);

        } else {
            HelpDesk::create([
                'userid' => $userid,
                'name' => $user->name,
                'comment' => $r->enquiry,
                'response' => $checkifexists->response,
            ]);
            $data = [
                'name' => $user->name,
                'email' => $user->email,
                'dept' => $user->dept,
                'division' => $user->division,
                'helpid' => $checkifexists->response
            ];


            $this->sendmail('SCANCOM PLC (MTN Ghana) Conflict of Interest Policy & Code of Ethics', $user->email, "Hello " . $user->name . ",\\n Your enquiry request has been received and the Administrator would respond to you shortly.\\n Help Desk id: " . $checkifexists->response . "\\n\\n Best Regards,\\n MTN CoI-CoE " . Carbon::now()->year);

            $adminmail = env('AdminEmail');
            $this->sendmail('SCANCOM PLC (MTN Ghana) Conflict of Interest Policy & Code of Ethics', $adminmail, "Hello Admin,\\n " . $user->name . " from " . $user->dept . " department and " . $user->division . " division  is requesting for assistance in gaining access to their MTN COI Account with their credentials.\\n Kindly visit the Help Desk section at the Administrative Portal to assist " . $user->name . " \\n with the appropriate assistance needed. \\n Help Desk id: " . $checkifexists->response . "\\n\\n Best Regards,\\n MTN CoI-CoE " . Carbon::now()->year);

            // SendAdminHelpRequest::dispatch($data);
            // HelpDeskNoticeMail::dispatch($data);
        }

        return redirect()->route('coi.help')->with('success', 'Enquiry Submitted!');
    }


    public function checkmess($id, $count)
    {

        $check = HelpDesk::where('userid', $id)->count();
        if ($check == $count) {
            // nothing happens
        } else {
            $response = HelpDesk::where('userid', $id)->orderBy('id', 'desc')->whereNotNull('adminid')->first();
            if ($response !== null) {
                return response()->json([
                    'response' => $response,
                    'newcount' => $check
                ]);
            }
            // else do nothing
        }
    }


    public function adminindex(AdminHelpDesk $dt)
    {
        AuditTrail::create([
            'userid' => auth()->guard('adminguard')->user()->id,
            'name' => auth()->guard('adminguard')->user()->name,
            'activity' => 'View: Is viewing HelpDesk page',
            // 'message',
        ]);
        return $dt->render('admin.helpdesk.index');
    }


    public function adminviewhelp($id)
    {
        $help = HelpDesk::where('userid', $id)->get();
        $namee = HelpDesk::where('userid', $id)->first();
        $name = $namee->name;
        $helpid = $namee->response;

        AuditTrail::create([
            'userid' => auth()->guard('adminguard')->user()->id,
            'name' => auth()->guard('adminguard')->user()->name,
            'activity' => 'View: Is viewing Help request sent by ' . $namee->name,
            // 'message',
        ]);
        return view('admin.helpdesk.view', compact('help', 'name', 'id', 'helpid'));
    }

    public function adminresponse(Request $r, $helpid, CoiUsers $id)
    {
        // return 'lol';
        $admin = Session::get('adminid');
        HelpDesk::create([
            'userid' => $id->id,
            // 'name'=>$id->name,
            'comment' => $r->enquiry,
            'response' => $helpid,
            'adminid' => $admin,
        ]);





        HelpDesk::where('response', $helpid)->whereNull('adminid')->update([
            'adminid' => $admin,
        ]);

        $data = [
            'name' => $id->name,
            'comment' => $r->enquiry,
            'response' => $helpid,
            'email' => $id->email,
        ];
        //
        $this->sendmail('SCANCOM PLC (MTN Ghana) Conflict of Interest Policy & Code of Ethics', $id->email, "Hello " . $id->name . ",\\n This mail is in reponse to your Help Desk Request.\\n Kindly find below the response from the Team: \\n Help Desk id: " . $helpid . "\\n Response: " . $r->enquiry . "\\n\\n Best Regards,\\n MTN CoI-CoE " . Carbon::now()->year);


        // HelpDeskReponse::dispatch($data);

        AuditTrail::create([
            'userid' => auth()->guard('adminguard')->user()->id,
            'name' => auth()->guard('adminguard')->user()->name,
            'activity' => 'HelpDesk Response: Responded to ' . $id->name . ' help request',
            // 'message',
        ]);
        // return 'lll';
        return back()->with('success', 'Response Submitted!');
    }


    // //////////////access requests

    public function accessrequestindex(AccessRequest $dt)
    {
        AuditTrail::create([
            'userid' => auth()->guard('adminguard')->user()->id,
            'name' => auth()->guard('adminguard')->user()->name,
            'activity' => 'View: Is viewing Access requests page',
            // 'message',
        ]);
        return $dt->render('admin.helpdesk.accessindex');
    }

    public function postaccess(PreLoginHelpDesk $id, Request $r)
    {
        // return $id;

        $id->update([
            'response' => $r->response,
            'adminname' => auth()->guard('adminguard')->user()->name,
        ]);

        $data = [
            'email' => $id->email,
            'name' => $id->name,
            'response' => $r->response,
            'helpid' => $id->helpid,
            'comment' => $id->comment,
        ];
        $this->sendmail('SCANCOM PLC (MTN Ghana) Conflict of Interest Policy & Code of Ethics', $id->email, "Hello " . $id->name . ",\\n Kindly find below the response from the MTN COI Administrator in response to your request: \\n Help Desk id: " . $id->helpid . "\\n Request: " . $id->comment . "\\n Response: " . $r->response . "\\n\\n Best Regards,\\n MTN CoI-CoE" . Carbon::now()->year);


        // AccessRequestResponseNotification::dispatch($data);
        AuditTrail::create([
            'userid' => auth()->guard('adminguard')->user()->id,
            'name' => auth()->guard('adminguard')->user()->name,
            'activity' => 'Access Request Response: Access request from ' . $id->name . ' response sent',
            // 'message',
        ]);
        return back()->with('success', 'Response submitted');
    }
}
