<?php

class Payment extends Public_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->helper(array(
            'payment/paypal',
            'payment/payu',
            'payment/ccavenue',
            'cart/cart',
            'file'
        ));
        $this->load->model(array(
            'order/order_model',
            'payment/payment_model'
        ));
        $this->load->library(array(
            'Dmailer',
            'safe_encrypt'
        ));
        $this->lang->load('portuguese', 'portuguese');
        $this->page_section_ct = 'common';
    }

    public function index()
    {
        $payMode = str_replace('.html', '', $this->input->get_post('pay_method'));

        if ($payMode == "payu") {
            $working_order_id = $this->session->userdata('working_order_id');
            $order_res = $this->order_model->get_order_master($working_order_id);
            payuForm($order_res);
        } elseif ($payMode == "COD") {
            $this->pay_by_check();
        } elseif ($payMode == "CCAvenue") {
            $data = array(
                'payment_method' => $payMode,
                'payment_status' => 'Unpaid'
            );
            $ordId = $this->session->userdata('working_order_id');
            $where = "order_id = '" . $ordId . "' ";
            $order_res = $this->order_model->get_order_master($ordId);
            ccavenueForm($order_res);
        } else {
            $data = array(
                'payment_method' => $payMode,
                'payment_status' => 'Unpaid'
            );
            $ordId = $this->session->userdata('working_order_id');
            $where = "order_id = '" . $ordId . "' ";
            $order_res = $this->order_model->get_order_master($ordId);
            paypalForm($order_res);
        }
    }

    // ccavenue handler
    public function ccavRequestHandler()
    {
        $data = array();
        $this->load->view('payment/ccavRequestHandler', $data);
    }

    public function pay_by_check()
    {
        $data = array(
            'payment_method' => 'Cash',
            'payment_status' => 'Unpaid'
        );
        $ordId = $this->session->userdata('working_order_id');
        $where = "order_id = '" . $ordId . "' ";
        $this->payment_model->safe_update('wps_order', $data, $where, FALSE);

        // update stock
        $orders = $this->db->query("SELECT store, products_id, quantity FROM wps_orders_products WHERE " . $where)->result_array();
        foreach ($orders as $ord) {
            $qty = $ord['quantity'];
            $this->db->query("UPDATE wps_product_attributes SET quantity=quantity-$qty WHERE store_id = '" . $ord['store'] . "' AND product_id = '" . $ord['products_id'] . "'");
        }
        // End here

        $res = get_db_field_value('wps_order', 'order_id', array(
            'order_id' => $ordId
        ));
        $ordmaster = $this->order_model->get_order_master($res);
        $orddetail = $this->order_model->get_order_detail($res);
        if (is_array($ordmaster) && ! empty($ordmaster)) {

            $content = '';

            ob_start();
            $mail_subject = $this->config->item('site_name') . " Order Oerview";
            $from_email = $this->admin_info->admin_email;
            $from_name = $this->config->item('site_name');
            $mail_to = $ordmaster['email'];
            $body = invoice_content_print($ordmaster, $orddetail);
            $content .= ob_get_contents();
            $content .= '<table width="1024" border="0" cellpadding="0" cellspacing="0" style="padding:10px;">
    <tr>
      <td colspan="2" style="">If you have any questions contact us here or call us Mcel 833055555, Voda 853055555, Movitel 873055555.<br /><br />
      We are here to help!<br />
      Thank you,<br />
      TEAM MERCADOMOZ
      </td>
      </tr>
      </table>';

            $mail_conf = array(
                'subject' => $this->config->item('site_name') . " Order overview",
                'to_email' => $mail_to,
                'from_email' => $from_email,
                'from_name' => $this->config->item('site_name'),
                'body_part' => $content
            );
            // trace($mail_conf); die;
            $this->dmailer->mail_notify($mail_conf);
        }
        $this->session->unset_userdata(array(
            'discount_amount' => 0
        ));
        $condition = "&& order_id='" . $ordId . "'";
        $cupn = $this->order_model->get_orders(0, 1, $condition);
        $cupn = $cupn[0];
        $ordId = md5($ordId);

        redirect('payment/thanks/' . $ordId, '');
    }

    public function order_success()
    {

        // trace($_POST);
        // die
        $response = json_encode($_POST);
        $ordId = $this->uri->segment(3);
        $content = "";

        if ($_POST['unmappedstatus'] == 'captured' && $_POST['status'] == 'success') {

            $this->session->unset_userdata(array(
                'discount_amount' => 0
            ));
            // update payment status
            $data = array(
                'payment_method' => 'PayuMoney',
                'payment_status' => 'Paid',
                'paymentResponse' => $response
            );
            $where = "MD5(order_id) = '$ordId' ";
            $this->payment_model->safe_update('wps_order', $data, $where, FALSE);
            // echo_sql();
            // exit;

            $res = get_db_field_value('wps_order', 'order_id', array(
                'MD5(order_id)' => $ordId
            ));
            $ordmaster = $this->order_model->get_order_master($res);
            $orddetail = $this->order_model->get_order_detail($res);
            if (is_array($ordmaster) && ! empty($ordmaster)) {
                ob_start();
                $mail_subject = $this->config->item('site_name') . " Order Oerview";
                $from_email = $this->admin_info->admin_email;
                $from_name = $this->config->item('site_name');
                $mail_to = $ordmaster['email'];
                $body = invoice_content_print($ordmaster, $orddetail);
                $msg = ob_get_contents();

                $mail_conf = array(
                    'subject' => $this->config->item('site_name') . " Order overview",
                    'to_email' => $mail_to,
                    'from_email' => $from_email,
                    'from_name' => $this->config->item('site_name'),
                    'body_part' => $msg
                );
                $this->dmailer->mail_notify($mail_conf);

                $mail_conf_admin = array(
                    'subject' => $this->config->item('site_name') . " Order Received",
                    'to_email' => 'support@webpulseindia.com',
                    'from_email' => $from_email,
                    'from_name' => $this->config->item('site_name'),
                    'body_part' => $msg
                );
                $this->dmailer->mail_notify($mail_conf_admin);

                // update membership
                $mres = $this->db->query("select * from wps_customers WHERE customers_id = '" . $this->session->userdata('user_id') . "'")
                    ->row_array();
                if (is_array($mres) && ! empty($mres)) {
                    if ($mres['is_manufacturer'] == '1') {
                        $mstartDate = $mendDate = '0000-00-00';
                        $mstartDate = date('Y-m-d');
                        $mendDate = date('Y-m-d', strtotime('+1 year'));
                        $data = array(
                            'membershipType' => (int) $this->session->userdata('pakage_id'),
                            'membershipStartDate' => $mstartDate,
                            'membershipEndDate' => $mendDate
                        );
                        $where = "customers_id = '" . $mres['customers_id'] . "' ";
                        $this->payment_model->safe_update('wps_customers', $data, $where, FALSE);
                    }
                    //mail to user for paid membership activation.
                    $content = file_get_contents(site_url().'mailer/email-paid-membership.html');
                    $subject = 'Welcome to Natural Therapy India';
                    $body = $content;
                    $name = $ordmaster['first_name'].' '.$ordmaster['last_name'];
                    $body = str_replace('{mem_name}', $name, $body);
                    $body = str_replace('{admin_email}', $this->admin_info->admin_email, $body);
                    $body = str_replace('{site_name}', $this->config->item('site_name'), $body);
                    //$body = str_replace('{url}', base_url(), $body);
                    //$body = str_replace('{link}', $verify_url, $body);
                    
                    $mail_conf = array(
                        'subject' => $subject,
                        'to_email' => $ordmaster['email'],
                        'from_email' => $this->admin_info->admin_email,
                        'from_name' => $this->config->item('site_name'),
                        'body_part' => $body
                    );
                    //trace($mail_conf);
                    //exit;
                    $this->dmailer->mail_notify($mail_conf);
                    //mail end here
                }
                // End Here

                $this->session->set_flashdata('msg', $this->config->item('payment_success'));
                redirect('payment/thanks/' . $ordId, '');
            }
        } else {
            $data = array(
                'paymentResponse' => $response
            );
            $where = "MD5(order_id) = '$ordId' ";
            $this->payment_model->safe_update('wps_order', $data, $where, FALSE);
            redirect('payment/order_cancle/' . $ordId, '');
        }
    }

    public function order_cancle()
    {
        $ordId = $this->uri->segment(3);
        $data = array(
            'order_status' => 'Canceled'
        );
        $where = "MD5(order_id) = '$ordId' ";
        $this->payment_model->safe_update('wps_order', $data, $where, FALSE);
        $this->session->unset_userdata(array(
            'working_order_id' => 0
        ));
        $this->session->unset_userdata(array(
            'discount_amount' => 0
        ));
        $this->session->set_flashdata('msg', $this->config->item('payment_failed'));
        redirect('payment/thanks/' . $ordId, '');
    }

    public function thanks()
    {
        $order_id = $this->uri->segment(3);
        $res = get_db_field_value('wps_order', 'order_id', array(
            'MD5(order_id)' => $order_id
        ));
        // trace($res);exit;

        if ($res > 0) {
            $data['title'] = "Invoice Print";
            $order_res = $this->order_model->get_order_master($res);
            // trace($order_res);
            $order_details_res = $this->order_model->get_order_detail($res);
            $data['orddetail'] = $order_details_res;
            $data['ordmaster'] = $order_res;
            $this->load->view('payment/pay_thanks', $data);
        }
    }
}

/* End of file member.php */
/* Location: .application/modules/products/controllers/cart.php */