<?php

GLOBAL $wpdb;

$sucess_alert = '<div class="alert alert-success alert-dismissible show" role="alert">{MESSAGE}<button type="button" class="close" data-bs-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button></div>';
$error_alert = '<div class="alert alert-danger alert-dismissible show" role="alert">{MESSAGE}<button type="button" class="close" data-bs-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button></div>';
$error_msg = [];
$result = "";
$result2 = "";

//NO POSTBACK, GENERAL LOAD
$wizard_options  = ftm_geo_target_getCurrentFields();

//GENERAL
if ( isset($_POST["sname"]) && strlen($_POST['sname']) > 0 && isset($_POST['sdescription']) && strlen($_POST['sdescription']) > 0 ){

    $insert = $wpdb->insert($wpdb->prefix . "ftm_geo_target_sites",
        array(
            'name'  => ($_POST["sname"]),
            'site_description' => (isset($_POST['sdescription'])?$_POST['sdescription']:''),
        ),
        array(
            '%s',
            '%s',
        )
    );


    if($wpdb->insert_id != false){
        if($wpdb->insert_id > 0){
            $result = true;
            $siteID = $wpdb->insert_id;
            $siteName = $_POST['sname'];
            // WPML
            if (function_exists ( 'wpml_register_single_string_action' )){
                do_action( 'wpml_register_string', $siteName, 'ftm_sitename_'.$siteID, [
                    'kind' => 'Site Fields',
                    'name' => 'site_'.$siteID,
                    'title' => 'Site '.$siteName,
                ], 'Site Name', 'LINE');
            }// \WPML

            //DETAILS
            foreach ($wizard_options as $woption){
                //$woption->optionid
                //$woption->fieldname

                $optionValue = $_POST[$woption->fieldname];
                if($optionValue)
                {
                    $values[] = $wpdb->prepare( "(%d,%d,%s)", $siteID, $woption->optionid, $optionValue );
                }
                // WPML
                if (function_exists ( 'wpml_register_single_string_action' ) && $woption->typename != 'picture'){
                    $package = [
                        'kind' => 'Site Fields',
                        'name' => 'site_'.$siteID,
                        'title' => 'Site '.$siteName,
                    ];
                    $matches = [];
                    $found_common_strings = preg_match_all('/\[\[([^\[\]]+)\]\]/', $value, $matches);
                    if ($found_common_strings) {
                        foreach ($matches[1] as $common_text) {
                            do_action( 'wpml_register_single_string', 'Site Fields', 'Common Text - '.$common_text, $common_text);
                        }
                    }
                    switch($woption->typename) {
                    case 'textbox':
                        $string_type = 'LINE';
                        $field_name = 'ftm_site_'.$siteID.'_'.$woption->fieldname;
                        do_action( 'wpml_register_string', $optionValue, $field_name, $package, $woption->fieldname, $string_type);
                        break;
                    case 'wysiwyg':
                        $string_type = 'VISUAL';
                        $field_name = 'ftm_site_'.$siteID.'_'.$woption->fieldname;
                        do_action( 'wpml_register_string', $optionValue, $field_name, $package, $woption->fieldname, $string_type);
                        break;
                    case 'geoValue':
                        $string_type = 'AREA';
                        //$geo_sets = json_decode(str_replace("\\", "", $optionValue), false);
                        $value = stripcslashes($value);
                        $geo_sets = json_decode($value, false);
                        foreach($geo_sets as $geo_set) {
                            $field_name = 'ftm_site_'.$siteID.'_'.$woption->fieldname.'_'.$geo_set->country;
                            do_action( 'wpml_register_string', $geo_set->value, $field_name, $package, $woption->fieldname .' ' .$geo_set->country, $string_type);
                        }
                    }
                }// \WPML
            }

            $query  = "INSERT INTO ". $wpdb->prefix . "ftm_geo_target_site_values(`siteid`, `siteoptionid`, `siteoptionvalue`) VALUES ";
            $query .= implode(",\n", $values);

            $insert = $wpdb->query($query);

            if($insert != false){
                $result = true;
                $siteInfo  = ftm_geo_target_sites_info($siteID);
                do_action("ftm_geo_target_add_site", $siteInfo);
            }
            else{
                $result = false;
            }
        }
        else {
            $result = false;
        }
    }
    else{
        $result = false;
    }
} else {
    if ( !isset($_POST['sname']) || strlen($_POST['sname']) == 0 ) {
        $error_msg[] = 'The description is required';
        $result = false;
    }
    if ( !isset($_POST['sdescription']) || strlen($_POST['sdescription']) == 0 ) {
        $error_msg[] = 'The description is required';
        $result = false;
    }
}

?>
<div class="wrap ftm_geo_target">

    <div id="icon-options-general" class="icon32"></div>
    <h1><?php esc_attr_e( 'Add New Site', 'wp_admin_style' ); ?></h1>

    <div id="poststuff">

        <div id="post-body" class="metabox-holder columns-2">

            <!-- main content -->
            <div id="post-body-content">

                <div class="ftm_geo_target">

                    <?php
                    if($result === true){
                        echo str_replace("{MESSAGE}","<strong>Cool!</strong> The site has been inserted. Check out the <a href='/wp-admin/admin.php?page=ftm-geo-target-sites/'>sites list</a> or <a href='/wp-admin/admin.php?page=ftm-geo-target-site-add'>add another one</a>.", $sucess_alert);
                    }elseif ($result === false){
                        foreach ($error_msg as $error) {
                            echo str_replace("{MESSAGE}", $error, $error_alert);
                        }
                    }
                    ?>

                    <div class="postbox">

                        <h2 class="hndle"><span><b><?php esc_attr_e( 'Step 1.', 'wp_admin_style' ); ?></b></span> General Site Info</h2>

                        <div class="inside">If you enclose a text between 2 sets of square brackets that text will be translatable as a common text. Example: [[bonus up]]</div>
                        <div class="inside">
                                <form method="post" action="" id="site_add_form" name="site_add_form">

                                    <div>
                                        Name: <input type="text" class="ftm_geo_target_big_input" name="sname" size="60"/>
                                        <hr/>
                                        Description: <input type="text" class="ftm_geo_target_big_input" name="sdescription" size="60"/>
                                        <hr/>
                                        <?php
                                         foreach ($wizard_options as $woption){
                                             echo ("<div class='field_name'>" . $woption->fieldname . "</div>");
                                             ftm_geo_target_htmlField($woption->typename, $woption->fieldname, $woption->fieldvalue);
                                         }
                                        ?>
                                    </div>

                                </form>
                        </div>

                    </div>
                    <!-- .postbox -->
                </div>
                <!-- .meta-box-sortables .ui-sortable -->

            </div>
            <!-- post-body-content -->

            <!-- sidebar -->
            <?php
            GLOBAL $ftm_geo_target_plugin_path;
            $sidebar_mode = "add";
            require_once $ftm_geo_target_plugin_path . '/includes/sidebar-sites-edit.php'
            ?>

        </div>

        <br class="clear">
    </div>

    <!-- #poststuff -->

</div> <!-- .wrap -->
