<?php

GLOBAL $wpdb;
$status = "";
$upload_status = "";
$upload_message = "";
$ip_lookup_result = "";
$db_update_needed = false;
$sucess_alert = '<div class="alert alert-success alert-dismissible show" role="alert">{MESSAGE}<button type="button" class="btn btn-secondary 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="btn btn-secondary close" data-bs-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button></div>';

$should_use_cache_info = get_option( 'ftmgt_use_cache_info', 1 );
$nginx_cache_plugin_active = class_exists("NginxCache");
$nginx_cache_path = get_option( 'nginx_cache_path' );
$nginx_cache_path_working = false;

if ($nginx_cache_plugin_active && strlen($nginx_cache_path)) {
    $nginx_cache_path_working = file_exists($nginx_cache_path) && is_dir($nginx_cache_path) && is_writeable($nginx_cache_path);
}
//$nginx_parameters = $_SERVER["COUNTRY_CODE"] || $_SERVER["CITY_CODE"];
$nginx_parameters = '';

$settings_values = null;

//UPDATE GENERAL SETTINGS

if (isset($_POST['clear_nginx'])) {
    function rrmdir($dir) {
        if (is_dir($dir)) {
            $objects = scandir($dir);
            foreach ($objects as $object) {
                if ($object != "." && $object != "..") {
                    if (is_dir($dir. DIRECTORY_SEPARATOR .$object) && !is_link($dir."/".$object))
                        rrmdir($dir. DIRECTORY_SEPARATOR .$object);
                    else
                        unlink($dir. DIRECTORY_SEPARATOR .$object);
                }
            }
            rmdir($dir);
        }
    }
    $objects = scandir($nginx_cache_path);
    foreach ($objects as $object) {
        rrmdir($object);
    }
}


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

    if(!isset($_POST["wordpress_bedrock_check"])){        
        update_option( 'ftmgt_bedrock_installation', '0' );
    }
    else
    {
        update_option( 'ftmgt_bedrock_installation', '1' );
    }
}
$wordpress_bedrock_installation = get_option( 'ftmgt_bedrock_installation', '1' );

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

    $dStatus = false;
    if(isset($_POST["debug_status_check"])) {
        if ($_POST["debug_status_check"] == "on") {
            $dStatus = '1';
        }
        else
        {
            $dStatus = '0';
        }
    }
    else
    {
        $dStatus = '0';
    }

    $update = $wpdb->query( $wpdb->prepare("UPDATE " . $wpdb->prefix . "ftm_geo_target_settings SET DebugStatus = %s WHERE DebugStatus IS NOT NULL", $dStatus) );

    if($update !== false){
        $status = true;
    }
    else
    {
        $status = false;
    }
}
if(isset($_SERVER['CONTENT_LENGTH'])){
    if(intval($_SERVER['CONTENT_LENGTH'])>0 && count($_POST)===0){
        // PHP discarded POST data because of request exceeding post_max_size
        $upload_status = false;
        $upload_message = "Sorry, your file is too large.";
    }
}

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

    $ftm_eo_files_path = WP_PLUGIN_DIR . '/ftm-geo-target/geo/';
    $ftm_geo_target_upload_path    = WP_PLUGIN_DIR . '/ftm-geo-target/uploads/';
    $target_dir = $ftm_geo_target_upload_path;
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $FileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// Check file size
    /*if ($_FILES["fileToUpload"]["size"] > 500000) {
        echo "Sorry, your file is too large.";
        $uploadOk = 0;
    }*/
// Allow certain file formats
    if($FileType != "zip") {
        $upload_message = "Error: Only ZIP files are allowed.";
        $uploadOk = 0;
    }
// Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        $upload_message = "Sorry, your file was not uploaded." . $upload_message;
        $upload_status = false;
// if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { //Upload the file to the uploads folder
            //unzip the file
            $zip = new ZipArchive;
            $res = $zip->open( $ftm_geo_target_upload_path . basename( $_FILES["fileToUpload"]["name"]));
            if ($res === TRUE) {
                $zip->extractTo($target_dir);
                $zip->close();
                //Check if the uploaded file is the right one
                $FileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
                //Delete the zip file
                unlink($ftm_geo_target_upload_path . basename( $_FILES["fileToUpload"]["name"]));

                // Check if correct file exists
                if (file_exists($target_dir . "GeoIP2-City.mmdb")) {

                    copy($target_dir . "GeoIP2-City.mmdb", $ftm_eo_files_path .'GeoIP2-City.mmdb');
                    ftm_geo_target_update_geoFile_updateDate();

                    //Set success message and status
                    $upload_message = "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
                    $upload_status = true;
                }
                else
                {
                    $upload_message = "Sorry, GeoIP2-City.mmdb file not found.";
                    $upload_status = false;
                }

                clear_directorys_files($target_dir);
            } else {
                $upload_message = "Sorry, there was an error uploading your file.";
                $upload_status = false;
            }

        } else {
            $upload_message = "Sorry, there was an error uploading your file.";
            $upload_status = false;
        }
    }
}

if(isset($_POST["local_ip_lookup"])){
  $test_ip_addtess = "";
    $ip_lookup_result = "IP not found";

  if(isset($_POST["ip_to_test"])){
      $test_ip_addtess = $_POST["ip_to_test"];
      $ip_lookup_result = ftm_geo_target_lookup_ip($test_ip_addtess);
  }

}

$settings_values = ftm_geo_target_getSettings();

function clear_directorys_files($folder){
    $files = glob($folder .'*'); //get all file names
    foreach($files as $file){
        if(is_file($file))
            unlink($file); //delete file
    }
}

?>

<?php
    if ( get_option( 'ftmgt_database_version' ) != FTM_GT_DB_VERSION ) {
        $db_update_needed = true;
    }
?>

<?php if(isset($_POST["v6_update"]) && $db_update_needed){
        $update_msg = '<div><strong>The plugin has been updated to support Ipv6, and the available regions have changed.</strong></div>';
        $update_msg .= ftm_gt_db_update();
        echo str_replace("{MESSAGE}", $update_msg, $sucess_alert);
        $db_update_needed = false;
}

?>

<?php
if($status !== "") {
    if ($status === true) {
        echo str_replace("{MESSAGE}", "<strong>Done!</strong> The plugin settings were successfully updated.", $sucess_alert);
    } elseif ($status === false) {
        echo str_replace("{MESSAGE}", "<strong>Oops!</strong> There was a problem updating the plugin settings, please contact support.", $error_alert);
    }
}

if($upload_status !== "") {

    if ($upload_status === true) {
        echo str_replace("{MESSAGE}", $upload_message, $sucess_alert);
    } elseif ($upload_status === false) {
        echo str_replace("{MESSAGE}", $upload_message, $error_alert);
    }
}

?>

<div class="wrap ftm_geo_target">
    <div id="icon-options-general" class="icon32"></div>
    <h1><?php esc_attr_e( 'FTM Geo Target Plugin Settings', 'wp_admin_style' ); ?></h1>
    <p><i><?php esc_attr_e('Here you can enable the debug setting and update the Geo Location File.', 'wp_admin_style'); ?></i></p>
    <div id="poststuff">
        <div id="post-body" class="metabox-holder columns-2">
            <!-- main content -->
            <div id="post-body-content">
                <?php if ($db_update_needed) { ?>

                    <form action=""  method="post">
                        <div class="postbox">
                            <h2 class="hndle"><b><?php esc_attr_e('Update Required', 'wp_admin_style'); ?></b></h2>
                            <div class="inside">
                                <div>The Ipv6 supporting version of this plugin requires an update.</div>
                                <div>There has been an update to the regions. Some regions were removed and other new regions were added. A list of any groups using outdated regions will be shown here after you click the update button.</div>
                                <div><strong>Important!</strong> You will also need to <strong>upload the new .mmdb file</strong> for the plugin to continue working.</div>
                                <br>
                                <input type="submit" value="Update Now" class="btn btn-primary" name="v6_update">
                            </div>
                        </div>
                    </form>

                <?php } ?>

                <form id="update_settings_form" name="update_settings_form" action="" method="post">
                    <div class="postbox">
                        <h2 class="hndle"><b><?php esc_attr_e('Activate DEBUG MODE', 'wp_admin_style'); ?></b></h2>
                        <div class="inside">
                            <div>
                                <br>
                                Debug Mode:
                                <input type="checkbox" name="debug_status_check" id="debug_status_check" <?php if($settings_values[0]->DebugStatus === '1'){ print 'checked="checked"';} ?>>
                            </div>
                        </div>
                    </div>
                    <div class="postbox">
                        <h2 class="hndle"><b><?php esc_attr_e('Wordpress Installation Type', 'wp_admin_style'); ?></b></h2>
                        <div class="inside">
                            <div>
                                <br>
                                Is this a Bedrock install?:
                                <input type="checkbox" name="wordpress_bedrock_check" id="wordpress_bedrock_check" <?php if($wordpress_bedrock_installation === '1'){ print 'checked="checked"';} ?>>
                            </div>
                        </div>
                    </div>
                </form>

                <div class="postbox">
                    <h2 class="hndle"><b><?php esc_attr_e('Update geo location .mmdb file', 'wp_admin_style'); ?></b></h2>
                    <div class="inside">
                        <div>
                            <br>
                            Last time updated:&nbsp;
                            <?php
                                if($settings_values[0]->GeoFileLastUpdated !== null){
                                    echo date("Y-m-d H:i:s",strtotime($settings_values[0]->GeoFileLastUpdated));
                                }
                                else
                                {
                                    echo "<b>Never</b>";
                                }
                            ?>
                        </div>
                        <div>
                            <br>
                            <div>Upload a new <b>.Zip</b> file:</div>
                            <br>
                            <form action=""  method="post" enctype="multipart/form-data">
                                <input type="file" name="fileToUpload" id="fileToUpload">
                                <br><br>
                                <input type="submit" value="Upload geo .Zip file" class="btn btn-primary" name="upload_file_form">
                            </form>
                        </div>
                    </div>
                </div>

                <div class="postbox">
                    <h2 class="hndle"><b><?php esc_attr_e('IP country lookup tester', 'wp_admin_style'); ?></b></h2>
                    <div class="inside">
                        <div>
                            <br>
                            <form action=""  method="post" enctype="multipart/form-data">
                                <label for="ip_to_test">IP to check:</label>
                                <input type="text" name="ip_to_test" id="ip_to_test">
                                <br><br>
                                <?php if($ip_lookup_result !== ""):?>
                                    <label id="lbl_lookup_results" name="lbl_lookup_results"><?php echo $ip_lookup_result;?></label>
                                <?php endif;?>
                                <br><br>
                                <input type="submit" value="Lookup IP Country" class="btn btn-primary" name="local_ip_lookup">
                            </form>
                        </div>
                    </div>
                </div>
                <div class="postbox">
                    <h2 class="hndle"><b><?php esc_attr_e('Nginx Cache', 'wp_admin_style'); ?></b></h2>
                    <div class="inside">
                        <div>
                            <br>
                            <form action=""  method="post" enctype="multipart/form-data">
                                <label for="by_pass_geo_parameters">By Pass Geo Parameters:</label>
                                <input type="checkbox" name="by_pass_geo_parameters" id="by_pass_geo_parameters" <?php if($should_use_cache_info){ print 'checked="checked"';} ?>>
                                <br><br>
                                <label>Receiving Nginx parameters:</label> <?php echo $nginx_parameters?'Yes':'No' ?>
                                <br><br>
                                <label>Using Nginx Cache Plugin:</label> <?php echo $nginx_cache_plugin_active?'Active':'No' ?>
                                <br><br>
                                <label>Nginx cache path:</label> <?php echo $nginx_cache_path ?>
                                <br><br>
                                <?php if ($nginx_cache_plugin_active): ?>
                                    <label>Nginx cache with content:</label> <?php echo $nginx_cache_path_working?'Active':'No' ?>
                                <br><br>
                                <?php endif; ?>
                                <label for="clear_nginx_cache">Clear Nginx cache</label>
                                <input type="submit" value="Clear Cache" class="btn btn-primary" name="clear_nginx">
                            </form>
                        </div>
                    </div>
                </div>
                <!-- .meta-box-sortables .ui-sortable -->
            </div>
            <!-- post-body-content -->
            <!-- sidebar -->
            <?php
            GLOBAL $ftm_geo_target_plugin_path;
            require_once $ftm_geo_target_plugin_path . '/includes/sidebar-settings.php';
            ?>
            <!-- sidebar -->
            <!-- #postbox-container-1 .postbox-container -->
        </div>
        <!-- #post-body .metabox-holder .columns-2 -->
        <br class="clear">
    </div>
    <!-- #poststuff -->
</div> <!-- .wrap -->
