<?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

/**
 * Event for module Rtform_mail
 *
 * @author CIEXT skeleton
 */
class Rtform_mail_event implements SplObserver
{

    public function update(SplSubject $subject)
    {
        $event_name = $subject->get_event_name();
        if ($event_name == 'add') {
            $event_data = $subject->get_event_data();
            $ci = get_instance();
            $ci->load->model('rtform/rtform_tmodel');
            $ci->load->model('rtform/rtform_request_tmodel');
            $ci->load->model('emailmng/template_tmodel');

            $request_data = $ci->rtform_request_tmodel->fetch($event_data['id']);
            $decode_data = json_decode($request_data['data'], true);
            $form = $ci->rtform_tmodel->fetch($request_data['id_rtform']);

            // Send to recipients
            $rec_tpl = $ci->template_tmodel->fetch($form['recipients_template']);
            foreach (explode(',', $form['recipients']) as $email) {
                $ci->load->library('emailmng/emailmng')->initialize();
                $ci->emailmng->to(trim($email));
                $ci->emailmng->send_template($rec_tpl['code'], $decode_data, $decode_data);
            }

            // Send to reply
            if (!empty($form['reply_template']) && $ci->input->post('email')) {
                $rep_tpl = $ci->template_tmodel->fetch($form['reply_template']);
                $ci->load->library('emailmng/emailmng')->initialize();
                $ci->emailmng->to($ci->input->post('email'));
                $ci->emailmng->send_template($rep_tpl['code'], $decode_data, $decode_data);
            }
        }
    }

}
