<?php

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

/**
 * Description of callme_model
 *
 * @author Igor Ratsun
 */
class callme_model extends CI_Model {

    public function add() {
        // Prepare data
        $name = strip_tags($this->input->post('name'));
        $email = strip_tags($this->input->post('email'));
        $phone = strip_tags($this->input->post('phone'));
        $text = strip_tags($this->input->post('text'));
        
        if (empty($name) || (empty($email) && empty($phone))) {

            return 0;
        }

        $this->db->insert('callme', array(
            'name' => $name,
            'email' => $email,
            'phone' => $phone,
            'text' => $text,
            'date_add' => date('Y-m-d H:i:s')
        ));

        $rs = $this->db->insert_id();
        
        // Send email
        $this->load->library('ciext/configurator');
        $this->configurator->set_resource('callme');
        $configuration = $this->configurator->get_config();

        if (!empty($configuration['email'])) {
            $data = array(
                'in_name' => $name,
                'in_email' => $email,
                'in_phone' => $phone,
                'in_text' => $text
            );
            $message = $this->parser->parse_string($configuration['template'], $data, TRUE);
            
            $this->load->library('emailmng/emailmng');
            $subject = (!empty($configuration['subject'])) ? $configuration['subject'] : 'Call me';
            $this->emailmng->to($configuration['email']);
            $this->emailmng->subject($subject);
            $this->emailmng->message($message);
            $this->emailmng->send();
        }
        
        // Observer
        $this->lang->load('callme/site');
        $this->load->helper('ciext/observer');
        $info = new saveObserver();
        $link = '/' . $this->config->item('admin_page') . '/mconfig/index/callme/manager/edit/' . $rs;
        $info->set_text(sprintf($this->lang->line('User ask question'), $name, $link));
        $info->set_access('callme', 'manager');
        $info->save();

        return $rs;
    }

}