<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    Mage
 * @package     Mage_Sales
 * @copyright   Copyright (c) 2010 Magento Inc. (http://www.magentocommerce.com)
 * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */

/**
 * Order model
 *
 * Supported events:
 *  sales_order_load_after
 *  sales_order_save_before
 *  sales_order_save_after
 *  sales_order_delete_before
 *  sales_order_delete_after
 *
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Rareplay_Sales_Model_Order extends Mage_Sales_Model_Order
{
    protected $_orderAction = null;

    public function getOrderAction()
    {
        return $this->_orderAction;
    }

    public function setOrderAction($action)
    {
        $this->_orderAction = $action;

        return $this;
    }

    /**
     * Load invoice by customOrder Id
     *
     * @param string $customOrderId
     * @return Mage_Sales_Model_Order_Invoice
     */
    public function loadByCustomOrderId($customOrderId)
    {
        $ids = $this->getCollection()
            ->addAttributeToFilter('custom_order_id', $customOrderId)
            ->getAllIds();

        if (!empty($ids)) {
            reset($ids);
            $this->load(current($ids));
        }

        return $this;
    }

    public function getBranchId()
    {
        if ($this->getPickupBranchId()) {
            $branchId = Mage::getSingleton('branch/store')->load($this->getPickupBranchId())->getId();
        } elseif ($this->getDeliveryAreaId()) {
            $branchId = Mage::getSingleton('branch/store')->getStoreByDistrictId($this->getDeliveryDistrictId())->getId();
        }
        if ($branchId == null || $branchId == '') {
            $branchId = substr($this->getCustomOrderId(), 0, 3);
        }

        return $branchId;
    }

    public function getStoreEmail()
    {
        return Mage::getSingleton('branch/store')->load($this->getBranchId())->getBranchEmail();
    }

    public function getPickupOptionText()
    {
        if ($this->getPickupOption() == 'Drive To' || $this->getPickupOption() == 'Drive Thru') {
            return 'บิ๊กซี ไดร์ฟ';
        } else {
            if ($this->getPickupBranchId()) {
                return 'รับสินค้า';
            } else //if($this->getDeliveryAreaId()})
            {
                return 'จัดส่งสินค้า';
            }
        }
    }

    public function getCanceledReason_order()
    {
        $resource = Mage::getSingleton('core/resource');
        $readConnection = $resource->getConnection('core_read');
        $query = 'SELECT * FROM ' . $resource->getTableName('order_cancel_reason_varchar');
        $rows = $readConnection->fetchAll($query);
        $result[0] = '----------------- select ------------------';
        foreach ($rows as $item) {
            $id = $item['id'];
            $result[$id] = $item['cancel_reason_desc_en'] . ' / ' . $item['cancel_reason_desc_th'];
        }

        return $result;
    }

    public function saveCanceledReason_order($id, $order_id)
    {
        $resource = Mage::getSingleton('core/resource');
        $readConnection = $resource->getConnection('core_read');
        $sql_count = "SELECT COUNT(*) AS count_no FROM " . $resource->getTableName('order_cancel_reason_entity') . " WHERE order_id = ?";
        $count = $readConnection->fetchOne($sql_count, array($order_id));
        $writeConnection = $resource->getConnection('core_write');
        if ($count > 0) {
            $sql = "UPDATE " . $resource->getTableName('order_cancel_reason_entity') . " SET cancel_id = ? WHERE order_id = ?";
            $writeConnection->query($sql, array($id, $order_id));
        } else {
            $sql = "INSERT INTO " . $resource->getTableName('order_cancel_reason_entity') . " (cancel_id, order_id) VALUES (?, ?)";
            $writeConnection->query($sql, array($id, $order_id));
        }

    }

    public function getCanceledReasonId_order($order_id)
    {

        $resource = Mage::getSingleton('core/resource');
        $readConnection = $resource->getConnection('core_read');
        $query = 'SELECT * FROM ' . $resource->getTableName('order_cancel_reason_entity') . " WHERE order_id = ?";
        $row = $readConnection->fetchAll($query, array($order_id));
        foreach ($row as $item) {
        }
        if (count($item) > 0) {
            return $item['cancel_id'];
        } else {
            return 0;
        }
    }

    public function get_supplier_normal_product($pid_list = array())
    {
        $str_pid = implode(',', $pid_list);
        $resource = Mage::getSingleton('core/resource');
        $readConnection = $resource->getConnection('core_read');
        $query = 'SELECT s.code, d.email FROM supplier_product_normal s
                        LEFT JOIN supplier_product_normal_detail d ON d.supplier_id=s.id
                        LEFT JOIN supplier_product_normal_rt_product p ON p.supplier_id=s.id
                        WHERE p.product_id IN (' . $str_pid . ')';
        $row = $readConnection->fetchAll($query);
        $res = array();
        foreach ($row as $item) {
            $supplier_code = $item['code'];
            $res[$supplier_code] = $item['email'];
        }

        return $res;
    }

    public function isDriveThru()
    {
        if ($this->getPickupOption() == 'Drive To' || $this->getPickupOption() == 'Drive Thru') {
            return true;
        } else {
            return false;
        }
    }

    public function isPickup()
    {
        if ($this->getPickupOption() != 'Drive To' && $this->getPickupOption() != 'Drive Thru' && $this->getPickupBranchId()) {
            return true;
        } else {
            return false;
        }
    }

    public function isDelivery()
    {
        if ($this->getDeliveryAreaId()) {
            return true;
        } else {
            return false;
        }
    }

    /*
    * Add a comment to order
    * Different or default status may be specified
    *
    * @param string $comment
    * @param string $status
    * @return Mage_Sales_Order_Status_History
    */
    public function addStatusHistoryComment($comment, $status = false)
    {
        if (false === $status) {
            $status = $this->getStatus();
        } elseif (true === $status) {
            $status = $this->getConfig()->getStateDefaultStatus($this->getState());
        } else {
            $this->setStatus($status);
        }
        $history = Mage::getModel('sales/order_status_history')
            ->setStatus($status)
            ->setComment($comment);
        $this->addStatusHistory($history);

        //ipune : dont send cancel update xml when edit
        try {

            // check branch
            if ($branchId = $this->getPickupBranchId()) {
            } elseif ($deliveryDistrictId = $this->getDeliveryAreaId()) {
                $branchId = Mage::getSingleton('branch/store')->getStoreByDistrictId($deliveryDistrictId)->getId();
            }

            $branchId = (int)$branchId;
            $store_enable_gway = false;
            $branchId_list = unserialize(file_get_contents($_SERVER['DOCUMENT_ROOT'] . '/context/store_gway_list.txt'));
            //     $branchId_list = array(11116, 11210, 11190, 11191, 11136, 11108, 11114, 11177, 11126, 11102, 11103, 11172);
            if (in_array($branchId, $branchId_list)) {
                $store_enable_gway = true;
            }

            $store_enable_gway = true;
            if ($store_enable_gway) {
                // send xml when customer confirm
                if ($this->getStatus() == '01') {
                    // TODO GV
                    $PID = array();
                    $order = Mage::getModel('sales/order')->load($this->getId());
                    $items = $order->getAllItems();
                    foreach ($items as $item) {
                        $PID[] = $item->getProductId();
                    }
                    $arr_gv = Mage::helper('checkout/data')->productID_GV('array');
                    $IsGv = array_intersect($arr_gv, $PID);
                    //var_dump($this->getId(),$PID,$arr_gv); exit;
                    if (count($IsGv) > 0) {
                        $arr_code = Mage::helper('checkout/data')->getSecureCode($this->getId());
                        $code1 = $arr_code['code1'];
                        $code2 = $arr_code['code2'];
                        //var_dump($IsGv, $code1, $code2);
                        Mage::helper('bcc_sales')->writeXml_master_order_gvm($this->getId(), '01', null, $code1,
                            $code2);
                        //$this->_getOrder()->sendNewOrderEmail();
                    } else {
                        //$this->_getOrder()->sendNewOrderEmail();
                        Mage::helper('bcc_sales')->writeXml_master_order($this->getId(), '01');
                    }

                    //Mage::helper('bcc_sales')->writeXml_master_order($this->getId(), '01');
                }
            } else {
                if ($this->getOrderAction() == 'edit') {
                    Mage::helper('bcc_sales')->writeXml($this->getId(), '01', $comment);
                } else {
                    if ($this->getStatus() != '00') {
                        Mage::helper('bcc_sales')->writeXml($this->getId(), $this->getStatus(), $comment);
                    }
                }
            }

        } catch (Exception $ex) {
            //var_dump($e->getMessage());
        }

        return $history;
    }


    /**
     * Send email with order data
     *
     * @return Mage_Sales_Model_Order
     */
    public function sendNewOrderEmail($storeEmail = '')
    {

        $fromapplication = $this->getFromApplication();
        $customorderid = $this->getCustomOrderId();
        if ($fromapplication == "mobile" || empty($customorderid)) {
            return $this;
        }
        Mage::log('if fn snoe : Rareplay/Sales/Model/Order.php from : ' . $fromapplication, null,
            'mgf_mike_rareplay.log');
        Mage::log('if fn snoe : Rareplay/Sales/Model/Order.php from : ' . $customorderid, null,
            'mgf_mike_rareplay.log');
        //echo('send mail gv'); exit;
        $storeId = $this->getStore()->getId();

        if (!Mage::helper('sales')->canSendNewOrderEmail($storeId)) {
            return $this;
        }
        // Get the destination email addresses to send copies to
        $copyTo = $this->_getEmails(self::XML_PATH_EMAIL_COPY_TO);
        $copyMethod = Mage::getStoreConfig(self::XML_PATH_EMAIL_COPY_METHOD, $storeId);

        if ($storeEmail == '') {
            // ------------- OUR MODIFICATION RAREPLAY -------------
            $storeEmail = Mage::getSingleton('checkout/type_onepage')->getStoreEmail();
        }
        /*
        if ($storeEmail) {
            $copyMethod = 'bcc';
            if(!$copyTo) {
                $copyTo = array();
            }
            array_push($copyTo, $storeEmail);
            // Clear email session data
            Mage::getSingleton('checkout/type_onepage')->saveStoreEmail(NULL);
        }*/


        // ******************* get time period ***************************
        list($ship_date, $ship_time) = explode(' ', $this->getShippingDateTime());
        $ship_time_list = array();
        list($ship_time_list['hh'], $ship_time_list['mm'], $ship_time_list['ss']) = explode(':', trim($ship_time));

        // get period delivery
        $period_time_tbl = Mage::helper('core/data')->getTimePeriod();
        $shipping_time_period = '';
        foreach ($period_time_tbl as $item) {
            $time_period = trim($item['label']);
            $hour = substr($time_period, 0, 2);
            if ($ship_time_list['hh'] == $hour) {
                $shipping_time_period = $time_period;
                break;
            }
        }
        // ******************* get time period ***************************

        // get GVM code
        $arr_code = Mage::helper('checkout/data')->getSecureCode($this->getId());


        // Start store emulation process
        $appEmulation = Mage::getSingleton('core/app_emulation');
        $initialEnvironmentInfo = $appEmulation->startEnvironmentEmulation($storeId);

        try {
            // Retrieve specified view block from appropriate design package (depends on emulated store)
            $paymentBlock = Mage::helper('payment')->getInfoBlock($this->getPayment())
                ->setIsSecureMode(true);
            $paymentBlock->getMethod()->setStore($storeId);
            $paymentBlockHtml = $paymentBlock->toHtml();
        } catch (Exception $exception) {
            // Stop store emulation process
            $appEmulation->stopEnvironmentEmulation($initialEnvironmentInfo);
            throw $exception;
        }

        // Stop store emulation process
        $appEmulation->stopEnvironmentEmulation($initialEnvironmentInfo);

        // Retrieve corresponding email template id and customer name
        if ($this->getCustomerIsGuest()) {
            $templateId = Mage::getStoreConfig(self::XML_PATH_EMAIL_GUEST_TEMPLATE, $storeId);
            $customerName = $this->getBillingAddress()->getName();
        } else {
            $templateId = Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE, $storeId);
            $customerName = $this->getCustomerName();
        }

        $mailer = Mage::getModel('core/email_template_mailer');
        $emailInfo = Mage::getModel('core/email_info');
        $emailInfo->addTo($this->getCustomerEmail(), $customerName);
        $mailer->addEmailInfo($emailInfo);

        // check if delivery display store name
        $store_name = '';
        if ($deliveryDistrictId = $this->getDeliveryAreaId()) {
            $store_name = Mage::getSingleton('branch/store')->getStoreByDistrictId($deliveryDistrictId)->getBranchNameTh();
        }

        // Set all required params and send emails
        $mailer->setSender(Mage::getStoreConfig(self::XML_PATH_EMAIL_IDENTITY, $storeId));
        $mailer->setStoreId($storeId);
        $mailer->setTemplateId($templateId);
        $parameter_email = array(
            'order' => $this,
            'billing' => $this->getBillingAddress(),
            'payment_html' => $paymentBlockHtml,
            'shipping_time_period' => $shipping_time_period,
        );

        if ($store_name != '') {
            $parameter_email['store_name'] = $store_name;
        }

        if ($arr_code['code2']) {
            $parameter_email['gvm_code'] = '<div>รหัสสำหรับใช้รับบัตรกำนัล(สำหรับลูกค้า) : <span style="font-weight: bold; color: #320bee;">' . $arr_code['code2'] . '</span></div><div style="color: red;">* ข้อมูลนี้ถือเป็นความลับ กรุณาอย่าเปิดเผยข้อมูลนี้กับบุคคลอื่น บิ๊กซีขอสงวนสิทธิ์ที่จะไม่รับผิดชอบต่อการสูญหายของ Pin code หรือบัตรกำนัลไม่ว่ากรณีใด ๆ ทั้งสิ้น</div>';
        }

        if (count(Rareplay_Sales_Model_Service_Quote::$storeTypeList) > 1) {
            $allTotalPrice = Rareplay_Sales_Model_Service_Quote::$allTotalPrice;
            $parameter_email['allTotalPrice'] = '฿' . number_format($allTotalPrice, 2, '.', ',');
        }

        $mailer->setTemplateParams($parameter_email);
        $mailer->send();


        // ======================= 2nd EMAIL ==========================
        $mailer = Mage::getModel('core/email_template_mailer');
        $emailInfo = Mage::getModel('core/email_info');
        $emailInfo->addTo($storeEmail);
//       $emailInfo->addTo('raggyboy@gmail.com');
        if ($copyTo && $copyMethod == 'bcc') {
            // Add bcc to customer email
            foreach ($copyTo as $email) {
                $emailInfo->addBcc($email);
            }
        }
        $mailer->addEmailInfo($emailInfo);

        // Email copies are sent as separated emails if their copy method is 'copy'
        if ($copyTo && $copyMethod == 'copy') {
            foreach ($copyTo as $email) {
                $emailInfo = Mage::getModel('core/email_info');
                $emailInfo->addTo($email);
                $mailer->addEmailInfo($emailInfo);
            }
        }

        // Set all required params and send emails
        $mailer->setSender(Mage::getStoreConfig(self::XML_PATH_EMAIL_IDENTITY, $storeId));
        $mailer->setStoreId($storeId);
        $mailer->setTemplateId($templateId);
        $parameter_email = array(
            'order' => $this,
            'billing' => $this->getBillingAddress(),
            'payment_html' => $paymentBlockHtml,
            'shipping_time_period' => $shipping_time_period,
        );

        if ($store_name != '') {
            $parameter_email['store_name'] = $store_name;
        }

        if ($arr_code['code1']) {
            $parameter_email['gvm_code'] = '<div>รหัสสำหรับใช้ขายบัตรกำนัล(สำหรับสาขา) : <span style="font-weight: bold; color: #320bee;">' . $arr_code['code1'] . '</span></div>';
        }

        if (count(Rareplay_Sales_Model_Service_Quote::$storeTypeList) > 1) {
            $allTotalPrice = Rareplay_Sales_Model_Service_Quote::$allTotalPrice;
            $parameter_email['allTotalPrice'] = '฿' . number_format($allTotalPrice, 2, '.', ',');
        }
        $mailer->setTemplateParams($parameter_email);

        $mailTemplate = Mage::getModel('core/email_template');
        $mailTemplate->addAttachment();

        $mailer->send();
        // ======================= 2nd EMAIL ==========================


        // ******************************* EMAIL To Supplier product normal ***************

        $pid_list = array();
        foreach ($this->getAllItems() as $item) {
            if ($item->getProduct()) {
                $pid = $item->getProduct()->getId();
            } else {
                $pid = $item->getProductId();
            }

            $pid_list[] = $pid;
        }

        $supplier_product_normal = $this->get_supplier_normal_product($pid_list);

        foreach ($supplier_product_normal as $supplier_code => $email) {
            //     $this->sendEmailSupplierNormalProduct($email, $templateId, $paymentBlockHtml);

            $mailer = Mage::getModel('core/email_template_mailer');
            $emailInfo = Mage::getModel('core/email_info');
            $emailInfo->addTo($email);
            $mailer->addEmailInfo($emailInfo);

            // Set all required params and send emails
            $mailer->setSender(Mage::getStoreConfig(self::XML_PATH_EMAIL_IDENTITY, $storeId));
            $mailer->setStoreId($storeId);
            $mailer->setTemplateId($templateId);
            $parameter_email = array(
                'order' => $this,
                'billing' => $this->getBillingAddress(),
                'payment_html' => $paymentBlockHtml,
            );
            if (count(Rareplay_Sales_Model_Service_Quote::$storeTypeList) > 1) {
                $allTotalPrice = Rareplay_Sales_Model_Service_Quote::$allTotalPrice;
                $parameter_email['allTotalPrice'] = '฿' . number_format($allTotalPrice, 2, '.', ',');
            }
            $mailer->setTemplateParams($parameter_email);

            $mailTemplate = Mage::getModel('core/email_template');
            $mailTemplate->addAttachment();

            $mailer->send();
        }


        // ******************************* EMAIL To Supplier product normal ***************

        $this->setEmailSent(true);
        $this->_getResource()->saveAttribute($this, 'email_sent');

        return $this;
    }


    /**
     * Send email with order update information
     *
     * @param boolean $notifyCustomer
     * @param string $comment
     * @return Mage_Sales_Model_Order
     */
    public function sendOrderUpdateEmail($notifyCustomer = true, $comment = '')
    {
        $storeId = $this->getStore()->getId();

        if (!Mage::helper('sales')->canSendOrderCommentEmail($storeId)) {
            return $this;
        }
        // Get the destination email addresses to send copies to
        $copyTo = $this->_getEmails(self::XML_PATH_UPDATE_EMAIL_COPY_TO);
        $copyMethod = Mage::getStoreConfig(self::XML_PATH_UPDATE_EMAIL_COPY_METHOD, $storeId);
        // Check if at least one recepient is found
        if (!$notifyCustomer && !$copyTo) {
            return $this;
        }

        // Retrieve corresponding email template id and customer name
        if ($this->getCustomerIsGuest()) {
            $templateId = Mage::getStoreConfig(self::XML_PATH_UPDATE_EMAIL_GUEST_TEMPLATE, $storeId);
            $customerName = $this->getBillingAddress()->getName();
        } else {
            $templateId = Mage::getStoreConfig(self::XML_PATH_UPDATE_EMAIL_TEMPLATE, $storeId);
            $customerName = $this->getCustomerName();
        }

        $mailer = Mage::getModel('core/email_template_mailer');
        if ($notifyCustomer) {
            $emailInfo = Mage::getModel('core/email_info');
            $emailInfo->addTo($this->getCustomerEmail(), $customerName);
            if ($copyTo && $copyMethod == 'bcc') {
                // Add bcc to customer email
                foreach ($copyTo as $email) {
                    $emailInfo->addBcc($email);
                }
            }
            $mailer->addEmailInfo($emailInfo);
        }

        // Email copies are sent as separated emails if their copy method is 'copy' or a customer should not be notified
        if ($copyTo && ($copyMethod == 'copy' || !$notifyCustomer)) {
            foreach ($copyTo as $email) {
                $emailInfo = Mage::getModel('core/email_info');
                $emailInfo->addTo($email);
                $mailer->addEmailInfo($emailInfo);
            }
        }

        // Set all required params and send emails
        $mailer->setSender(Mage::getStoreConfig(self::XML_PATH_UPDATE_EMAIL_IDENTITY, $storeId));
        $mailer->setStoreId($storeId);
        $mailer->setTemplateId($templateId);
        $mailer->setTemplateParams(array(
                'order' => $this,
                'comment' => $comment,
                'billing' => $this->getBillingAddress()
            )
        );
        $mailer->send();

        // ======================= 2nd EMAIL ==========================
        $mailer = Mage::getModel('core/email_template_mailer');
        $emailInfo = Mage::getModel('core/email_info');
        $emailInfo->addTo($this->getStoreEmail());
        $mailer->addEmailInfo($emailInfo);
        // Set all required params and send emails
        $mailer->setSender(Mage::getStoreConfig(self::XML_PATH_UPDATE_EMAIL_IDENTITY, $storeId));
        $mailer->setStoreId($storeId);
        $mailer->setTemplateId($templateId);
        $mailer->setTemplateParams(array(
                'order' => $this,
                'comment' => $comment,
                'billing' => $this->getBillingAddress()
            )
        );
        $mailer->send();

        // ======================= 2nd EMAIL ==========================

        return $this;
    }
}
