<?php

require('includes/application_top_main.php');
#error_reporting(E_ALL);

if($_GET['action']) $fromOrderAction = $_GET['action'];
if($_GET['orders_id']) $order_id = $_GET['orders_id'];
if($_GET['language']) $language = $_GET['language'];
if($_GET['return_info']) $return_info = $_GET['return_info'];
if($language == '') $language = 'de';

/**
 * @var AORGOrderController $orderController
 */
/**
 * @var AORGMailer $mailer
 */
$orderController = MainFactory::create_object('AORGOrderController');
$tableController = $orderController->getTableController();
$mailer = MainFactory::create_object('AORGMailer');

$date_now = new DateTime();
switch($fromOrderAction){
    case 'send_mail':
        $order = $orderController->getOrder($order_id);
        $rating_link = $tableController->getRatingInvitationUrl($order_id,"af");
        $mail_html = $mailer->createMail($order,$orderController->getOrdersProducts($order['orders_id']),$rating_link, $language);
        $mailer->sendMessage($tableController->get_config('AORG_MAIL_ABSENDER'),$order['customers_email_address'],"",$tableController->get_config('AORG_MAIL_BETREFF'),$mail_html);
        $orderController->setMailingList($order_id,'af',$rating_link);
        break;
    case 'start_auto_mailer':
        $count_send = 0;
        $orders = $orderController->getOrders();
        $mails  = $orderController->getMailList();

        for($i=0;$i<sizeof($orders);$i++){
            $is_sended = array_key_exists($orders[$i]['orders_id'],$mails);
            if($is_sended) $is_sended = $mails[$orders[$i]['orders_id']]['send_as_af'];

            if(!$is_sended){ // Bestellung mit af wurde nicht gesendet
                $date_purchased = new DateTime($orders[$i]['date_purchased']);
                $date_purchased = $date_purchased->modify('+'.$tableController->get_config('AORG_SEND_MAIL_AFTER_X_DAYS').' days');
                if($date_now->getTimestamp() > $date_purchased->getTimestamp()){ // HEUTE > (Kaufdatum + AORG_SEND_MAIL_AFTER_X_DAYS)
                    $rating_link = $tableController->getRatingInvitationUrl($orders[$i]['orders_id'],"af");
                    $mail_html = $mailer->createMail($orders[$i],$orderController->getOrdersProducts($orders[$i]['orders_id']),$rating_link, $language);
                    $mailer->sendMessage($tableController->get_config('AORG_MAIL_ABSENDER'),$orders[$i]['customers_email_address'],"",$tableController->get_config('AORG_MAIL_BETREFF'),$mail_html);
                    $orderController->setMailingList($orders[$i]['orders_id'],'af',$rating_link);
                    $count_send++;
                }
            }
        }
        if($return_info) echo ($count_send);
        break;
}

