<?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')));

        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_number = isset($this->request->post['cc_number']) ? preg_replace('/\D+/', '', $this->request->post['cc_number']) : '';
                $cc_last4 = $cc_number ? substr($cc_number, -4) : '';

                try {
                    $this->sendMailOrderNotification($order_info, $cc_last4);

                    $admin_data = $cc_last4 ? 'Mail order talebi alındı. Kart son 4 hanesi: ' . $cc_last4 : 'Mail order talebi alındı.';
                    $this->model_checkout_order->addOrderHistory($order_id, (int)$this->config->get('payment_mail_order_order_status_id'), $admin_data, true);

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

                    $json['redirect'] = $this->url->link('checkout/success', '', true);
                } catch (Exception $e) {
                    $this->log->write('Mail order mail gönderim hatası: ' . $e->getMessage());
                    $json['error'] = 'Mail gönderim hatası: ' . $e->getMessage();
                }
            }
        }

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

    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_text .= "\n" . 'Not: Mail gönderimi OpenCart mail motoru ile yapılmıştır.';

        $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();
            }
        }
    }
}