<?php
/**
 * Sifency AI — File Writer
 *
 * Responsible for writing, toggling (enable/disable), deleting, and
 * listing AI-generated PHP files in wp-content/uploads/sifency-ai/.
 *
 * Enable/disable is implemented as a simple manifest stored in a
 * WP option rather than renaming files, to avoid filesystem race
 * conditions and permission headaches.
 *
 * @package Sifency_Addons
 * @since   1.0.5
 */

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

class Sifency_Addons_AI_File_Writer {

	/*
	 ------------------------------------------------------------------ */
	/*
	  Option key for the enabled-state manifest                          */
	/* ------------------------------------------------------------------ */

	private const MANIFEST_OPTION = 'sifency_ai_manifest';

	/*
	 ------------------------------------------------------------------ */
	/*
	  Write                                                               */
	/* ------------------------------------------------------------------ */

	/**
	 * Write a PHP file for a generated item.
	 *
	 * @param  string $type      Sub-folder key: 'widgets', 'cpts', etc.
	 * @param  string $slug      Sanitized machine name (e.g. 'my-card-widget').
	 * @param  string $php_code  The PHP code to write (without opening tag).
	 * @return array|\WP_Error   ['filename' => ..., 'path' => ..., 'url' => ...]
	 */
	public function write( string $type, string $slug, string $php_code ): array|\WP_Error {
		$dir = Sifency_Addons_AI_Module::base_dir() . $type . '/';

		if ( ! is_dir( $dir ) && ! wp_mkdir_p( $dir ) ) {
			return new \WP_Error(
				'sifency_ai_dir',
				sprintf(
					/* translators: %s: directory path */
					__( 'Cannot create directory: %s', 'sifency-addons' ),
					$dir
				)
			);
		}

		// Ensure the slug is safe for use as a filename.
		$slug     = $this->sanitize_slug( $slug );
		$filename = $slug . '.php';
		$filepath = $dir . $filename;

		// Prepend the PHP opening tag + a do-not-edit notice.
		$content  = "<?php\n";
		$content .= "/**\n";
		$content .= " * Generated by Sifency AI — do not edit manually.\n";
		$content .= " * Slug    : {$slug}\n";
		$content .= " * Type    : {$type}\n";
		$content .= ' * Created : ' . current_time( 'Y-m-d H:i:s' ) . "\n";
		$content .= " *\n";
		$content .= " * @package Sifency_Addons\n";
		$content .= " */\n\n";
		$content .= "if ( ! defined( 'ABSPATH' ) ) { exit; }\n\n";
		$content .= $php_code;

		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents
		$bytes = file_put_contents( $filepath, $content );

		if ( false === $bytes ) {
			return new \WP_Error(
				'sifency_ai_write',
				sprintf(
					/* translators: %s: file name */
					__( 'Could not write file: %s', 'sifency-addons' ),
					$filename
				)
			);
		}

		// Auto-enable on creation.
		$this->set_enabled( $type, $filename, true );

		return array(
			'filename' => $filename,
			'slug'     => $slug,
			'type'     => $type,
			'path'     => $filepath,
			'url'      => Sifency_Addons_AI_Module::base_url() . $type . '/' . $filename,
			'enabled'  => true,
			'created'  => current_time( 'Y-m-d H:i:s' ),
		);
	}

	/*
	 ------------------------------------------------------------------ */
	/*
	  Enable / Disable                                                    */
	/* ------------------------------------------------------------------ */

	public function set_enabled( string $type, string $filename, bool $enabled ): bool {
		$manifest         = $this->load_manifest();
		$key              = $type . '/' . $filename;
		$manifest[ $key ] = $enabled;
		return update_option( self::MANIFEST_OPTION, $manifest );
	}

	public static function is_enabled( string $type, string $filename ): bool {
		$manifest = get_option( self::MANIFEST_OPTION, array() );
		$key      = $type . '/' . $filename;
		// Items not yet in the manifest are considered enabled by default.
		return $manifest[ $key ] ?? true;
	}

	/*
	 ------------------------------------------------------------------ */
	/*
	  Delete                                                              */
	/* ------------------------------------------------------------------ */

	public function delete( string $type, string $filename ): bool {
		$filepath = Sifency_Addons_AI_Module::base_dir() . $type . '/' . sanitize_file_name( $filename );

		if ( file_exists( $filepath ) && ! wp_delete_file( $filepath ) ) {
			return false;
		}

		// Remove from manifest.
		$manifest = $this->load_manifest();
		unset( $manifest[ $type . '/' . $filename ] );
		update_option( self::MANIFEST_OPTION, $manifest );

		return true;
	}

	/*
	 ------------------------------------------------------------------ */
	/*
	  List Items                                                          */
	/* ------------------------------------------------------------------ */

	/**
	 * Return an array of metadata for every generated file in a sub-folder.
	 */
	public static function list_items( string $type ): array {
		$dir   = Sifency_Addons_AI_Module::base_dir() . $type . '/';
		$items = array();

		if ( ! is_dir( $dir ) ) {
			return $items;
		}

		foreach ( glob( $dir . '*.php' ) as $filepath ) {
			$filename = basename( $filepath );

			// Skip the silence file.
			if ( $filename === 'index.php' ) {
				continue;
			}

			$slug    = str_replace( '.php', '', $filename );
			$meta    = self::read_file_meta( $filepath );
			$items[] = array(
				'filename' => $filename,
				'slug'     => $slug,
				'type'     => $type,
				'enabled'  => self::is_enabled( $type, $filename ),
				'created'  => $meta['created'] ?? '',
				'size'     => filesize( $filepath ),
			);
		}

		return $items;
	}

	/*
	 ------------------------------------------------------------------ */
	/*
	  Helpers                                                             */
	/* ------------------------------------------------------------------ */

	private function load_manifest(): array {
		return (array) get_option( self::MANIFEST_OPTION, array() );
	}

	private function sanitize_slug( string $slug ): string {
		// Lowercase, replace spaces + underscores with hyphens, strip unsafe chars.
		$slug = strtolower( trim( $slug ) );
		$slug = preg_replace( '/[\s_]+/', '-', $slug );
		$slug = preg_replace( '/[^a-z0-9\-]/', '', $slug );
		$slug = trim( $slug, '-' );
		return $slug ?: 'sifency-ai-item';
	}

	/**
	 * Extract the Created date from the file header comment.
	 */
	private static function read_file_meta( string $filepath ): array {
		$meta = array();

		global $wp_filesystem;
		if ( empty( $wp_filesystem ) ) {
			require_once ABSPATH . 'wp-admin/includes/file.php';
			WP_Filesystem();
		}

		if ( ! $wp_filesystem || ! $wp_filesystem->exists( $filepath ) ) {
			return $meta;
		}

		$contents = $wp_filesystem->get_contents( $filepath );
		if ( false === $contents ) {
			return $meta;
		}

		$lines          = explode( "\n", $contents );
		$lines_to_check = array_slice( $lines, 0, 15 );

		foreach ( $lines_to_check as $line ) {
			if ( preg_match( '/\* Created\s*:\s*(.+)/', $line, $m ) ) {
				$meta['created'] = trim( $m[1] );
			}
		}

		return $meta;
	}
}
