<?php
/*
Plugin Name: Custom Plugin Features
Description: The plugin includes the ability to update upload fields, upload datetime updater, and textarea counter.
Version: 1.0
Requires at least: 3.50
*/

pluginAction_addHandler('_custom_pluginMenu_updateTable_ajax', 'admins');


function custom_pluginMenu_updateTable() {
	global $TABLE_PREFIX;

	$adminUI = [];
	$adminUI['PAGE_TITLE'] = [
		t('Plugins')						=> '?menu=admin&action=plugins',
		t('Permalinks - Update Tables')		=> '?_pluginAction=custom_pluginMenu_updateTable'
	];

	// button
	$adminUI['BUTTONS'] = [
		[ 'name' => 'back_to_plugins', 'label' => 'Back to Plugins &gt;&gt;',  'onclick' => 'window.location="?menu=admin&action=plugins";', 'type' => 'button' ],
	];
	$process_btn = (!empty($_POST['process_btn'])) ? $_POST['process_btn'] : false;

	$adminUI['CONTENT'] = ob_capture(function() {
	?>
		<p>
			<div class="form-group">
            <form class="update_table_form">
				<?php foreach(getSchemaTables() as $tableName) {
					if ($tableName === 'uploads') {
						$prefixTableName = getTableNameWithPrefix($tableName);
						$schema = loadSchema($tableName);
						$info1ColumnType = $schema['info1']['customColumnType'];
					?>

							<table width="50%">
								<thead>
								<tr>
									<th width="10%"></th><th>Column Name</th><th width="35%">Column value</th>
								</tr>
								</thead>
								<tbody>
								<tr>
									<td><input type="checkbox" name="fixit[]" value="uploadsinfo1"></td> <td>Info1 Column Type</td> <td><?php echo $info1ColumnType; ?><br><small>Note: This checkbox will change the column type to Mediumtext which will vastly increase the text you can store.</small></td>
								</tr>
								<tr>
									<td><input type="checkbox" name="fixit[]" value="uploadsCreatedTime"></td> <td>Created Time Column Type</td> <td><?php echo $schema['createdTime']['customColumnType']; ?><br><small>This checkbox will update the default time to datetime NOT NULL DEFAULT CURRENT_TIMESTAMP.</small></td>
								</tr>
								<tr>
									<td><input type="checkbox" name="fixit[]" value="combineInfoFields"></td> <td>Combine Info Fields</td> <td><span style="color:red">Warning: This will erase existing data in info2, info3, info4, and info5.</span> </td>
								</tr>
                                <tr>
                                    <td><input type="text" name="table_name" value="tableName"></td> <td>Enter The Table Name Where The Info Fields Are To Be Combined</td> <td><span style="color:red">Warning: This will erase existing data in info2, info3, info4, and info5 of the specified table.</span></td>
                                </tr>
                                </tbody>
							</table>
						<?php echo adminUI_button(['id' => 'process_btn', 'type' => 'button', 'btn-type' => 'default', 'label' => t('Process Fixes')]); ?>
                        <div class="messages"></div>
					<script type="text/javascript">
                        function setProgressMessage(message) { $('#progress').html(message); }
                        function disableForm() { $('#button').attr('disabled', 'disabled'); $('#table').attr('disabled', 'disabled'); }
                        function enableForm()  { $('#button').removeAttr('disabled'); $('#table').removeAttr('disabled'); }

                        $(document).ready(function() {
                            $('#process_btn').click(function () {
                                setProgressMessage('Processing updates starting...');
                                disableForm();
                                $('#errors').html('');

                                let url = '?_pluginAction=_custom_pluginMenu_updateTable_ajax';

                                $.ajax({
                                    url: url,
									type: 'POST',
									data: $(document).find('form').serialize(),
                                    error: function (msg) {
                                        setProgressMessage('Error!');
                                        enableForm();
                                    },
                                    success: function (msg) {
                                        let json;
                                        try {
                                            json = $.parseJSON(msg);
                                        } catch (err) {
                                        }
                                        $('.messages').html('');
                                        if (json) {
                                            let messages = $.each(json.message, function(index, messageItem) {
                                                let pElement = document.createElement('p');
                                                pElement.innerHTML = messageItem;
                                                $('.messages').append(pElement);
                                            });

                                        } else {
                                            setProgressMessage('Error!');
                                            alert('Error ' + msg);
                                            enableForm();
                                        }
                                    }
                                });
                                return false;
                            });
                        });
					</script>
					<?php
					}
				}
				?>
            </form>
			</div>
		</p>
	<?php
	});
	adminUI($adminUI);
	exit;
}

pluginAction_addHandlerAndLink(t('Update Uploads Table'), 'custom_pluginMenu_updateTable', 'admins');

function _custom_pluginMenu_updateTable_ajax() {
	global $TABLE_PREFIX;
	$fixitActions = @$_REQUEST['fixit'];
	$message 	  = array();
	$errors       = '';

	if (!empty($fixitActions)) {
		foreach ($fixitActions as $action) {
			$schema = loadSchema('uploads');
			$prefixTableName = getTableNameWithPrefix('uploads');
			if ($action === 'uploadsinfo1') {

				if (isset($schema['info1'])) {
					$schema['info1']['customColumnType'] = "MEDIUMTEXT";
				}

				saveSchema('uploads', $schema);
				mysqli()->query("ALTER TABLE `".mysql_escape($prefixTableName)."` CHANGE `info1` `info1` MEDIUMTEXT") or die("Error adding fields to uploads, the error was:\n\n". htmlencode(mysqli()->error));
				array_push($message, 'You have successfully altered the info1 field text length!');
			} elseif ($action === 'uploadsCreatedTime') {
				if (isset($schema['createdTime'])) {
					$schema['createdTime']['customColumnType'] = "datetime NOT NULL DEFAULT CURRENT_TIMESTAMP";
				}

				saveSchema('uploads', $schema);
				array_push($message, 'You have successfully set the datetime default value to CURRENT_TIMESTAMP.');
			} elseif ($action === 'combineInfoFields') {
				$table_name = mysql_escape($_REQUEST['table_name']);
				$rows_affected = 0;
				mysql_do("UPDATE {$TABLE_PREFIX}uploads SET info1=CONCAT_WS(CHAR(10), info1, info2, info3, info4, info5) WHERE tableName='".$table_name."'") or die("Error combining info fields, the error was:\n\n". htmlencode(mysqli()->error));
				$rows_affected += mysqli()->affected_rows;
				mysql_do("UPDATE {$TABLE_PREFIX}uploads SET info2='', info3='', info4='', info5='' WHERE tableName='".$table_name."'") or die("Error combining info fields, the error was:\n\n". htmlencode(mysqli()->error));
				$rows_affected += mysqli()->affected_rows;
				if ($rows_affected === 0) {
					array_push($message, 'Nothing was processed for table name <strong>'. $table_name.'</strong>');
                } else {
					array_push($message, 'You have successfully combined the content of the info2 to info5 fields into info1 for table name <strong>'.$table_name.'</strong>.');
                }

			}
		}
	} else {
		$errors = t('Nothing to process.');
	}

	print json_encode(array(
		'errors'	=> htmlentities($errors),
		'message'	=> $message,
	));
	exit;
}