 <?php

    // defined('BASEPATH') or exit('No direct script access allowed');

    if (!option_exists('zapier_client_secret_key')) {
        $client_secret = bin2hex(random_bytes(32));
        update_option('zapier_client_secret_key', $client_secret);
    }

    $CI = &get_instance();
    $uris = $CI->config->item('csrf_exclude_uris');

    if (!empty($uris) && is_array($uris) && !in_array("zapier/api\/.+", $uris)) {

        $myfile = fopen(APPPATH . "config/config.php", "a") or die("Unable to open file!");
        $txt = "if(!isset(\$config['csrf_exclude_uris'])) { \$config['csrf_exclude_uris']=[]; }";
        fwrite($myfile, "\n" . $txt);
        $txt = "\$config['csrf_exclude_uris'] = array_merge(\$config['csrf_exclude_uris'],array('zapier/api\/.+'));";
        fwrite($myfile, "\n" . $txt);
        fclose($myfile);
    }



    if (!$CI->db->table_exists(db_prefix() . 'zapier_hooks')) {
        $CI->db->query('CREATE TABLE `' . db_prefix() . "zapier_hooks` (
            `id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
            `functionality` VARCHAR(250) NOT NULL,
            `hook` VARCHAR(250) NOT NULL,
            `created_at` datetime DEFAULT NULL,
            PRIMARY KEY (`id`)
          ) ENGINE=InnoDB DEFAULT CHARSET=" . $CI->db->char_set . ';');
    }

    if (!$CI->db->field_exists('subscribe_id', 'zapier_hooks')) {
        $CI->db->query('ALTER TABLE `' . db_prefix() . 'zapier_hooks` ADD COLUMN `subscribe_id` VARCHAR(250) DEFAULT NULL');
    }


    ?>