<?php

require_once('../../wp-blog-header.php');


//call the autoload

require 'vendor/autoload.php';
//load phpspreadsheet class using namespaces
use PhpOffice\PhpSpreadsheet\Spreadsheet;
//call iofactory instead of xlsx writer
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Fill;

// get report data--------------------------------------------
    
    global $wpdb;
    $originalData = [];
    $inclusiveProducts = array( 'BANKPASS',
                                'CBS / EXPLORE',
                                'CODEBREAKER $49',
                                'CODEBREAKER AI + BANKPASS + BCRM',
                                'CODEBREAKER AI + BANKPASS + BCRM 30 DAY $1 TRIAL',
                                'CODEBREAKER AI + BANKPASS TRIAL',
                                'CODEBREAKER AI 7-DAY TRIAL',
                                'CODEBREAKER BANKPASS $29',
                                'CODEBREAKER BUNDLE',
                                'CODEBREAKER DISCOVER',
                                'CODEBREAKER DISCOVER - DISABLE',
                                'CODEBREAKER DISCOVER 29 - DISABLE',
                                'CODEBREAKER DISCOVER 49 - DISABLE',
                                'CODEBREAKER DISCOVER TRIAL',
                                'CODEBREAKER EXPLORE',
                                'CODEBREAKER EXPLORE W/ COACHING',
                                'CODEBREAKER SUMMIT',
                                'CODEBREAKER SUMMIT - SPECIAL OFFER',
                                'CODEBREAKER AI + BCRM 30 DAY TRIAL, BANK VAULT PLATINUM ACCESS',
                                'CODEBREAKER AI + BCRM 30 DAY TRIAL, BANK VAULT PLATINUM ACCESS, CODEBREAKER SUMMIT',
                                'CODEBREAKER AI 7-DAY TRIAL, CODEBREAKER AI + BANKPASS + BCRM',
                                'TOPSUMMIT | LEVEL 1 | BANK VAULT PLATINUM ACCESS',
                                'TOPSUMMIT | LEVEL 1 | BANK VAULT PLATINUM ACCESS, CODEBREAKER AI + BCRM 30 DAY TRIAL',
                                'TOPSUMMIT | LEVEL 1 | CODEBREAKER AI + BANKPASS + BCRM',
                                'TOPSUMMIT | LEVEL 1 | CODEBREAKER AI + BCRM 30 DAY TRIAL, BANK VAULT PLATINUM ACCESS',
                                'TOPSUMMIT | LEVEL 1 | CODEBREAKER AI + BCRM 30 DAY TRIAL, BANK VAULT PLATINUM ACCESS, CODEBREAKER SUMMIT',
                                'TOPSUMMIT | LEVEL 1 | CODEBREAKER AI 7-DAY TRIAL, CODEBREAKER AI + BANKPASS + BCRM',
                                'WHY THEY BUY - DIGITAL EBOOK',
                                'CODEBREAKER AI + BANKPASS TRIAL',
                                'CODEBREAKER COACH w/ EXPLORE SUBSCRIPTION',
                                'CODEBREAKER DISCOVER (special offer link)',
                                'CODEBREAKER BANKPASS $29',
                                'CODEBREAKER $49',
                                'CODEBREAKER DISCOVER 49 – Disable',
                                'CODEBREAKER DISCOVER 29 – Disable',
                                'CODEBREAKER COACHING w/ EXPLORE SUBSCRIPTION',
                                'CODEBREAKER CONNECT $29');
                                
        // Other than stephanie@empoweryourvoice.com which we will exclude for now, these are the list of emails for which we'll calculate 40%
        $fortyPercentUsers = array('bank@bankcode.com',
'jbatc@comcast.net',
'abundanceonpurpose@gmail.com',
'wellnesswithabc@gmail.com',
'ambassadoranasuya@gmail.com',
'angie@angiegraywellness.com',
'anne@teamjordan.ca',
'arlenekrantz@gmail.com',
'bfarmer@me.com',
'brenda@brendawise.com',
'brigitta@hoeferle.com',
'bryanmurphy6@hotmail.com',
'anubus63@gmail.com',
'carollstanley24@gmail.com',
'globalstar99@gmail.com',
'carolynnutrition@mac.com',
'cchatelain@usa.net',
'azwellnesscoach@gmail.com',
'chanin@firstwashingtonmortgage.com',
'chris@contagiousenthusiasm.com',
'christine@bcgtmanagement.com',
'cindygauri@comcast.net',
'irishsunshine60@gmail.com',
'dharami@gmail.com',
'dkpriddy@gmail.com',
'david@theadlardgroup.com',
'bankdig@gmail.com',
'diana@dianadeene.com',
'excelerate.us@gmail.com',
'bank@businesssuccesstoday.com',
'dwaynerichards72@gmail.com',
'emmie.bankcode@gmail.com',
'eric@meridiansuccessgroup.com',
'fernando.espinosa@energiza.biz',
'gohchongtong@yahoo.com.sg',
'farrantgarth@gmail.com',
'info@taxproplan.com',
'jwong139@gmail.com',
'rjp.bos@gmail.com',
'jackieulmer@gmail.com',
'jamesleong@visions1.com.sg',
'briarhillgroup@gmail.com',
'jane@trainerjane.ca',
'jshteam1@gmail.com',
'jeannezierhoffer@gmail.com',
'jen@thedrapergroup.org',
'bankonjenny@gmail.com',
'jevine@startgrowachieve.com',
'taybri7@aol.com',
'jory@joryfisher.com',
'languageofsales@gmail.com',
'julieweiss@hotmail.com',
'codeme@shapeshiftworld.com',
'colmantkathleen@gmail.com',
'bagladykellyann@gmail.com',
'kerry@theaudiencewhisperer.com',
'kimcobbme@gmail.com',
'lakhunt@gmail.com',
'laura.y.armstrong@gmail.com',
'laura.decesaris23@gmail.com',
'leonkoenck@hotmail.com',
'mastertrainer@bankonlong.com',
'luanne@ycpcoach.com',
'lyndamolaison@gmail.com',
'ttycoaching@gmail.com',
'bank1l1w@gmail.com',
'marias247store@me.com',
'marie@drmariebenoit.com',
'trainermarty@gmail.com',
'yang.martina1234@gmail.com',
'mayra@theleaptotransformation.com',
'mb@elevatingperformance.com',
'michelle@heysmartypants.com',
'minhd.hado@gmail.com',
'nickm@safetyblade.com',
'youdecidetomorrow@gmail.com',
'pam.kranhold@yahoo.com',
'yearroundsuccess@gmail.com',
'raqueltillman@gmail.com',
'rwacura@gmail.com',
'bobbymartin1947@gmail.com',
'admin@regiuminternational.com',
'info@keystonegroupintl.com',
'sandy@sandyhayakawa.com',
'sanguan.w@uspthailand.com',
'crackthecode.sarahandsharon@gmail.com',
'sarahjstevens@hotmail.com',
'sarah@knowtheirwhy.com',
'aaehomesolutions@gmail.com',
's@segmet.net',
'drshawnrad@gmail.com',
'shelly@veranceconsulting.com',
'stephanie@empoweryourvoice.com',
'suemandell@wetip.com',
'1blssdgrl@gmail.com',
'skydallas@netzero.net',
'srupp5434@gmail.com',
'info@time4changehi.com',
'tryan@ryanhillgroup.com',
'tpabraham12@gmail.com',
'traciehasse@me.com',
'valerie@valeriepjohnson.com',
'wendy@wendydarling.com',
'y.reyes098@gmail.com',
'yvette@thecodemasters.net',
'yearroundsuccess@gmail.com',
'admin@regiuminternational.com',
'robert74bloom@gmail.com',
'jpmomonamission@gmail.com',
'goxponential@gmail.com',
'josselin.h@naturalpropertysolutions.com',
'info@dwaynerichards.com',
'aflaclong@gmail.com',
'marenmalcodebreakers@gmail.com',
'info@hiromiscpa.com',
'jendraper2011@gmail.com',
'sandy.hayakawa@gmail.com',
'tu.bankcode@gmail.com',
'gopro.businesssuccess@gmail.com',
'meridact@yahoo.com');

$emails20 =  array('amayea.maat@cox.net',
'amy@upurnet.com',
'angiecrossdc@yahoo.com',
'aoifejaneroche@gmail.com',
'arleta@arletadaniels.com',
'caralewisdavid@gmail.com',
'chadbecker89@gmail.com',
'christiana@claritymapping.com',
'cmckay@vennnegotiation.com',
'daniel.r.faust@gmail.com',
'info@darlenesmith.ca',
'dbrooksh17@gmail.com',
'david@onthehorizonhomes.com',
'dawnholly.bank@gmail.com',
'deborah@charteraccounting.com',
'kenneth@esorthodontics.com',
'duodragonsservices@gmail.com',
'info@ssdamerica.com',
'glennandrew@outlook.com',
'gregbdavis53@gmail.com',
'jeang25@outlook.com',
'jeangrissim@gmail.com',
'jeanniemarie1375@gmail.com',
'robbinsbankcode@gmail.com',
'karen@bankonblack.com',
'karie.codebreaker@gmail.com',
'royalmoodkat@gmail.com',
'kbranch@letip.com',
'lisaann1005@gmail.com',
'majoradvancements@gmail.com',
'mari@maryme.se',
'nannuessle@gmail.com',
'muittin.r@gmail.com',
'desertdreamscoach@gmail.com',
'mycode@emfluent.com',
'sangeeta.patil@reignsearch.com',
'smithgardner83@gmail.com',
'collaborate@curiohaus.com',
'stephnevada@yahoo.com',
'tjohnston308@yahoo.com',
'vficheux@netvigator.com',
'vivlou@comcast.net',
'barbara@movingonmovement.com',
'marieangelalee@gmail.com',
'coach@4color.cards',
'colleen@connectdevelopsucceed.com',
'take@therightdecision.co',
'ecvass@gmail.com',
'iveshuang@gmail.com',
'armstrongjamesr@gmail.com',
'jencampbell.coach@gmail.com',
'jessica@jessicalkoch.com',
'jawarder@gmail.com',
'1wld1lang@gmail.com',
'info@irysassistant.com',
'julierichard337@yahoo.com',
'katdbarton@gmail.com',
'kskgconsulting@gmail.com',
'ashawiser@hotmail.com',
'melissa.limitlesspossibilities@gmail.com',
'galeano5@outlook.com',
'micca.bbm@gmail.com',
'nasira.jamal@gmail.com',
'pacifico.soldati@gmail.com',
'peg@duchessllc.com',
'riverlightwalker@gmail.com',
'transcendentchiropractic@gmail.com',
'sgonzalez825@outlook.com',
'sharon@sharonblossom.com',
'tamirussaz1@gmail.com',
'tinaboylewhyte@gmail.com',
'yvonne@wordswomenandwisdom.com',
'blessongerentsolutions@gmail.com',
'd.loew@imarketing24.com',
'cameliafawzy@gmail.com',
'briana@emergingmoda.com',
'jonathan@jfcoach.com',
'simon.coulson@gmail.com',
'abruensells4u@gmail.com',
'knowbetterdobetter.jp@gmail.com',
'jared@assessments247.com',
'michaeldgoodman@gmail.com',
'nicolejo5150@verizon.net',
'jeannine222@gmail.com',
'dianne@sandbrookgroup.com',
'joe@sanjoseandbeyond.com',
'tonyvmiller@gmail.com',
'beesonjana@gmail.com',
'juliemango@talkwithmepod.com',
'gene.shull@gmail.com',
'so@performancepartners.us',
'cece@cececonverse.com',
'del@delsutton.com',
'robert@brillmedia.co',
'john@tgrmastermind.com',
'jessls723@gmail.com',
'robert.abraham@cryonextintegrative.com',
'joycreations4you@gmail.com',
'linda@lpcandassociates.com',
'rebeccagracearce@gmail.com',
'courtney@otbtax.com',
'ndelavega@ymail.com',
'kmokhbery@gmail.com',
'alicia.mesa@me.com',
'clubkidsyoga@gmail.com',
'mfports@gmail.com',
'greenstar1964@gmail.com',
'steve@rmarketingdept.com',
'mmkogler@gmail.com',
'graemegish@hotmail.com',
'kay@sweetlifewellness.com',
'jdmasero@gmail.com',
'jay@mentoru.ca',
'madhubaker@gmail.com',
'phaitoon@global-success-alliance.com',
'abraham@viptransformationblueprint.com',
'clubkucera@gmail.com',
'kimshock44@gmail.com',
'robin@robinneal.com',
'10000swordscoaching@gmail.com',
'jonade@allenprinting.com',
'scott@mindspout.com',
'888vern@gmail.com',
'dlshanks13@gmail.com',
'mssistrunk@icloud.com',
'fsibankit@gmail.com',
'ac@andrealnetworks.com',
'denken.tan85@gmail.com',
'thegoaldiggergirl@gmail.com',
'achievewithdorothy@gmail.com',
'vazhocar@gmail.com',
'enchantedseomarketing@gmail.com',
'dianne@dianneyoung.com',
'kearle291@gmail.com',
'maggasiggajons@gmail.com',
'destinylp84@gmail.com',
'maureen.hylton@gmail.com',
'josephine.marcellin@gmail.com',
'drjayster@gmail.com',
'sbarber@supportingstrategies.com',
'manmeet.dhamoon@gmail.com.com',
'juliatakescharge@gmail.com',
'joygenea@joygenea.com',
'tquist1550@hotmail.com',
'charlimace@att.net',
'bob.kelner@theknewview.com',
'caroline@smittencosmetics.com.au',
'dawn@mooreandbetterhealth.com',
'pschandle@gmail.com',
'drmaass@motuschiro.com',
'juliewieler@hotmail.ca',
'trand9239@gmail.com',
'hello@dishevents.ca',
'clarkc@me.com',
'linda@jp4wellbeing.com',
'kaitlinmgoodrich@gmail.com',
'paygeinc1@gmail.com',
'babertsch13@gmail.com',
'beth.huckabee@yahoo.com',
'contact@evelynhuynhfitness.com',
'booking@akanundrum.com',
'rknecht@universalaccounting.com',
'bank@theshulergroupllc.com',
'sd4realty@gmail.com',
'christina@reimaginepossibilities.com',
'360mconsulting@gmail.com',
'barb.adams@ecinsight.com',
'karena@behindyourcurtain.com',
'georgealmaraz@gmail.com',
'denies.cassandra@gmail.com',
'samdias.services@gmail.com',
'joe@redsapiens.com',
'paglinawan@gmail.com',
'noncom144@aol.com',
'mary.finlayson97@gmail.com',
'heidi@upwordsinc.com',
'maya@loyaltybrands.com',
'thinchelwood@gmail.com',
'alvindarien2@gmail.com',
'my_online_accts@yahoo.com',
'angelamillerbankcode@gmail.com',
'desiree.vignon@gmail.com',
'rebecca@ahd247.com',
'paw@youwillchangetheworld.com',
'coachamy@heartmindconnection.com',
'michele@lovetohelpothers.com',
'jodiebert@cox.net',
'dcerbone@msn.com',
'bnovoeebw@gmail.com',
'ahsjc@aol.com',
'info@glowbodysculpting.com',
'skipdonnelly@cox.net',
'realestatetlc@gmail.com',
'melinda.gipson@gmail.com',
'gerycraig@gmail.com',
'dvvalliancebl@gmail.com',
'lovinia.mak@gmail.com',
'dannyclarkecoaching@gmail.com',
'renewyouhealth.wellness@gmail.com',
'marinaaris@icloud.com',
'cspade1@yahoo.com',
'enjoyyourdestiny2@gmail.com',
'brigittelessarddeyell@gmail.com',
'osborne0170@gmail.com',
'andrew@pcgmail.com',
'christianrb96@gmail.com',
'marcodreamz@gmail.com',
'lee.blurredconceptsaustralia@gmail.com',
'roguespirit@protonmail.com',
'basia.ruta@onpointrc.ca',
'anna@annaforsberg.se',
'tom@tomfredella.com',
'mkeeter@codebreakertech.com',
'fitnesstransformationacademy@gmail.com',
'fijiprincess0430@gmail.com',
'celena8cares@gmail.com',
'annmarieclements@gmail.com',
'sexton.jerry@gmail.com',
'oneworldbanknation@gmail.com',
'multiole@yahoo.com',
'lancewalker@fitnesstogether.com',
'rhonda@rhondapeoples.com',
'sonia.luna@avivaspectrum.com',
'claudio@letscreatewealth.ca',
'agatiy@aol.com',
'mike@drivetrafficmedia.com',
'yanee.xy@gmail.com',
'fiona@calibremedical.com.au',
'hms139@sky.com',
'jessica77green@gmail.com',
'jessica77green@gmail.com',
'sgonzalez825@outlook.com',
'whitemudllc@gmail.com',
'eric@ericlofholm.com',
'lofholm@ericlofholm.com',
'mj@jpar.net');


    $roundValues  = array( "29.00",
                            "49.00" ,
                            "59.00" , 
                            "99.00" , 
                            "999.00",
                            "1499.00" , 
                            "1599.00" , 
                            "1999.00" , 
                            "2999.00" , 
                            "4999.00");
    //  $endDate = strtotime("-10 day");
    //  $curDateTime = date("Y-m-d h:m:s");
    
    if(isset($_GET['startDate']) && isset($_GET['endDate'])) {
        
        $startDate = $_GET['startDate'];
        $startDateName = $_GET['startDate'];
        $startDate = strtotime($startDate);
        $startDate = date('Y-m-d h:i:s', $startDate);
        // $today = date('Y-m-d h:i:sa');
      $startDate = date('Y-m-d h:i:s', strtotime($startDate . ' +7 hours'));
       
        $endDate = $_GET['endDate'];
        $endDateName = $_GET['endDate'];
        $endDate = strtotime($endDate);
        $endDate = date('Y-m-d h:i:s', $endDate);
        // $today = date('Y-m-d h:i:sa');
        $endDate = date('Y-m-d h:i:s', strtotime($endDate . ' +31 hours'));
        
        
        
    } else {
        
         $endDateTime = strtotime("-3 day");
         $endDateTimeFormat = 'Y-m-d 00:00:00';
         $endDate = date($endDateTimeFormat, $endDateTime); 
         $startDateTime = strtotime("-9 day");
         $startDateTimeFormat = 'Y-m-d 00:00:00';
         $startDate = date($startDateTimeFormat, $startDateTime);                            
        
    }
     
    
    $results = $wpdb->get_results( "SELECT *,wp_affiliate_wp_referrals.referral_id AS resellerReferralId , wp_affiliate_wp_referrals.affiliate_id AS resellerAffiliateId, (SELECT wp_affiliate_wp_customers.user_id FROM wp_affiliate_wp_customers WHERE wp_affiliate_wp_customers.customer_id = wp_affiliate_wp_referrals.customer_id) as resellerWpUserId , (SELECT wp_users.user_email FROM wp_users WHERE wp_users.ID = resellerWpUserId) as resellerWpEmailAddress, (SELECT wp_users.user_login FROM wp_users WHERE wp_users.ID = resellerWpUserId) as resellerAccessCode, wp_affiliate_wp_referrals.description as productName , pm1.post_id as wpOrderId ,pm1.meta_value as buyerWpUserId, wp_affiliate_wp_affiliates.affiliate_id as buyerAffiliateId, (SELECT wp_users.user_email FROM wp_users WHERE wp_users.ID = buyerWpUserId) as buyerWpEmailAddress , pm2.meta_value as tr FROM `wp_posts` LEFT JOIN wp_postmeta pm1 ON wp_posts.ID = pm1.post_id AND pm1.meta_key = '_customer_user' LEFT JOIN wp_affiliate_wp_affiliates ON wp_affiliate_wp_affiliates.user_id = pm1.meta_value LEFT JOIN wp_affiliate_wp_referrals ON wp_affiliate_wp_referrals.affiliate_id = wp_affiliate_wp_affiliates.affiliate_id LEFT JOIN wp_postmeta pm2 ON wp_posts.ID = pm2.post_id AND pm2.meta_key = '_paid_date' WHERE pm2.meta_value >= '".$startDate."'  AND  pm2.meta_value <= '".$endDate."' AND pm1.meta_value != ''
UNION 
SELECT *,wp_affiliate_wp_referrals.referral_id AS resellerReferralId , wp_affiliate_wp_referrals.affiliate_id AS resellerAffiliateId, (SELECT wp_affiliate_wp_customers.user_id FROM wp_affiliate_wp_customers WHERE wp_affiliate_wp_customers.customer_id = wp_affiliate_wp_referrals.customer_id) as resellerWpUserId, (SELECT wp_users.user_email FROM wp_users WHERE wp_users.ID = resellerWpUserId) as resellerWpEmailAddress, (SELECT wp_users.user_login FROM wp_users WHERE wp_users.ID = resellerWpUserId) as resellerAccessCode, wp_affiliate_wp_referrals.description as productName, pm1.post_id as wpOrderId ,pm1.meta_value as buyerWpUserId, wp_affiliate_wp_affiliates.affiliate_id as buyerAffiliateId, (SELECT wp_users.user_email FROM wp_users WHERE wp_users.ID = buyerWpUserId) as buyerWpEmailAddress , pm2.meta_value as tr FROM `wp_posts` RIGHT JOIN wp_postmeta pm1 ON wp_posts.ID = pm1.post_id AND pm1.meta_key = '_customer_user' RIGHT JOIN wp_affiliate_wp_affiliates ON wp_affiliate_wp_affiliates.user_id = pm1.meta_value RIGHT JOIN wp_affiliate_wp_referrals ON wp_affiliate_wp_referrals.affiliate_id = wp_affiliate_wp_affiliates.affiliate_id RIGHT JOIN wp_postmeta pm2 ON wp_posts.ID = pm2.post_id AND pm2.meta_key = '_paid_date' WHERE pm2.meta_value >= '".$startDate."'  AND pm2.meta_value <= '".$endDate."' AND pm1.meta_value != '' ORDER by tr ASC", OBJECT );


    foreach ($results as $post) 
    { 
        $post->tomNotes     = "";
        $orderId       = $post->wpOrderId;
        $description   = $post->productName;
        $checkOrderId  = get_post_meta($orderId, '_subscription_renewal', true);
        $checkOrderId2 = get_post_meta($orderId, '_requires_manual_renewal', true);
        //  if($checkOrderId || $checkOrderId2) {
             
            // foreach($inclusiveProducts as $product) {
            //     if(strtoupper($product) == strtoupper($description)) {
                    // get transaction Id
                    $orderId = $post->wpOrderId;
                    $userId = $post->buyerWpUserId;
                    
                    /////////////getting entry URL/////////////
                    
                    
                     $createLeadRequest = get_post_meta( $orderId, 'createLeadRequest' ,true );
                     if($createLeadRequest) {
                        $createLeadRequest = json_decode($createLeadRequest);
                        $entryUrl = $createLeadRequest->trackingInfo->entryUrl;
                        $post->entryUrl = $entryUrl;
                     }
                     
                     
                    
                    
                    
                    // ---------------------------------------
                    // VERY IMPORTANT (getting referrer) start
                    // ---------------------------------------
                    
                    $queryForGettingCustId = "SELECT customer_id FROM wp_affiliate_wp_customers WHERE user_id = '".$userId."'";
                     
                    $queryForGettingCustIdR = $wpdb->get_results($queryForGettingCustId);
                    if(!empty($queryForGettingCustIdR)) {
                        $refCustomerId = $queryForGettingCustIdR[0]->customer_id;
                        // $post->resellerAffiliateId = $refCustomerId;
                        
                        
                        //getting affiliateId from CustomerId
                        $queryForGettingAffId = "SELECT affiliate_id FROM `wp_affiliate_wp_referrals` WHERE customer_id = '".$refCustomerId."'";
                        $queryForGettingAffIdR = $wpdb->get_results($queryForGettingAffId);
                        if(!empty($queryForGettingAffIdR)) {
                            $refAffiliateId = $queryForGettingAffIdR[0]->affiliate_id;
                            
                            
                            //getting ref ref 
                            $queryForGettingrefInfo = "SELECT * FROM `wp_affiliate_wp_affiliates` WHERE affiliate_id = '".$refAffiliateId."'";
                            $queryForGettingrefInfoR = $wpdb->get_results($queryForGettingrefInfo);
                            if(!empty($queryForGettingrefInfoR)) {
                                
                                $resellerWPUserID = $queryForGettingrefInfoR[0]->user_id;
                                $resellerWpemailAddress = $queryForGettingrefInfoR[0]->payment_email;
                                $post->resellerAffiliateId = $refAffiliateId;
                                $post->resellerWpUserId = $resellerWPUserID;
                                $post->resellerWpEmailAddress = $resellerWpemailAddress;
                                $post->comStatus = "WP Affiliate";
                                
                            } else {
                                
                                    if(isset($post->entryUrl)){
                                        
                                    $url = $post->entryUrl;
                                    
                                    $urlCopy = explode("/", $url);
                                    // print_r($urlCopy);
                                    $urlStatus = true;
                                    foreach($urlCopy as $key => $val){
                                        
                                        if($val == "ref"){
                                            
                                            $resellerAccessCode = $urlCopy[$key+1];
                                            $urlStatus = true;
                                            return;
                                            
                                        } else {
                                            $urlStatus = false;
                                        }
                                        
                                    }
                                    
                                    if(!$urlStatus) {
                                        $parts = parse_url($url);
                                        parse_str($parts['query'], $query);
                                        $resellerAccessCode = $query['ref'];
                                        
                                    }
                                        
                                        if($resellerAccessCode != null || !empty($resellerAccessCode)) {
                                            
                                            $queryForGettingReUId = "SELECT ID FROM `wp_users` WHERE user_login = '".$resellerAccessCode."'";
                     
                                            $queryForGettingReUIdR = $wpdb->get_results($queryForGettingReUId);
                                            
                                            if(!empty($queryForGettingReUIdR)) {
                                
                                                $resellerWPUserIDByAc = $queryForGettingReUIdR[0]->ID; 
                                
                                                $queryForGettingrefInfoByAc = "SELECT * FROM `wp_affiliate_wp_affiliates` WHERE user_id= '".$resellerWPUserIDByAc."'";
                                                $queryForGettingrefInfoByAcR = $wpdb->get_results($queryForGettingrefInfoByAc);
                                                
                                                if(!empty($queryForGettingrefInfoByAcR)) {
                                                    
                                                    $resellerWPUserID = $queryForGettingrefInfoByAcR[0]->user_id;
                                                    $resellerWpemailAddress = $queryForGettingrefInfoByAcR[0]->payment_email;
                                                    $post->resellerAffiliateId = $queryForGettingrefInfoByAcR[0]->affiliate_id;
                                                    $post->resellerWpUserId = $resellerWPUserID;
                                                    $post->resellerWpEmailAddress = $resellerWpemailAddress;
                                                    $post->comStatus = "Entry URL";
                                                    
                                                    
                                                }
                                                
                                                
                                            }
                                            
                                            
                                            
                                        }
                                        
                                        
                                        
                                    }
                                
                                
                            }
                            
                            
                            
                        }
                        
                        
                    }
                    
                    // ---------------------------------------
                    // VERY IMPORTANT (getting referrer) end
                    // ---------------------------------------
                    
                    
                    // $order = wc_get_order( $orderId );
                    // $order_data = $order->get_data();
                    $date_created = $post->post_date;
                    // $test = date_format("2020-02-02","Y/m/d H:i:s");
                    $time                = strtotime($date_created);
                    $newformat           = date('m/d/yy h:m A',$time);
                    $post->date_created  = $newformat;
                    $cFirstName          = get_post_meta( $orderId, '_billing_first_name' ,true );
                    $cLastName           = get_post_meta( $orderId, '_billing_last_name' ,true );
                    $orderTotal          = get_post_meta( $orderId, '_order_total' ,true );
                    $transactionId       = get_post_meta( $orderId, '_transaction_id' ,true );
                    $customerUser        = get_post_meta( $orderId, '_customer_user' ,true );
                    $authorizationCode   = get_post_meta( $orderId, '_wc_authorize_net_cim_credit_card_authorization_code' ,true );
                    $chargeCaptured      = get_post_meta( $orderId, '_wc_authorize_net_cim_credit_card_charge_captured' ,true );
                    $getUFirstName       = get_user_meta( $userId, 'first_name', true );
                    $getUlastName        = get_user_meta( $userId,  'last_name', true );
                    $post->customerName  = $getUFirstName . " " . $getUlastName;
                    $getUNiceName        = get_user_meta( $userId, 'nickname', true );
                    $post->affNiceName   = $getUNiceName;
                    $post->cFirstName    = $getUFirstName;
                    $post->cLastName     = $getUlastName;
                    $post->orderTotal    = $orderTotal;
                    $post->transactionId = $transactionId;
                    $post->authorizationCode = $authorizationCode;
                    ///add reseller full name
                    if(isset($post->resellerWpUserId)) {
                        $pUserId = $post->resellerWpUserId;
                        $getPFirstName       = get_user_meta( $pUserId, 'first_name', true );
                        $getPlastName        = get_user_meta( $pUserId,  'last_name', true );
                        $post->resellerFullName  = $getPFirstName . " " . $getPlastName;
                        $post->resellerFirstName  = $getPFirstName;
                        $post->resellerLastName  = $getPlastName;
                        $post->getPNiceName        = get_user_meta( $pUserId, 'nickname', true );
                        
                    } else {
                        
                        $post->resellerFullName  = "Codebreaker Corporate";
                        $post->resellerFirstName = "Codebreaker";
                        $post->resellerLastName  = "Corporate";
                        $post->resellerWpUserId = 11;
                        $post->resellerWpEmailAddress = "bank@bankcode.com";
                        $post->getPNiceName = "Bank";
                        
                    }
                    
                    ///
                    if($chargeCaptured) {
                        $post->chargeCaptured = "CMPLT";    
                    } else {
                        $post->chargeCaptured = "DECLINED";
                    }
                    $post->amount         = round($post->amount);
                    $postStatus           = get_post_status($orderId );
                    $post->orderSatus     = $postStatus;
                    $post->customerUser   = $customerUser;
                    $emailAddress = $post->buyerWpEmailAddress;
                    $post->cv = round($orderTotal);
                    if($post->cv == 1) {
                        $post->cv = 0;
                    }
                    foreach($roundValues as $cv) {
                        if($orderTotal == $cv) {
                            $post->cv = $orderTotal + 1;
                        } 
                    }
                    
                    // $post->newRate = $post->rate / 100;
                    // $comn = $post->orderTotal * $post->newRate;
                    // $post->amount = round($comn);
                    $resellerWpEmailAddress = $post->resellerWpEmailAddress;
                    
                    
                    
                    foreach($emails20 as $rate) {
                        if(strtoupper($resellerWpEmailAddress) == strtoupper($rate)) {
                            $post->newRate = 0.2; 
                            $comn = $post->orderTotal * 0.2;
                            
                            $post->amount = round($comn);
                        }
                    }
                    
                    
                    foreach($fortyPercentUsers as $rate) {
                        if(strtoupper($resellerWpEmailAddress) == strtoupper($rate)) {
                            $post->newRate = 0.4; 
                            $comn = $post->orderTotal * 0.4;
                            
                            $post->amount = round($comn);
                        }
                    }
                    // ---------------------------------------------
                    $transactionDate = get_post_meta( $orderId, '_paid_date' ,true );
                    $post->transactionDate = $transactionDate;
                    array_push($originalData, $post);                 
    }
    
    // } }

$originalDataCopy = $originalData;
$names = [];
$withUniqueNames = array_reduce(
    $originalDataCopy,
    function ($withUniqueNames, $object) use (&$names) {
        if (!in_array($object->transactionId, $names)) {
            $names[] = $object->transactionId;
            $withUniqueNames[] = $object;
        } 
        return $withUniqueNames;
    },
    []
);

$originalDatatest = [];
$ahmad = [];



// echo "<pre>";
// print_r($withUniqueNames);
// echo "</pre>";



foreach($withUniqueNames as $key1 => $val) {
    
    if($val->chargeCaptured != "DECLINED") {
        
        if($val->post_status == "wc-processing") {
            // if($val->orderTotal != 1.00 ) {
                
            // $buyerWpUserId = $val->buyerWpUserId;    
            // $rs = $wpdb->get_results("SELECT post_id FROM wp_postmeta WHERE meta_key = '_customer_user' AND meta_value = '".$buyerWpUserId."' ORDER BY post_id ASC LIMIT 1");
                // if (!empty($rs)) {
                    // $parentWPOrderId = $rs[0]->post_id;
                // } else {
                    $parentWPOrderId = 0;
                // }
                
            
            
            
            
            $orderId = $val-> wpOrderId;
            $order = wc_get_order ($orderId);
            $items = $order-> get_items ();
        $itemsCount = count($items); 
        $i = 0;
        if($itemsCount > 1) {
            unset($results[$val]);
            foreach ( $items as $key => $item ) {
                $postCopy = $val;
                $postCopy->orderTotal = $item->get_subtotal();
                $postCopy->description = $item->get_name();
                
                $postCopy->parentWPOrderId = $parentWPOrderId;
                
                $orderTotal = $postCopy->orderTotal;
                $postCopy->cv = round($orderTotal);

                
                if($postCopy->cv == 1) {
                    $postCopy->cv = 0;
                    }
                    foreach($roundValues as $cv) {
                        if($orderTotal == $cv) {
                            $postCopy->cv = $orderTotal + 1;
                        } 
                    }
                    $newRate = $postCopy->newRate;
                    $newRate = str_replace("%", "", $newRate);
                    $newRate = $newRate * 100;
                    $newRate = $newRate / 100;
                    $comn = $postCopy->orderTotal * $newRate;
                    $postCopy->amount = round($comn);
                  $postCopy = (array) $postCopy;
                  $ahmad[] = $postCopy;
            }
        } else {
            foreach ( $items as $key => $item ) {
                $postCopy = $val;
                $postCopy->description = $item->get_name(); 
                
                
                $postCopy->parentWPOrderId = $parentWPOrderId;
                
                $postCopy = (array) $postCopy;
                $ahmad[] = $postCopy; 
            }
        }
            
            
        // }
            
        }
        
    }
    
}
$results = $ahmad;


// echo "<pre>";
// print_r($results);
// echo "</pre>";



// echo "before: ".count($results);
$ahmadkhalid = [];

    
//     foreach($results as $k=>$v) { 
//         // echo $k.$v->description."<br>";
        
//         foreach($inclusiveProducts as $product) {
        
//         if(strtoupper($v['description']) === strtoupper($product)){
//             // echo "inc: ".$product."<br>";
//             // echo "db: ".$v['description']."<br>";
//             // echo $product."<br>";
//             // unset($withUniqueNames[$k]); //Delete from Array 
//             $ahmadkhalid[] = (array) $v;
//         }
// }
    
// }

// echo "After: ".count($ahmadkhalid);


// echo "<pre>";
// print_r($ahmadkhalid);
// echo "</pre>";


$reader 	 = IOFactory::createReader('Xlsx');                                 // get report data
$spreadsheet = $reader->load("orderstemplate.xlsx");                                  // load the xlsx template
$startDate1 = strtotime($startDateName);                                             // set tab name
$startDate1 = date('M d', $startDate1);                            
$endDate1   = strtotime($endDateName);
$endDate1   = date('M d, Y', $endDate1);   
$tabName   = $startDate1." to ".$endDate1;
$fileStartDate = strtotime($startDateName);
$fileStartDate = date('Y-md', $fileStartDate); 
$fileEndDate = strtotime($endDateName);
$fileEndDate = date('md', $fileEndDate);
$fileName = "OrdersCommissionReport-".$fileStartDate."-to-".$fileEndDate.".xlsx";
// $fileName = str_replace("_", "", $fileName);
$spreadsheet->getActiveSheet()->setTitle($tabName);
//add the content
$currentStartRow   = 2;
$currentContentRow = 2;
foreach($results as $result) {
	$spreadsheet->getActiveSheet()->insertNewRowBefore($currentContentRow+1,1);
    $transactionDate = strtotime($result['transactionDate']);
    $transactionDateNew = strtotime($result['transactionDate']);
    $transactionDateNew = date('m/d/yy h:i:sa', $transactionDateNew);
    $transactionDate = date('m/d/yy h:i:sa', $transactionDate);
     
    $transactionDatePST = date('m/d/yy', strtotime($transactionDateNew . ' -7 hours'));
    $transactionTimePST = date('h:i:sa', strtotime($transactionDateNew . ' -7 hours'));
    
    $date_created    = strtotime($result['date_created']);
    $date_created    = date('m/d/yy', $date_created); 
    
    $date_createdDatePST = date('m/d/yy', strtotime($date_created . ' -7 hours'));
    $date_createdTimePST = date('h:i:sa', strtotime($date_created . ' -7 hours'));
    
    $tr    = strtotime($result['tr']);
    $tr = date('m/d/yy h:i:sa', $tr); 
    
	$spreadsheet-> getActiveSheet()
				->setCellValue('A'.$currentContentRow , $result['wpOrderId'])
				->setCellValue('B'.$currentContentRow , $transactionDatePST)
				->setCellValue('C'.$currentContentRow , $transactionTimePST)
				->setCellValue('D'.$currentContentRow , "")
				->setCellValue('E'.$currentContentRow , $result['orderTotal'])
				->setCellValue('F'.$currentContentRow , $result['cv'])
				// ->setCellValue('E'.$currentContentRow , $result['parentOrderId'])$postCopy->parentOrderId = $parent_order_id;
				->setCellValue('G'.$currentContentRow , $result['parentWPOrderId'])
				->setCellValue('H'.$currentContentRow , $date_createdDatePST)
				->setCellValue('I'.$currentContentRow , $date_createdTimePST)
				->setCellValue('J'.$currentContentRow , $result['description'])
				->setCellValue('K'.$currentContentRow , $result['buyerWpUserId'])
				->setCellValue('L'.$currentContentRow , $result['post_status'])
				->setCellValue('M'.$currentContentRow , $result['post_type'])
				->setCellValue('N'.$currentContentRow , $result['comStatus'])
				->setCellValue('O'.$currentContentRow , $result['buyerWpEmailAddress'])
				->setCellValue('P'.$currentContentRow , $result['affNiceName'])
				->setCellValue('Q'.$currentContentRow , str_replace('\' ', '\'', ucwords(str_replace('\'', '\' ', strtolower($result['customerName'])))))
				->setCellValue('R'.$currentContentRow , str_replace('\' ', '\'', ucwords(str_replace('\'', '\' ', strtolower($result['cFirstName'])))))
				->setCellValue('S'.$currentContentRow , str_replace('\' ', '\'', ucwords(str_replace('\'', '\' ', strtolower($result['cLastName'])))))
				->setCellValue('T'.$currentContentRow , str_replace('\' ', '\'', ucwords(str_replace('\'', '\' ', strtolower($result['resellerFullName'])))))
				->setCellValue('U'.$currentContentRow , str_replace('\' ', '\'', ucwords(str_replace('\'', '\' ', strtolower($result['resellerFirstName'])))))
				->setCellValue('V'.$currentContentRow , str_replace('\' ', '\'', ucwords(str_replace('\'', '\' ', strtolower($result['resellerLastName'])))))
				->setCellValue('W'.$currentContentRow , $result['resellerWpUserId'])
				->setCellValue('X'.$currentContentRow , $result['resellerWpEmailAddress'])
				->setCellValue('Y'.$currentContentRow , $result['getPNiceName'])
				->setCellValue('Z'.$currentContentRow , "")
				->setCellValue('AA'.$currentContentRow , "")
				->setCellValue('AB'.$currentContentRow , "")
				->setCellValue('AC'.$currentContentRow , $result['entryUrl'])
				->setCellValue('AD'.$currentContentRow , $result['resellerAffiliateId'])
				->setCellValue('AE'.$currentContentRow , $result['chargeCaptured'])
				->setCellValue('AF'.$currentContentRow , $result['newRate'])
				->setCellValue('AG'.$currentContentRow , $result['transactionId'])
				->setCellValue('AH'.$currentContentRow , $result['authorizationCode'])
				->setCellValue('AI'.$currentContentRow , $result['amount'])
				->setCellValue('AJ'.$currentContentRow , "");
	$currentContentRow++;
}
//remove 
//set the header first, so the result will be treated as an xlsx file.
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); 
//make it an attachment so we can define filename
header('Content-Disposition: attachment;filename="'.$fileName.'"');                          
//create IOFactory object
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');                                   
ob_end_clean();
$writer->save('php://output');
exit();
//save into php output

?>

