<?php

	class SCWC_Activator {

		public static function activate() {
			self::dosya_olustur();

			add_option( 'birinci_sozlesme_link_ismi', 'Pre-Information Form' );
			add_option( 'ikinci_sozlesme_link_ismi', 'Distance Sales Contract' );

			add_option( 'sozlesme_ozellik_1', '1' );
			add_option( 'sozlesme_ozellik_2', '1' );
			add_option( 'sozlesme_ozellik_3', '1' );
			add_option( 'sozlesme_ozellik_4', '1' );
			add_option( 'sozlesme_ozellik_5', '1' );
			add_option( 'sozlesme_ozellik_6', '1' );
			add_option( 'korkmaz_contract_log_enabled', '0' );
		}

		public static function dosya_olustur() {
			// 1) Bootstrap WP_Filesystem
			if ( ! function_exists( 'request_filesystem_credentials' ) ) {
				require_once ABSPATH . 'wp-admin/includes/file.php';
			}
			WP_Filesystem();
			global $wp_filesystem;

			if ( empty( $wp_filesystem ) || ! is_object( $wp_filesystem ) ) {
				return;
			}

			// 2) Upload base dir and subfolder path
			$upload_dir_info = wp_upload_dir();
			$dir_path        = trailingslashit( $upload_dir_info['basedir'] ) . 'korkmazsozlesme';

			// 3) Create folder if not exists
			if ( ! $wp_filesystem->is_dir( $dir_path ) ) {
				$wp_filesystem->mkdir( $dir_path, FS_CHMOD_DIR ); // 0755 equivalent
			}

			if ( ! $wp_filesystem->is_dir( $dir_path ) ) {
				return;
			}

			// 4) Files to create
			$files = array(
				'.htaccess' => "# Auto-generated by Korkmaz Contract\nOptions -Indexes\n<Files \"*.pdf\">\n\t<IfModule mod_authz_core.c>\n\t\tRequire all denied\n\t</IfModule>\n\t<IfModule !mod_authz_core.c>\n\t\tOrder allow,deny\n\t\tDeny from all\n\t</IfModule>\n</Files>\n",
				'index.php' => '<?php // Silence is golden',
			);

			foreach ( $files as $filename => $content ) {
				$file_path = trailingslashit( $dir_path ) . $filename;

				$should_write = ! $wp_filesystem->exists( $file_path );
				if ( '.htaccess' === $filename && ! $should_write ) {
					$current_htaccess = (string) $wp_filesystem->get_contents( $file_path );
					$should_write     = false === strpos( $current_htaccess, 'Require all denied' ) || false === strpos( $current_htaccess, 'mod_authz_core.c' );
				}

				if ( $should_write ) {
					$wp_filesystem->put_contents(
						$file_path,
						$content,
						FS_CHMOD_FILE // 0644 equivalent
					);
				}
			}
		}
	}
