<?php

class Ambient_Routee_Adminhtml_RouteeController extends Mage_Adminhtml_Controller_Action {

    public function generatemmidAction() {
        $username = $this->getRequest()->getParam('username');
        $pwd = $this->getRequest()->getParam('pwd');

        $pusername = Mage::getStoreConfig('routeesection/routeegroup/routee_username');
        $ppwd = Mage::getStoreConfig('routeesection/routeegroup/routee_pwd');

        if (empty($username) || empty($pwd)) {
            if (empty($username) && empty($pwd)) {
                Mage::getSingleton('core/session')->addError('First fill username and password');
            } else if (empty($username)) {
                Mage::getSingleton('core/session')->addError('First fill username');
            } else if (empty($pwd)) {
                Mage::getSingleton('core/session')->addError('First fill password');
            }
            if (!empty($username)) {
                Mage::getConfig()->saveConfig('routeesection/routeegroup/routee_username', $username, 'default', 0);
            }
            if (!empty($pwd)) {
                Mage::getConfig()->saveConfig('routeesection/routeegroup/routee_pwd', $pwd, 'default', 0);
            }
        } else if (!empty($username) && !empty($pwd)) {
            Mage::getConfig()->saveConfig('routeesection/routeegroup/routee_username', $username, 'default', 0);
            Mage::getConfig()->saveConfig('routeesection/routeegroup/routee_pwd', $pwd, 'default', 0);
            if ($username != $pusername || $pwd != $ppwd) {
                $requestcont = array();
                $requestcont['username'] = $username;
                $requestcont['password'] = $pwd;
                $requestcont['source'] = "Magento";
                $requestcont['type'] = "E-COMMERCE";
                $requestcont['version'] = Mage::getVersion();
                $requestcont['domain'] = Mage::getBaseUrl();

                $json = Mage::helper('core')->jsonEncode($requestcont);

                $url = "https://waymore.routee.net/api/authenticate";

                $c = curl_init();
                curl_setopt($c, CURLOPT_URL, $url);
                curl_setopt($c, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
                curl_setopt($c, CURLOPT_POST, true);
                curl_setopt($c, CURLOPT_POSTFIELDS, $json);
                curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($c, CURLOPT_TIMEOUT, 30);
                $response = curl_exec($c);
                curl_close($c);

                $result = Mage::helper('core')->jsonDecode($response);

                if ($result['uuid']) {
                    Mage::getConfig()->saveConfig('routeesection/routeegroup/routee_mmid', $result['uuid'], 'default', 0);
                    Mage::getSingleton('core/session')->addSuccess('Routee MMID created and save successfully');
                } else {
                    Mage::getSingleton('core/session')->addError('Username and password are wrong');
                }
            } else {
                if (empty(Mage::getStoreConfig('routeesection/routeegroup/routee_mmid'))) {
                    $requestcont = array();
                    $requestcont['username'] = Mage::getStoreConfig('routeesection/routeegroup/routee_username');
                    $requestcont['password'] = Mage::getStoreConfig('routeesection/routeegroup/routee_pwd');
                    $requestcont['source'] = "Magento";
                    $requestcont['type'] = "E-COMMERCE";
                    $requestcont['version'] = Mage::getVersion();
                    $requestcont['domain'] = Mage::getBaseUrl();

                    $json = Mage::helper('core')->jsonEncode($requestcont);

                    $url = "https://waymore.routee.net/api/authenticate";

                    $c = curl_init();
                    curl_setopt($c, CURLOPT_URL, $url);
                    curl_setopt($c, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
                    curl_setopt($c, CURLOPT_POST, true);
                    curl_setopt($c, CURLOPT_POSTFIELDS, $json);
                    curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($c, CURLOPT_TIMEOUT, 30);
                    $response = curl_exec($c);
                    curl_close($c);

                    $result = Mage::helper('core')->jsonDecode($response);

                    if ($result['uuid']) {
                        Mage::getConfig()->saveConfig('routeesection/routeegroup/routee_mmid', $result['uuid'], 'default', 0);
                        Mage::getSingleton('core/session')->addSuccess('Routee MMID created and save successfully');
                    } else {
                        Mage::getSingleton('core/session')->addError('Username and password are wrong');
                    }
                } else {
                    Mage::getSingleton('core/session')->addSuccess('Routee MMID already created');
                }
            }
        }
        $this->_redirectReferer();
    }

    public function bulkimportAction() {

        Mage::getConfig()->saveConfig('routeesection/routeegroup/routee_bulkimport', 0, 'default', 0);
        
        if (empty(Mage::getStoreConfig('routeesection/routeegroup/routee_mmid'))) {
            Mage::getSingleton('core/session')->addError('MMID not found please create MMID first.');
            $this->_redirectReferer();
            return;
        }

        $uuid = Mage::getStoreConfig('routeesection/routeegroup/routee_mmid');
        $mainrequest = array();


        //load all customer
        $customers = Mage::getModel('customer/customer')->getCollection();

        if ($customers->count() > 0) {

            /* 
            * Part of new batch implementation
            * cURL initialize once so for mulitple customers it will remain same and avoid re-initialize in looping
            * Date : 02/19/2020
            * Author : Kapil Hanswal
            */
            $cu = curl_init();

            /*
            * Part of new batch implementation
            * Flags that will be used to send the customer data in batch, $l is used to print log only
            * Date : 02/18/2020
            * Author : Kapil Hanswal 
            */
            $c = 0;
            $i = 0;
            
            /* 
            * Part of new batch implementation 
            * This will be useful to compare with the batch count and once equal we need to indicate to execute next mass data api
            * Date : 02/18/2020
            * Author : Kapil Hanswal 
            */
            $total_users = $customers->count();
            
            /*
            * Part of new batch implementation 
            * Base object of data and uuid, rest data will be added in this object and will send at the end.
            * Date : 02/18/2020
            * Author : Kapil Hanswal 
            */
            $mass_data = array(
                'uuid' => $uuid,
                'data' => array(
                    array(
                        'name' => 'customers',
                        'description' => 'Shop Customers'
                    )
                )
            );
            foreach ($customers as $customer) {
                $customer1 = Mage::getModel('customer/customer')->load($customer->getId());
                $subscriber = Mage::getModel('newsletter/subscriber')->loadByEmail($customer1->getEmail());

                /*
                * Part of new batch implementation 
                * Building customer address array that will be passed into main object
                * Date : 02/19/2020
                * Author : Kapil Hanswal 
                */
                $addressreq_new = array();
                foreach ($customer1->getAddresses() as $address) {
                    $country = Mage::app()->getLocale()->getCountryTranslation($address->getCountryId());
                    $street = $address->getStreet();
                    $addressreq = array();
                    $addressreq['country'] = $country;
                    $addressreq['city'] = $address->getCity();
                    $addressreq['address1'] = $street[0];
                    $addressreq['address2'] = $street[1];
                    $addressreq['postcode'] = $address->getPostcode();

                    if ($address->getCompany()) {
                        $addressreq['company'] = $address->getCompany();
                    }

                    if ($address->getRegion()) {
                        $addressreq['region'] = $address->getRegion();
                    }

                    if ($address->getTelephone()) {
                        $addressreq['phone'] = $address->getTelephone();
                    }

                    if ($address->getFax()) {
                        $addressreq['fax'] = $address->getFax();
                    }
                    $addressreq_new[] = $addressreq;
                }
                
                /*
                * Part of new batch implementation 
                * Main object that contains all the information regarding customer and this will be sent at the end to routee.
                * Date : 02/19/2020
                * Author : Kapil Hanswal 
                */
                $mass_data['data'][0]['object'][$i] = array(
                    'customer' => array(
                        'id' => $customer1->getId(),
                        'lastname' => $customer1->getLastname(),
                        'firstname' => $customer1->getFirstname(),
                        'birthday' => date('d/m/Y', strtotime($customer1->getDob())),
                        'email' => $customer1->getEmail(),
                        'phone' => $phone,
                    ),
                    'addresses' => $addressreq_new
                );    

                $i++;
                $c++;
            
                /*
                * Part of new batch implementation 
                * Batch mechanism, if batch count equal to 100 then reset batch count for next batch and if loop count is equal to total users then get response from routee server to process next mass data.
                * Date : 02/19/2020
                * Author : Kapil Hanswal 
                */
                if ($i == 100 || $c == $total_users) {

                    $url = "https://idata.routee.net/api/data";

                    curl_setopt($cu, CURLOPT_URL, $url);
                    curl_setopt($cu, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
                    curl_setopt($cu, CURLOPT_POST, true);
                    curl_setopt($cu, CURLOPT_POSTFIELDS, json_encode($mass_data));
                    curl_setopt($cu, CURLOPT_RETURNTRANSFER, true);
                    
                    //response will contain the output in form of JSON string
                    $i = 0;
                    $mass_data['data'][0]['object'] = array();
                    
                    $response = curl_exec($cu);
                    if($c == $total_users)
                    {
                        $responseArr = json_decode($response, true);
                        if(isset($responseArr['message']) && !empty($responseArr['message'])) {
                            $customerResponse = "CustomerDone";
                        }
                    }
                }
            }
        } else {
            $customerResponse = "CustomerDone";
        }
        
        //load all subscribers
        $newsletters = Mage::getResourceSingleton('newsletter/subscriber_collection');

        if ($newsletters->count() > 0 && $customerResponse=='CustomerDone') {
            /* 
            * Part of new batch implementation
            * cURL initialize once so for mulitple subscribers it will remain same and avoid re-initialize in looping
            * Date : 02/19/2020
            * Author : Kapil Hanswal
            */
            $su = curl_init();

            /*
            * Part of new batch implementation
            * Flags that will be used to send the subscriber data in batch, $l is used to print log only
            * Date : 02/19/2020
            * Author : Kapil Hanswal 
            */
            $s = 0;
            $i = 0;
            
            /* 
            * Part of new batch implementation 
            * This will be useful to compare with the batch count and once equal we need to indicate to execute next mass data api
            * Date : 02/19/2020
            * Author : Kapil Hanswal 
            */
            $total_subscribers = $newsletters->count();
            
            /*
            * Part of new batch implementation 
            * Base object of data and uuid, rest data will be added in this object and will send at the end.
            * Date : 02/19/2020
            * Author : Kapil Hanswal 
            */
            $mass_data = array(
                'uuid' => $uuid,
                'data' => array(
                    array(
                        'name' => 'subscribers',
                        'description' => 'Shop Subscribers'
                    )
                )
            );
            foreach ($newsletters as $newsletter) {

                /*
                * Part of new batch implementation 
                * Main object that contains all the information regarding subscriber and this will be sent at the end to routee.
                * Date : 02/19/2020
                * Author : Kapil Hanswal 
                */
                $mass_data['data'][0]['object'][$i] = array('subscriber' => array(
                    'id' => $newsletter->getSubscriberId(),
                    'id_shop' => $requestData['store_id'],
                    'id_shop_group' => $requestData['store_id'],
                    'email' => $newsletter->getEmail(),
                    /*'subscription' => $newsletter->getSubscription(),*/
                    'newsletter_date_add' => $newsletter->getChangeStatusAt(),
                    'ip_registration_newsletter' => 'N/A',
                    'http_referer' => 'N/A',
                    'active' => $newsletter->getSubscriberStatus(),                    
                ));

                $i++;
                $s++;
        
                /*
                * Part of new batch implementation 
                * Batch mechanism, if batch count equal to 100 then reset batch count for next batch and if loop count is equal to total users then get response from routee server to process next mass data.
                * Date : 02/19/2020
                * Author : Kapil Hanswal 
                */
                if ($i == 100 || $s == $total_subscribers) {
        
                    $url = "https://idata.routee.net/api/data";

                    curl_setopt($su, CURLOPT_URL, $url);
                    curl_setopt($su, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
                    curl_setopt($su, CURLOPT_POST, true);
                    curl_setopt($su, CURLOPT_POSTFIELDS, json_encode($mass_data));
                    curl_setopt($su, CURLOPT_RETURNTRANSFER, true);
                    
                    //response will contain the output in form of JSON string
                    $i = 0;
                    $mass_data['data'][0]['object'] = array();
                    
                    $response = curl_exec($su);
                    if($s == $total_subscribers)
                    {
                        $responseArr = json_decode($response, true);
                        if(isset($responseArr['message']) && !empty($responseArr['message'])) {
                            $subscriberResponse = "SubscriberDone";
                        }
                    }
                }                
            }
        } else{
            $subscriberResponse = "SubscriberDone";
        }
        
        //load all product
        $products = Mage::getModel('catalog/product')->getCollection();

        if ($products->count() > 0 && $subscriberResponse=='SubscriberDone') {
            /* 
            * Part of new batch implementation
            * cURL initialize once so for mulitple products it will remain same and avoid re-initialize in looping
            * Date : 02/18/2020
            * Author : Kapil Hanswal
            */
            $pr = curl_init();
            /*
            * Part of new batch implementation
            * Flags that will be used to send the product data in batch, $l is used to print log only
            * Date : 02/18/2020
            * Author : Kapil Hanswal 
            */
            $p = 0;
            $i = 0;
            
            /* 
            * Part of new batch implementation 
            * This will be useful to compare with the batch count and once equal we need to indicate to execute next mass data api
            * Date : 02/18/2020
            * Author : Kapil Hanswal 
            */
            $total_products = $products->count();
            
            /*
            * Part of new batch implementation 
            * Base object of data and uuid, rest data will be added in this object and will send at the end.
            * Date : 02/18/2020
            * Author : Kapil Hanswal 
            */
            $mass_data = array(
                'uuid' => $uuid,
                'data' => array(
                    array(
                        'name' => 'products',
                        'description' => 'Shop Products'
                    )
                )
            );

            foreach ($products as $_product) {
                $product = Mage::getModel('catalog/product')->load($_product->getId());

                $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product);    

                if ($product->getImage()) {
                    $image_link = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . 'catalog/product' . $product->getImage();
                } else {
                    $image_link = '';
                }    

                /*
                * Part of new batch implementation 
                * Declare discount array that will be added in the product object and can have more than one discounted options.
                * Date : 02/18/2020
                * Author : Kapil Hanswal 
                */
                $discount = array();
                    
                $specialprice = $product->getSpecialPrice();
                if($specialprice > 0) {
                    $specialfromdate = date('d/m/Y', strtotime($product->getSpecialFromDate()));
                    $specialtodate = date('d/m/Y', strtotime($product->getSpecialToDate()));
                    $discount['price'] = $specialprice ;
                    $discount['date_start'] = $specialfromdate ;
                    $discount['date_end'] = $specialtodate ;
                    $discount['quantity'] = null ;
                }

                /*
                * Part of new batch implementation 
                * Main object that contains all the information regarding the product items and this will be sent at the end to routee.
                * Date : 02/18/2020
                * Author : Kapil Hanswal 
                */
                $mass_data['data'][0]['object'][$i] = array(
                    'product_id' => $product->getId(),
                    'name' => $product->getName(),
                    'description' => $product->getDescription(),
                    'short_description' => $product->getShortDescription(),
                    'stock_quantity' => (int) $stock->getQty(),
                    'price' => $product->getFinalPrice(),
                    'discount' => $discount,
                    'image_link' => $image_link,
                    'product_link' => $product->getProductUrl(true),
                );    

                /*
                * Part of new batch implementation 
                * Building category array that will be sent in product object, will return category ids array
                * Date : 02/18/2020
                * Author : Kapil Hanswal 
                */
                $categories = $product->getCategoryIds(); /*will return category ids array*/
                if (!empty($categories)) {
                    foreach($categories as $category){
                        $cat = Mage::getModel('catalog/category')->load($id);
                        $mass_data['data'][0]['object'][$i]['categories'][] = $cat->getName();
                    }
                }

                $i++;
                $p++;
            
                /*
                * Part of new batch implementation 
                * Batch mechanism, if batch count equal to 100 then reset batch count for next batch and if loop count is equal to total products then get response from routee server to process next mass data.
                * Date : 02/18/2020
                * Author : Kapil Hanswal 
                */
                if ($i == 100 || $p == $total_products) {

                    $url = "https://idata.routee.net/api/data";

                    curl_setopt($pr, CURLOPT_URL, $url);
                    curl_setopt($pr, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
                    curl_setopt($pr, CURLOPT_POST, true);
                    curl_setopt($pr, CURLOPT_POSTFIELDS, json_encode($mass_data));
                    curl_setopt($pr, CURLOPT_RETURNTRANSFER, true);
                    
                    //response will contain the output in form of JSON string
                    $i = 0;
                    $mass_data['data'][0]['object'] = array();

                    $response = curl_exec($pr);
                    if($p == $total_products)
                    {
                        $responseArr = json_decode($response, true);
                        if(isset($responseArr['message']) && !empty($responseArr['message'])) {
                            $productResponse = "ProductDone";
                        }
                    }
                }                
            }
        } else {
            $productResponse = "ProductDone";
        }

        //load all wishlist items
        $wishlistitems = Mage::getModel('wishlist/item')->getCollection();

        if ($wishlistitems->count() > 0 && $productResponse=='ProductDone') {
            /* 
            * Part of new batch implementation
            * cURL initialize once so for mulitple wishlistitems it will remain same and avoid re-initialize in looping
            * Date : 02/20/2020
            * Author : Kapil Hanswal
            */
            $wi = curl_init();
            /*
            * Part of new batch implementation
            * Flags that will be used to send the wishlist items in batch, $l is used to print log only
            * Date : 02/20/2020
            * Author : Kapil Hanswal 
            */
            $w = 0;
            $i = 0;
            
            /* 
            * Part of new batch implementation 
            * This will be useful to compare with the batch count and once equal we need to indicate to execute next mass data api
            * Date : 02/20/2020
            * Author : Kapil Hanswal 
            */
            $total_wishlists = $wishlistitems->count();
            
            /*
            * Part of new batch implementation 
            * Base object of data and uuid, rest data will be added in this object and will send at the end.
            * Date : 02/20/2020
            * Author : Kapil Hanswal 
            */
            $mass_data = array(
                'uuid' => $uuid,
                'data' => array(
                    array(
                        'name' => 'wishlists',
                        'description' => 'Shop Wishlists'
                    )
                )
            );

            foreach ($wishlistitems as $wishlist) {

                //Fetching customer id from wishlist table for the wishlist item id and it will be passed in to mass data
                $customer = Mage::getSingleton('wishlist/wishlist')->load($wishlist->wishlist_id);
                
                $mass_data['data'][0]['object'][$i] = array(
                    'customer_id' => $customer->customer_id,
                    'product_id' => $wishlist->getProductId()
                );

                $i++;
                $w++;
        
                /*
                * Part of new batch implementation 
                * Batch mechanism, if batch count equal to 100 then reset batch count for next batch and if loop count is equal to total users then get response from routee server to process next mass data.
                * Date : 02/20/2020
                * Author : Kapil Hanswal 
                */
                if ($i == 100 || $w == $total_wishlists) {
        
                    $url = "https://idata.routee.net/api/data";

                    curl_setopt($wi, CURLOPT_URL, $url);
                    curl_setopt($wi, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
                    curl_setopt($wi, CURLOPT_POST, true);
                    curl_setopt($wi, CURLOPT_POSTFIELDS, json_encode($mass_data));
                    curl_setopt($wi, CURLOPT_RETURNTRANSFER, true);

                    //response will contain the output in form of JSON string
                    $i = 0;
                    $mass_data['data'][0]['object'] = array();
                    
                    $response = curl_exec($wi);
                    if($w == $total_wishlists)
                    {
                        $responseArr = json_decode($response, true);
                        if(isset($responseArr['message']) && !empty($responseArr['message'])) {
                            $wishlistResponse = "WishlistDone";
                        }
                    }
                }
            }
        } else {
            $wishlistResponse = "WishlistDone";
        }

        //load all product
        $orders = Mage::getModel('sales/order')->getCollection();

        if($orders->count() > 0 && $wishlistResponse=='WishlistDone'){
            /* 
            * Part of new batch implementation
            * cURL initialize once so for mulitple orders it will remain same and avoid re-initialize in looping
            * Date : 02/20/2020
            * Author : Kapil Hanswal
            */
            $or = curl_init();
            /*
            * Part of new batch implementation
            * Flags that will be used to send the orders in batch, $l is used to print log only
            * Date : 02/20/2020
            * Author : Kapil Hanswal 
            */
            $o = 0;
            $i = 0;
            
            /* 
            * Part of new batch implementation 
            * This will be useful to compare with the batch count and once equal we need to indicate to execute next mass data api
            * Date : 02/20/2020
            * Author : Kapil Hanswal 
            */
            $total_orders = $orders->count();
            
            /*
            * Part of new batch implementation 
            * Base object of data and uuid, rest data will be added in this object and will send at the end.
            * Date : 02/20/2020
            * Author : Kapil Hanswal 
            */
            $mass_data = array(
                'uuid' => $uuid,
                'data' => array(
                    array(
                        'name' => 'orders',
                        'description' => 'Shop Orders'
                    )
                )
            );

            foreach ($orders as $orderss) {
                $order = Mage::getModel('sales/order')->load($orderss->getId());

                $mass_data['data'][0]['object'][$i] = array('order_details' => array(
                    'customer_id' => $order->getCustomerId(),
                    'order_id' => $order->getId(),
                    'order_status' => $order->getStatus(),
                    'shipping_method' => $order->getShippingMethod(),
                    'payment_method' => $order->getPayment()->getMethodInstance()->getCode(),
                    'total_price' => $order->getGrandTotal(),
                    'order_create_date' => $order->getCreatedAt()
                ));
                $orderItems = $order->getAllItems();
                foreach ($orderItems as $item) {
                    $mass_data['data'][0]['object'][$i]['order_products'][] = array(
                            'product_id' => $item->getProductId(),
                            'quantity' => (int) $item->getQtyOrdered(),
                    );             
                }
                
                $i++;
                $o++;
        
                /*
                * Part of new batch implementation 
                * Batch mechanism, if batch count equal to 100 then reset batch count for next batch and if loop count is equal to total users then get response from routee server to process next mass data.
                * Date : 02/20/2020
                * Author : Kapil Hanswal 
                */
                if ($i == 100 || $o == $total_orders) {
        
                    $url = "https://idata.routee.net/api/data";

                    curl_setopt($or, CURLOPT_URL, $url);
                    curl_setopt($or, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
                    curl_setopt($or, CURLOPT_POST, true);
                    curl_setopt($or, CURLOPT_POSTFIELDS, json_encode($mass_data));
                    curl_setopt($or, CURLOPT_RETURNTRANSFER, true);

                    //response will contain the output in form of JSON string
                    $i = 0;
                    $mass_data['data'][0]['object'] = array();
                    
                    $response = curl_exec($or);
                    if($o == $total_orders)
                    {
                        $responseArr = json_decode($response, true);
                        if(isset($responseArr['message']) && !empty($responseArr['message'])) {
                            $orderResponse = "OrderDone";
                        }
                    }
                }            
            }
        } else{
            $orderResponse = "OrderDone";
        }
        
        /*
        * Part of new batch implementation 
        * After all the request have been sent to routee, it's good to check all are done and then set core config to 1 for bulk import
        * And then redirect user to the referrer page from where they came from. 
        * Date : 02/21/2020
        * Author : Kapil Hanswal 
        */
        if($customerResponse=="CustomerDone" && $subscriberResponse=="SubscriberDone" && $productResponse=="ProductDone" && $wishlistResponse=="WishlistDone" && $orderResponse=="OrderDone")
        {
            curl_close($cu);
            curl_close($su);
            curl_close($pr);
            curl_close($wi);
            curl_close($or);

            Mage::getConfig()->saveConfig('routeesection/routeegroup/routee_bulkimport', 1, 'default', 0);
            Mage::getSingleton('core/session')->addSuccess('Data Bulk imported successfully');
            $this->_redirectReferer();
        }        
    }

}
