<?php /*

 Composr
 Copyright (c) Christopher Graham, 2004-2024

 See docs/LICENSE.md for full licensing information.


 NOTE TO PROGRAMMERS:
   Do not edit this file. If you need to make changes, save your changed file to the appropriate *_custom folder
   **** If you ignore this advice, then your website upgrades (e.g. for bug fixes) will likely kill your changes ****

*/

/**
 * @license    http://opensource.org/licenses/cpal_1.0 Common Public Attribution License
 * @copyright  Christopher Graham
 * @package    catalogues
 */

/**
 * Block class.
 */
class Block_main_catalogues_form
{
    /**
     * Find details of the block.
     *
     * @return ?array Map of block info (null: block is disabled)
     */
    public function info() : ?array
    {
        $info = [];
        $info['author'] = 'Patrick Schmalstig';
        $info['organisation'] = 'PDStig, LLC';
        $info['hacked_by'] = null;
        $info['hack_version'] = null;
        $info['version'] = 1;
        $info['locked'] = false;
        $info['min_cms_version'] = 11.0;
        $info['addon'] = 'catalogues';
        $info['parameters'] = ['param', 'only_one', 'redirect', 'guid'];
        return $info;
    }

    /**
     * Find caching details for the block.
     *
     * @return ?array Map of cache details (cache_on and ttl) (null: block is disabled)
     */
    public function caching_environment() : ?array
    {
        $info = [];
        $info['cache_on'] = <<<'PHP'
        (post_param_string('_block_id', '') != '')
        ?
        null // No cache when submitting the form
        :
        [
            md5(get_ip_address() . ' ' . strval(get_member())), // Separate cache by member / IP so CAPTCHA works
            array_key_exists('param', $map) ? $map['param'] : '',
            array_key_exists('only_one', $map) ? $map['only_one'] : '',
            array_key_exists('guid', $map) ? $map['guid'] : '',
            array_key_exists('redirect', $map) ? $map['redirect'] : '',
        ]
PHP;
        $info['ttl'] = 60 * 24;
        return $info;
    }

    /**
     * Execute the block.
     *
     * @param  array $map A map of parameters
     * @return Tempcode The result of execution
     */
    public function run(array $map) : object
    {
        $error_msg = new Tempcode();
        if (!addon_installed__messaged('catalogues', $error_msg)) {
            return $error_msg;
        }

        require_code('fields');
        require_code('catalogues2');
        require_lang('catalogues');

        $text = new Tempcode();

        // Options...

        if (addon_installed('captcha')) {
            require_code('captcha');
            $use_captcha = ((get_option('captcha_on_feedback') == '1') && (use_captcha()));
        } else {
            $use_captcha = false;
        }

        if (@cms_empty_safe($map['param'])) {
            $catalogue_name = $GLOBALS['SITE_DB']->query_select_value_if_there('catalogue_categories', 'c_name', ['id' => db_get_first_id()]);
            if ($catalogue_name === null) {
                return do_template('RED_ALERT', ['_GUID' => '9acd95ab5376b10fc915f37352660702', 'TEXT' => do_lang_tempcode('MISSING_RESOURCE', 'catalogue')]);
            }
        } else {
            $catalogue_name = $GLOBALS['SITE_DB']->query_select_value_if_there('catalogues', 'c_name', ['c_name' => $map['param']]);
            if ($catalogue_name === null) {
                return do_template('RED_ALERT', ['_GUID' => 'c5cb67b3671126c856f09e9450b5a78f', 'TEXT' => do_lang_tempcode('MISSING_RESOURCE', 'catalogue')]);
            }
        }

        // If only_one, check if the member already submitted an entry
        if (isset($map['only_one']) && ($map['only_one'] == '1')) {
            if (is_guest(get_member())) {
                return do_template('RED_ALERT', ['_GUID' => 'cbb8b4f7e2ee46831cd79a51224cb627', 'TEXT' => do_lang_tempcode('permissions:ACCESS_DENIED__NOT_AS_GUEST')]);
            }

            $already_filled_in = $GLOBALS['SITE_DB']->query_select_value_if_there('catalogue_entries', 'id', ['c_name' => $catalogue_name, 'ce_submitter' => get_member()]);

            if ($already_filled_in !== null) {
                return do_template('RED_ALERT', ['_GUID' => '35a0bc49640864adf9d6d2e8a622a32d', 'TEXT' => do_lang_tempcode('ALREADY_SUBMITTED_CONTENT')]);
            }
        }

        $special_fields = $GLOBALS['SITE_DB']->query_select('catalogue_fields', ['*'], ['c_name' => $catalogue_name], 'ORDER BY cf_order,' . $GLOBALS['SITE_DB']->translate_field_ref('cf_name'));

        $guid = isset($map['guid']) ? $map['guid'] : '6092b1533f549abe94a764d88d89c66b';

        $block_id = md5(serialize($map));

        // Submission...
        if (post_param_string('_block_id', '') == $block_id) {
            // Check CAPTCHA
            if ($use_captcha) {
                enforce_captcha();
            }

            // Data
            $category_id = post_param_integer('catalogue_category');
            $c_map = [];
            foreach ($special_fields as $field_num => $field) {
                $ob = get_fields_hook($field['cf_type']);
                $inputted_value = $ob->inputted_to_field_value(false, $field);

                // Required field validation (a standard for all field hooks except tick)
                if (($field['cf_type'] != 'tick') && ($field['cf_required'] == 1) && (($inputted_value === null) || ($inputted_value == '') || (($inputted_value == STRING_MAGIC_NULL) && !fractional_edit()))) {
                    return do_template('RED_ALERT', ['_GUID' => 'ae4e4f4f2a3423bf141faa953ee8a705', 'TEXT' => do_lang_tempcode('_REQUIRED_NOT_FILLED_IN', get_translated_tempcode('catalogue_fields', $field, 'cf_name'))]);
                }

                if ($inputted_value !== null) {
                    $c_map[$field['id']] = $inputted_value;
                }
            }

            // Create catalogue entry which is not validated
            actual_add_catalogue_entry($category_id, 0, do_lang('CATALOGUE_ENTRY_VIA_BLOCK', 'main_catalogues_form'), 0, 0, 0, $c_map);

            // Redirect/messaging (we use redirect_exit because the only_once check already happened before adding the entry)
            require_code('site2');
            $redirect = array_key_exists('redirect', $map) ? $map['redirect'] : '';
            if ($redirect != '') {
                $redirect = page_link_to_url($redirect);
                redirect_exit($redirect, null, do_lang_tempcode('SUCCESS'));
            } else {
                redirect_exit(get_self_url(), null, do_lang_tempcode('SUCCESS'));
            }
        }

        // Form (note that this needs updated if changed in main_contact_catalogues)...

        require_code('form_templates');

        $fields = new Tempcode();

        $hidden = new Tempcode();

        if ($use_captcha) {
            $fields->attach(form_input_captcha($hidden));
            $text->attach(do_lang_tempcode('captcha:FORM_TIME_SECURITY'));
        }

        // Attach catalogue category selection field
        $fields->attach(form_input_tree_list(do_lang_tempcode('CATEGORY'), '', 'catalogue_category', null, 'choose_catalogue_category', ['catalogue_name' => $catalogue_name], true));

        $field_groups = [];

        url_default_parameters__enable();

        foreach ($special_fields as $field_num => $field) {
            $ob = get_fields_hook($field['cf_type']);

            $_cf_name = get_translated_text($field['cf_name']);
            $field_cat = '';
            if (strpos($_cf_name, ': ') !== false) {
                $field_cat = substr($_cf_name, 0, strpos($_cf_name, ': '));
                if ($field_cat . ': ' == $_cf_name) {
                    $_cf_name = $field_cat; // Just been pulled out as heading, nothing after ": "
                } else {
                    $_cf_name = substr($_cf_name, strpos($_cf_name, ': ') + 2);
                }
            }
            if (!array_key_exists($field_cat, $field_groups)) {
                $field_groups[$field_cat] = new Tempcode();
            }

            $_cf_description = escape_html(get_translated_text($field['cf_description']));

            $GLOBALS['NO_DEV_MODE_FULLSTOP_CHECK'] = true;
            $result = $ob->get_field_inputter($_cf_name, $_cf_description, $field, null, true, !array_key_exists($field_num + 1, $special_fields));
            $GLOBALS['NO_DEV_MODE_FULLSTOP_CHECK'] = false;

            if ($result === null) {
                continue;
            }

            if (is_array($result)) {
                $field_groups[$field_cat]->attach($result[0]);
            } else {
                $field_groups[$field_cat]->attach($result);
            }

            unset($result);
            unset($ob);
        }

        if (array_key_exists('', $field_groups)) { // Blank prefix must go first
            $field_groups_blank = $field_groups[''];
            unset($field_groups['']);
            $field_groups = array_merge([$field_groups_blank], $field_groups);
        }
        foreach ($field_groups as $field_group_title => $extra_fields) {
            if (is_integer($field_group_title)) {
                $field_group_title = ($field_group_title == 0) ? '' : strval($field_group_title);
            }

            if ($field_group_title != '') {
                $fields->attach(do_template('FORM_SCREEN_FIELD_SPACER', ['_GUID' => '19ac569b304134af6ad9589872cf8ef1', 'TITLE' => $field_group_title]));
            }
            $fields->attach($extra_fields);
        }

        url_default_parameters__disable();

        $hidden->attach(form_input_hidden('_block_id', $block_id));

        $url = get_self_url();

        return do_template('FORM', [
            '_GUID' => $guid,
            'FIELDS' => $fields,
            'HIDDEN' => $hidden,
            'SUBMIT_ICON' => 'buttons/send',
            'SUBMIT_NAME' => do_lang_tempcode('SEND'),
            'URL' => $url,
            'TEXT' => $text,
            'SECONDARY_FORM' => true,
        ]);
    }
}
