<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\AdminRole;
use App\Models\mobilead;
use App\Models\MobileAdsVehicleLicense;
use App\Models\PermitStepMobile;
use App\Models\PermitStepStreetLamp;
use App\Models\StreetLampsAds;
use App\Models\ThirdPartyMobile;
use App\Models\ThirdPartyMobilePermitStep;
use App\Models\User;
use App\Models\UserAdmin;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;


class HODApprovalController extends Controller    {

    public function hodDeclineMobile($mobileId) {

        if(Auth::user()->admin_role_id == 5) {

            $setDeclineAds = mobilead::where('id', $mobileId)->update(['hod_permit_status' => 'declined', 'status' => 'declined', 'final_status' => 'declined']);
            $getSingleMobile = mobilead::where('id', $mobileId)->get();
            $mobileObj = mobilead::find($getSingleMobile[0]['id']);
            $currentStep = AdminRole::where('id', 2)->get();
            $permitStep = new PermitStepMobile();
            $permitStep->purpose = 'New Mobile Ads';
            $permitStep->current_steps = $currentStep[0]['role'];
            $mobileObj->permitStepMobile()->save($permitStep);
            $getApplicant = User::where('id', $getSingleMobile[0]['user_id'])->get();
            $getApplicantEmail = $getApplicant[0]['email'];
            $subject = 'Update on Mobile  Ads Application';
            $body = 'The Mobile ads your applied for was declined.';
            //$this->composeEmail($subject, $body, $getApplicantEmail);
            $templateData = [
                'body' => $body,
                'name' => $getApplicant[0]['business_name'],
            ];
            $templateContent = view('emailtemplate', $templateData)->render();
            $this->composeEmailV2($subject, $getApplicantEmail,  $templateContent);
            $getCreateby = UserAdmin::where('id', (string)$getApplicant[0]['created_by'])->exists();
            if($getCreateby ) {
                $getAdmin = UserAdmin::where('id', (string)$getApplicant[0]['created_by'])->get();
                $getCreatebyEmail = $getAdmin[0]['email'];
                $this->composeEmailV2($subject, $getCreatebyEmail,  $templateContent);
            }
            return response()->json(['data' => $getSingleMobile], 200);
        } else {
            return response()->json(['data' => 'You do not have the priviledge to take this action.'], 422);
        }
    }

    public function hodDeclineThirdPartyMobile($mobileId) {

        if(Auth::user()->admin_role_id == 5) {

            $setDeclineAds = ThirdPartyMobile::where('id', $mobileId)->update(['hod_permit_status' => 'declined', 'status' => 'declined']);
            $getSingleMobile = ThirdPartyMobile::where('id', $mobileId)->get();
            $thirdPartyObj = ThirdPartyMobile::find($getSingleMobile[0]['id']);
            $currentStep = AdminRole::where('id', 2)->get();
            $permitStep = new ThirdPartyMobilePermitStep();
            $permitStep->purpose = 'New Mobile Ads';
            $permitStep->current_steps = $currentStep[0]['role'];
            $thirdPartyObj->thirdPartyMobilePermitStep()->save($permitStep);
            $getApplicant = User::where('id', $getSingleMobile[0]['user_id'])->get();
            $getApplicantEmail = $getApplicant[0]['email'];
            $subject = 'Update on Mobile  Ads Application';
            $body = 'The Third Party  Mobile ads you applied for was declined.';
            //$this->composeEmail($subject, $body, $getApplicantEmail);
            $templateData = [
                'body' => $body,
                'name' => $getApplicant[0]['business_name'],
            ];
            $templateContent = view('emailtemplate', $templateData)->render();
            $this->composeEmailV2($subject, $getApplicantEmail,  $templateContent);
            $getCreateby = UserAdmin::where('id', (string)$getApplicant[0]['created_by'])->exists();
            if($getCreateby ) {
                $getAdmin = UserAdmin::where('id', (string)$getApplicant[0]['created_by'])->get();
                $getCreatebyEmail = $getAdmin[0]['email'];
                $this->composeEmailV2($subject, $getCreatebyEmail,  $templateContent);
            }
            return response()->json(['data' => $getSingleMobile], 200);
        } else {
            return response()->json(['data' => 'You do not have the priviledge to take this action.'], 422);
        }
    }

    public function hodDeclineStreetLamp($streetLampId) {

        if(Auth::user()->admin_role_id == 5) {

            $setDeclineAds = StreetLampsAds::where('id', $streetLampId)->update(['hod_permit_status' => 'declined', 'status' => 'declined']);
            $getSingleStreetLamps = StreetLampsAds::where('id', $streetLampId)->get();
            $StreetLampObj = StreetLampsAds::find($getSingleStreetLamps[0]['id']);
            $currentStep = AdminRole::where('id', 2)->get();
            //var_dump($currentStep[0]['role']); die();
            $permitStep = new PermitStepStreetLamp();
            $permitStep->purpose = 'New Mobile Ads';
            $permitStep->current_steps = $currentStep[0]['role'];
            $StreetLampObj->permitStepStreetLamp()->save($permitStep);
            $getApplicant = User::where('id', $getSingleStreetLamps[0]['user_id'])->get();
            $getApplicantEmail = $getApplicant[0]['email'];
            $subject = 'Update on Street Lamp Ads Application';
            $body = 'Your Street Lamps Ads has been declined';

            $templateData = [
                'body' => $body,
                'name' => $getApplicant[0]['business_name'],

            ];
            $templateContent = view('emailtemplate', $templateData)->render();
            $this->composeEmailV2($subject, $getApplicantEmail,  $templateContent);
            $getCreateby = UserAdmin::where('id', (string)$getApplicant[0]['created_by'])->exists();
            if($getCreateby ) {
                $getAdmin = UserAdmin::where('id', (string)$getApplicant[0]['created_by'])->get();
                $getCreatebyEmail = $getAdmin[0]['email'];
                $this->composeEmailV2($subject, $getCreatebyEmail,  $templateContent);
            }
            return response()->json(['data' => $getSingleStreetLamps], 200);
        } else {
            return response()->json(['data' => 'You do not have the priviledge to take this action.'], 422);
        }
    }

    public function hodApprovalMobile($mobileId) {

        if(Auth::user()->admin_role_id == 5) {
            $setApprovalAds = mobilead::where('id', $mobileId)->update(['hod_permit_status' => 'approved','status' => 'approved']);
            $getSingleMobile = mobilead::where('id', $mobileId)->get();
            $mobileObj = mobilead::find($getSingleMobile[0]['id']);
            $currentStep = AdminRole::where('id', 6)->get();
            $permitStep = new PermitStepMobile();
            $permitStep->purpose = 'New Mobile Ads';
            $permitStep->current_steps = $currentStep[0]['role'];
            $mobileObj->permitStepMobile()->save($permitStep);
            //$this->sendDetailsforQrcode($mobileId);
            $getApplicant = User::where('id', $getSingleMobile[0]['user_id'])->get();
            $getApplicantEmail = $getApplicant[0]['email'];
            $subject = 'Update on Mobile  Ads Application';
            $body = 'The Mobile ads your applied for was approved, you can proceed to make payment.';
            //$this->composeEmail($subject, $body, $getApplicantEmail);
            $templateData = [
                'body' => $body,
                'name' => $getApplicant[0]['business_name'],
            ];
            $templateContent = view('emailtemplate', $templateData)->render();
            $this->composeEmailV2($subject, $getApplicantEmail,  $templateContent);
            $getCreateby = UserAdmin::where('id', (string)$getApplicant[0]['created_by'])->exists();
            if($getCreateby ) {
                $getAdmin = UserAdmin::where('id', (string)$getApplicant[0]['created_by'])->get();
                $getCreatebyEmail = $getAdmin[0]['email'];
                $this->composeEmailV2($subject, $getCreatebyEmail,  $templateContent);
            }

            return response()->json(['data' => $getSingleMobile], 200);
        } else {
            return response()->json(['data' => 'You do not have the priviledge to take this action.'], 422);
        }
    }

    public function hodApprovalThirdPartyMobile($mobileId) {
        if(Auth::user()->admin_role_id == 5) {
            $setApprovalAds = ThirdPartyMobile::where('id', $mobileId)->update(['hod_permit_status' => 'approved', 'status' => 'approved']);
            $getSingleMobile = ThirdPartyMobile::where('id', $mobileId)->get();
            $thirdPartyObj = ThirdPartyMobile::find($getSingleMobile[0]['id']);
            $currentStep = AdminRole::where('id', 6)->get();
            $permitStep = new ThirdPartyMobilePermitStep();
            $permitStep->purpose = 'New Mobile Ads';
            $permitStep->current_steps = $currentStep[0]['role'];
            $thirdPartyObj->thirdPartyMobilePermitStep()->save($permitStep);
            $getApplicant = User::where('id', $getSingleMobile[0]['user_id'])->get();
            $getApplicantEmail = $getApplicant[0]['email'];
            $subject = 'Update on Third party mobile  Ads Application';
            $body = 'The Mobile ads your applied for was approved.' ;
            //$this->composeEmail($subject, $body, $getApplicantEmail);
            $templateData = [
                'body' => $body,
                'name' => $getApplicant[0]['business_name'],
            ];
            $templateContent = view('emailtemplate', $templateData)->render();
            $this->composeEmailV2($subject, $getApplicantEmail,  $templateContent);
            $getCreateby = UserAdmin::where('id', (string)$getApplicant[0]['created_by'])->exists();
            if($getCreateby ) {
                $getAdmin = UserAdmin::where('id', (string)$getApplicant[0]['created_by'])->get();
                $getCreatebyEmail = $getAdmin[0]['email'];
                $this->composeEmailV2($subject, $getCreatebyEmail,  $templateContent);
            }
            return response()->json(['data' => $getSingleMobile], 200);
        } else {
            return response()->json(['data' => 'You do not have the priviledge to take this action.'], 422);
        }
    }

    public function hodApprovalStreetLamp($streetLampId) {
        if(Auth::user()->admin_role_id == 5) {
            $setApprovalStreetLamp = StreetLampsAds::where('id', $streetLampId)->update(['hod_permit_status' => 'approved',
                'status' => 'approved', 'date_hod_approval' => Carbon::now()]);
            $getSingleStreetLamps = StreetLampsAds::where('id', $streetLampId)->get();
            $StreetLampObj = StreetLampsAds::find($getSingleStreetLamps[0]['id']);
            // var_dump($getSingleStreetLamps[0]['id']); die();
            $currentStep = AdminRole::where('id', 6)->get();
            // var_dump($currentStep[0]['role']); die();
            $permitStep = new PermitStepStreetLamp();
            $permitStep->purpose = 'New Mobile Ads';
            $permitStep->current_steps = $currentStep[0]['role'];
            $StreetLampObj->permitStepStreetLamp()->save($permitStep);
            $getApplicant = User::where('id', $getSingleStreetLamps[0]['user_id'])->get();
            // var_dump($getApplicant); die();
            $getApplicantEmail = $getApplicant[0]['email'];
            $subject = 'Update on Street Lamps  Ads Application';
            $body = 'The Street Lamps you applied for has been approved, you can proceed to make payment';
            //$this->composeEmail($subject, $body, $getApplicantEmail);
            $templateData = [
                'body' => $body,
                'name' => $getApplicant[0]['business_name'],
            ];
            $templateContent = view('emailtemplate', $templateData)->render();
            $this->composeEmailV2($subject, $getApplicantEmail,  $templateContent);
            $getCreateby = UserAdmin::where('id', (string)$getApplicant[0]['created_by'])->exists();
            if($getCreateby ) {
                $getAdmin = UserAdmin::where('id', (string)$getApplicant[0]['created_by'])->get();
                $getCreatebyEmail = $getAdmin[0]['email'];
                $this->composeEmailV2($subject, $getCreatebyEmail,  $templateContent);
            }
            return response()->json(['data' => $getSingleStreetLamps], 200);
        } else {
            return response()->json(['data' => 'You do not have the priviledge to take this action.'], 422);
        }
    }

    private function sendDetailsforQrcode($id) {

        $url = getenv('QRcode_URL');

        $headers = [
            'Authorization' => 'Bearer ' . getenv('QRcode_BEARER_TEST'),
            'Accept' => 'application/json',
            'Content-Type' => 'application/json'
        ];

        $getMobileDetails = mobilead::where('id', $id)->get();
        $getUserInfo = User::where('id', $getMobileDetails[0]['user_id'])->get();
        $getMobileLicense = MobileAdsVehicleLicense::where('mobilead_id', $id)->get();
        $count = count($getMobileLicense) - 1;
        $currentYear = date('Y');

        $data = [];

        for ($i=0; $i<= $count; $i++) {
            $postData = [
                'email' => $getUserInfo[0]['email'],
                'phone' => $getUserInfo[0]['phone_number'],
                'businessName' => $getUserInfo[0]['business_name'],
                'brandingType' => $getMobileLicense[$i]['branding_details'],
                'vehicleType' => $getMobileLicense[$i]['vehicle_type'],
                'permitYear' => $currentYear,
                'plateNumber' => $getMobileLicense[$i]['vehicle_license'],
                'branding_id' => $id
            ];
            $data [] = $postData;
        }

        $response = Http::withHeaders($headers)->post($url, $data);
        if($response->successful()) {
            $responseData = $response->json();

        } else {
            $responseData = "Unable to send data";
        }
        Log::info( response()->json(['data' => $responseData], $response->status()));
    }

    protected function domainExists($email)
    {
        // Extract the domain from the email address
        $parts = explode('@', $email);
        $domain = array_pop($parts);

        // Perform a DNS lookup for the domain
        $mxRecords = [];
        if (checkdnsrr($domain, 'MX')) {
            // MX records found, domain exists
            return true;
        } else {
            // No MX records found, domain does not exist
            return false;
        }
    }

    public function composeEmailV2($subject, $userEmail, $emailContent) {

        if($this->domainExists($userEmail)) {
            Log::info("Domain Exists");
        } else {
            Log::error("Domain does not exist");
        }

        require base_path('vendor/autoload.php');

        try {
            $mail = new PHPMailer(true);
            $mail->SMTPDebug = 0;
            $mail->isSMTP();
            $mail->Host = 'smtp-relay.brevo.com'; //ssl://smtp.gmail.com
            $mail->SMTPAuth = true;
            $mail->Username = 'macdonnad@gmail.com';
            $mail->Password = 'xsmtpsib-93267ec9551960673300f309d7edd9a807648eb7aac5b10b6f80f2e106c7f010-dMSfPhNXDW84pqvY';
            // $mail->SMTPSecure = 'ssl';
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port = 587;
            $mail->setFrom('noreply@lasaa.lg.gov.ng', 'Lasaa');
            $mail->addAddress($userEmail);
            $mail->addReplyTo('noreply@lasaa.lg.gov.ng', 'Lasaa');

            $mail->isHTML(true);
            Log::info($userEmail);
            $mail->Subject = $subject;
            $mail->Body = $emailContent;
            $mail->send();
            Log::info("message sent");
        } catch (Exception $exception) {
//            error_log('Email delivery failed: ' . $mail->ErrorInfo);
            $message = $exception->getMessage();
            Log::error($message);
            return true;
        }
    }
}
