<?php

class Recaptcha
{
    /**
     * @param string $token_id
     * @return html tag input and all included javascript files
     */
    public function token_input($token_id = 're_token')
    {
        $ci = get_instance();
        $site_key = $ci->load->library('ciext/configurator')->set_resource('system')->item('recaptcha_site_key');
        $ci->js_css->add_js('https://www.google.com/recaptcha/api.js?render=' . $site_key);
        $ci->js_css->parse_js('recaptcha/init.js', ['site_key' => $site_key, 'token_id' => $token_id]);
        $ci->load->helper('html');

        return form_input([
            'type' => 'hidden',
            'name' => $token_id,
        ]);
    }

    /**
     * @param string $token if empty than will get value from $_POST['re_token']
     * @return bool
     */
    public function is_valid_token($token = '')
    {
        $ci = get_instance();
        $secret_key = $ci->load->library('ciext/configurator')->set_resource('system')->item('recaptcha_secret_key');

        $params = [
            'secret'   => $secret_key,
            'response' => empty($token) ? $ci->input->post('re_token') : $token,
            'remoteip' => $ci->input->ip_address(),
        ];

        $ch = curl_init('https://www.google.com/recaptcha/api/siteverify');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $response = curl_exec($ch);

        $data = json_decode($response, true);

        return isset($data['success']) && $data['success'] == 1;
    }
}