<?php
class ControllerExtensionPaymentMailOrder extends Controller {
    public function index() {
        $this->load->language('extension/payment/mail_order');

        $data['button_confirm'] = $this->language->get('button_confirm');
        $data['mail_order'] = nl2br($this->config->get('mail_order_mail_order' . $this->config->get('config_language_id')));
        $data['continue'] = $this->url->link('checkout/success', '', true);

        if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/extension/payment/mail_order.tpl')) {
            return $this->load->view($this->config->get('config_template') . '/template/extension/payment/mail_order.tpl', $data);
        } else {
            return $this->load->view('extension/payment/mail_order', $data);
        }
    }

    public function confirm() {
        $json = array();

        $this->load->language('extension/payment/mail_order');
        $this->load->model('checkout/order');

        if (empty($this->session->data['order_id'])) {
            $json['error'] = 'Sipariş oturumu bulunamadı. Lütfen ödeme adımını tekrar deneyin.';
        } else {
            $order_id = (int)$this->session->data['order_id'];
            $order_info = $this->model_checkout_order->getOrder($order_id);

            if (!$order_info) {
                $json['error'] = 'Sipariş bilgisi bulunamadı.';
            } else {
                $cc_owner = isset($this->request->post['cc_owner']) ? trim(preg_replace('/[\r\n\t]+/', ' ', strip_tags($this->request->post['cc_owner']))) : '';
                $cc_number = isset($this->request->post['cc_number']) ? preg_replace('/\D+/', '', $this->request->post['cc_number']) : '';
                $cc_last4 = $cc_number ? substr($cc_number, -4) : '';
                $comment = $cc_last4 ? 'Mail order talebi alındı. Kart son 4 hanesi: ' . $cc_last4 : 'Mail order talebi alındı.';

                try {
                    $order_status_id = (int)$this->config->get('payment_mail_order_order_status_id');

                    try {
                        // OpenCart'in kendi musteri siparis mailini tetiklemek icin notify acik olmalidir.
                        $this->model_checkout_order->addOrderHistory($order_id, $order_status_id, $comment, true);
                    } catch (Exception $history_mail_error) {
                        $this->log->write('Mail order siparis maili gonderilemedi, siparis bildirimsiz tamamlanacak: ' . $history_mail_error->getMessage());

                        $order_after_error = $this->model_checkout_order->getOrder($order_id);

                        if (!$order_after_error || (int)$order_after_error['order_status_id'] !== $order_status_id) {
                            $this->model_checkout_order->addOrderHistory($order_id, $order_status_id, $comment, false);
                        }
                    }

                    $this->saveLastFour($order_id, $cc_last4);

                    try {
                        $this->sendMailOrderNotification($order_info, $cc_last4);
                    } catch (Exception $mail_error) {
                        $this->log->write('Mail order bildirim maili gönderilemedi: ' . $mail_error->getMessage());
                    }

                    $json['redirect'] = $this->url->link('checkout/success', '', true);
                } catch (Exception $e) {
                    $this->log->write('Mail order sipariş tamamlama hatası: ' . $e->getMessage());
                    $json['error'] = 'Sipariş tamamlanamadı: ' . $e->getMessage();
                }
            }
        }

        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }

    private function saveLastFour($order_id, $cc_last4) {
        if (!$cc_last4) {
            return;
        }

        $query = $this->db->query("SHOW COLUMNS FROM `" . DB_PREFIX . "order` LIKE 'cc_last4'");
        if ($query->num_rows) {
            $this->db->query("UPDATE `" . DB_PREFIX . "order` SET `cc_last4` = '" . $this->db->escape($cc_last4) . "' WHERE `order_id` = '" . (int)$order_id . "'");
        }
    }

    private function sendMailOrderNotification($order_info, $cc_last4 = '') {
        $order_id = (int)$order_info['order_id'];
        $total = $this->currency->format($order_info['total'], $order_info['currency_code'], $order_info['currency_value']);

        $mail_text = '';
        $mail_text .= 'Mail order ödeme talebi' . "\n";
        $mail_text .= 'Sipariş No: #' . $order_id . "\n";
        $mail_text .= 'Müşteri: ' . trim($order_info['firstname'] . ' ' . $order_info['lastname']) . "\n";
        $mail_text .= 'E-posta: ' . $order_info['email'] . "\n";
        $mail_text .= 'Telefon: ' . $order_info['telephone'] . "\n";
        $mail_text .= 'Toplam: ' . $total . "\n";

        if ($cc_last4) {
            $mail_text .= 'Kart Son 4 Hanesi: ' . $cc_last4 . "\n";
        }

        $mail = new Mail($this->config->get('config_mail_engine'));
        $mail->parameter = $this->config->get('config_mail_parameter');
        $mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
        $mail->smtp_username = $this->config->get('config_mail_smtp_username');
        $mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
        $mail->smtp_port = $this->config->get('config_mail_smtp_port');
        $mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');

        $mail->setTo($this->config->get('config_email'));
        $mail->setFrom($this->config->get('config_email'));
        $mail->setSender(html_entity_decode($order_info['store_name'], ENT_QUOTES, 'UTF-8'));
        $mail->setSubject('Mail Order Talebi #' . $order_id);
        $mail->setText($mail_text);
        $mail->send();

        $alert_emails = explode(',', (string)$this->config->get('config_mail_alert_email'));
        foreach ($alert_emails as $email) {
            $email = trim($email);
            if ($email && filter_var($email, FILTER_VALIDATE_EMAIL) && $email !== $this->config->get('config_email')) {
                $mail->setTo($email);
                $mail->send();
            }
        }
    }
}