<?php
/**
 * Install/schema/defaults.
 *
 * @package Upload_Vault
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class Uvgf_Install
 */
class Uvgf_Install {

	const DB_VERSION = '1';

	/**
	 * Activate.
	 */
	public static function activate() {
		self::create_tables();
		self::set_defaults();
		update_option( 'uvgf_db_version', self::DB_VERSION );
	}

	/**
	 * Deactivate: clear schedules (data stays; uninstall removes it).
	 */
	public static function deactivate() {
		wp_clear_scheduled_hook( 'uvgf_weekly_audit' );
		wp_clear_scheduled_hook( 'uvgf_retention_purge' );
	}

	/**
	 * Upgrade routine.
	 */
	public static function maybe_upgrade() {
		if ( (string) get_option( 'uvgf_db_version' ) !== self::DB_VERSION ) {
			self::create_tables();
			update_option( 'uvgf_db_version', self::DB_VERSION );
		}
	}

	/**
	 * The file registry. One row per file found under the Gravity Forms upload
	 * base. `path_hash` (md5 of the relative path) dedupes across re-indexes so
	 * `first_seen` stays stable; download links carry the row id, so user input
	 * is never a filesystem path.
	 */
	public static function create_tables() {
		global $wpdb;
		require_once ABSPATH . 'wp-admin/includes/upgrade.php';
		$charset = $wpdb->get_charset_collate();

		dbDelta(
			"CREATE TABLE {$wpdb->prefix}uvgf_files (
				id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
				path_hash CHAR(32) NOT NULL,
				form_id BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
				relpath TEXT NOT NULL,
				size BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
				file_mtime DATETIME NULL,
				status VARCHAR(12) NOT NULL DEFAULT 'unknown',
				first_seen DATETIME NOT NULL,
				last_check DATETIME NULL,
				PRIMARY KEY  (id),
				UNIQUE KEY path_hash (path_hash),
				KEY form_id (form_id),
				KEY status (status)
			) $charset;"
		);
	}

	/**
	 * Defaults.
	 */
	public static function set_defaults() {
		if ( false === get_option( 'uvgf_settings', false ) ) {
			update_option(
				'uvgf_settings',
				array(
					'alert_email'           => get_option( 'admin_email' ),
					'weekly_audit'          => 1,
					'email_on_new'          => 1,
					'rewrite_entry_links'   => 1,
					'rewrite_notifications' => 1,
					'open_form_dirs'        => array(),
				)
			);
		}
		add_option(
			'uvgf_state',
			array(
				'last_audit'     => 0,
				'loopback_ok'    => null,
				'loopback_error' => '',
				'verdict'        => '',
				'protected'      => 0,
			),
			'',
			'no'
		);
	}
}
