<?php

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

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');
        $cnf = new configurator('system');
        $this->load->library('emailmng/emailmng')->initialize();
        $this->emailmng->to($cnf->item('admin_email'));
        $this->emailmng->send_template('callme_me_tpl', [], [
            'in_name'  => $name,
            'in_email' => $email,
            'in_phone' => $phone,
            'in_text'  => $text
        ]);
        
        // 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;
    }

}