<?php

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

class Callme_site extends \Ciext\Controller\AbstractJsonController
{

    public function __construct()
    {
        $this->load->library('form_hash');
        $this->lang->load('callme/site');
        $this->load->config('callme/captcha');
        $this->load->model('callme/captcha_tmodel');
        $this->form_hash->time_point = 3;
    }

    public function index()
    {
        $this->load->config('callme/config');
        $this->lang->load('callme/site');
        $this->load->helper('form');

        $content = [
            'form_open'  => form_open('/ajax/callme/callme_site/add', ['id' => 'feedbackForm']),
            'hash'       => $this->form_hash->set_form_hash(),
            'ln_info'    => $this->lang->line('ln_info'),
            'ln_name'    => $this->lang->line('ln_name'),
            'ln_email'   => $this->lang->line('ln_email'),
            'ln_phone'   => $this->lang->line('ln_phone'),
            'ln_text'    => $this->lang->line('ln_text'),
            'ln_send'    => $this->lang->line('ln_send'),
            'form_close' => form_close(),
            'captcha'    => '',
        ];

        if ($this->config->item('captcha_enable')) {
            $content['captcha'] = $this->parser->parse('callme/captcha', ['captcha' => $this->captcha_tmodel->new_captcha()], TRUE);
        }

        return $this->parser->parse('callme/template', $content, TRUE);
    }

    public function add()
    {
        $c_enable = $this->config->item('captcha_enable');
        if ($c_enable && !$this->captcha_tmodel->check_captcha()) {

            return $this->response([
                        'success' => false,
                        'type'    => 'captcha',
                        'message' => $this->lang->line('ln_captcha_error'),
                        'image'   => $this->captcha_tmodel->new_captcha()['image'],
            ]);
        }

        $this->load->model('callme/callme_model');
        $rs = array(
            'success' => $this->form_hash->check_form_hash() ? intval($this->callme_model->add() > 0) : 0,
            'hash'    => $this->form_hash->set_form_hash(),
            'image'   => $c_enable ? $this->captcha_tmodel->new_captcha()['image'] : '',
        );

        return $this->response($rs);
    }

}
