<?php

GLOBAL $wpdb,$ftm_geo_target_plugin_path;

$wizard_options  = ftm_geo_target_getCurrentFields();
$sitesTable = $wpdb->prefix . "ftm_geo_target_sites";
$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 = "";

if(!isset($_POST["edits"]) && !isset($_POST["sid"]) ) {
    echo '<script type="text/javascript">
           window.location = "/wp-admin/admin.php?page=ftm-geo-target-sites";
      </script>';
}

if ( isset($_POST["edits"]) ){

    $siteID = $_POST["sedit"];

    if(!empty($siteID)){
        $siteInfo  = ftm_geo_target_sites_info($siteID);
    }
}

if ( isset($_POST["sid"]) ){

	$siteID             = $_POST["sid"];
    $siteName 			= $_POST["sname"];
    $siteDescription    = (isset($_POST['sdescription'])?$_POST['sdescription']:'');

    if(!empty($siteID) && !empty($siteName) && !empty($siteDescription)){

        $update = $wpdb->update($sitesTable,
            array(
                'name' 		            => $siteName,
                'site_description' => $siteDescription,
            ),
            array ('siteid' =>  $siteID),
            array(
                '%s',
                '%s',
            )
        );
        // 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

        if($update !== false){
            if(update_site_details($wpdb,$siteID, $wizard_options, $siteName) === true){
                $result = true;
                $siteInfo  = ftm_geo_target_sites_info($siteID);
                do_action("ftm_geo_target_update_site", $siteInfo);
            }
            else
            {
                $result = false;
                ftm_geo_target_jsLog("'-----'");
            }
        }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;
        }
    }

    $siteInfo  = ftm_geo_target_sites_info($siteID);
}

function update_site_details($wpdb,$siteID, $wizard_options, $siteName = ''){
    $result = true;

	if(!empty($siteID)){
	    foreach ($wizard_options as $woption){
            $check = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix."ftm_geo_target_site_values WHERE siteoptionid = " . $woption->optionid . " AND siteid = " . $siteID );

            if($_POST["$woption->fieldname"]){
                $value = $_POST[$woption->fieldname];

                if ( empty( $check ) ) {
                    $insert = $wpdb->insert( $wpdb->prefix."ftm_geo_target_site_values",
                        array(
                            'siteid'          => ( $siteID ),
                            'siteoptionid'    => ( $woption->optionid ),
                            'siteoptionvalue' => $value
                        ),
                        array(
                            '%d',
                            '%d',
                            '%s',
                        )
                    );

                } else {
                    $sql = $wpdb->update( $wpdb->prefix."ftm_geo_target_site_values",
                        array(
                            'siteoptionvalue' => $value,
                        ),
                        array( 'siteid' => $siteID, 'siteoptionid' => $woption->optionid ),
                        array(
                            '%s'
                        )
                    );
                }
                // 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', $value, $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', $value, $field_name, $package, $woption->fieldname, $string_type);
                        break;
                    case 'geoValue':
                        $string_type = 'AREA';
                        //$geo_sets = json_decode(str_replace("\\", "", $value), 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

                if ( $wpdb->last_error !== '' ) {
                    $result = false;
                    ftm_geo_target_jsLog("'".$wpdb->last_error."'");
                }else{
                    $result = true;
                }
            }
            else
            {
                //$result = false;
            }
        }
	}else{
		$result = false;
	}

	return $result;
}

require $ftm_geo_target_plugin_path . '/includes/modal-delete-form.php';
?>
<div class="wrap ftm_geo_target">

    <?php
    if ( $result === true ) {
        echo str_replace("{MESSAGE}","<strong>Cool!</strong> The site has been updated.", $sucess_alert);
    } elseif ( $result === false ) {
        foreach ($error_msg as $error) {
            echo str_replace("{MESSAGE}",$error, $error_alert);
        }
    }
    ?>

    <div id="icon-options-general" class="icon32"></div>
    <h1><?php esc_attr_e( 'Edit 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="meta-box-sortables ui-sortable">

                    <div class="postbox">

                        <?php
                        if(!empty($status)){
                            ?>
                            <div>
                                <div style="margin-top: 20px; padding: 0 .7em;" class="ui-state-highlight ui-corner-all">
                                    <p><span style="float: left; margin-right: .3em;" class="ui-icon ui-icon-info"></span>
                                        <?php print $status; ?>
                                    </p>
                                </div>
                            </div>
                        <?php } ?>

                        <h2 class="hndle"><span><b><?php esc_attr_e( 'General Site Info', 'wp_admin_style' ); ?></b></span></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="side_edit_form" name="side_edit_form">
                                    <input type="hidden" name="sid" value="<?php echo $siteID; ?>">
                                    <div>
                                        Name: <input type="text" value="<?php print $siteInfo[0]->name ?>" name="sname" size="60"/>
                                        <hr/>
                                        Description: <input type="text" value="<?php print isset($siteInfo[0]->site_description)?$siteInfo[0]->site_description:'' ?>" name="sdescription" size="60"/>
                                        <hr/>
                                        <span class="hndle"><b><?php esc_attr_e( 'Edit Site Details', 'wp_admin_style' ); ?></b></span>
                                        <?php
                                        foreach ($wizard_options as $woption){
                                            echo ("<div class='field_name'>" . $woption->fieldname . "</div>");
                                            $field_value = ftm_geo_target_getFieldValue( $siteInfo[0]->siteid,$woption->optionid);
                                            ftm_geo_target_htmlField($woption->typename, $woption->fieldname, $field_value);
                                        }
                                        ?>
                                    </div>

                                </form>
                        </div>

                    </div>

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

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

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

        </div>
        <!-- #post-body .metabox-holder .columns-2 -->

        <br class="clear">
    </div>
    <!-- #poststuff -->

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