<?php
/**
 * Schema installation and upgrades.
 *
 * @package Harbor_EU_EInvoicing_For_WooCommerce
 */

defined( 'ABSPATH' ) || exit;

class HEIN_Install {

	public const DB_VERSION = '1';

	public static function activate(): void {
		self::maybe_upgrade();

		// Only materialises the option row so the settings screen reflects the defaults on first load.
		// Nothing depends on it: all() merges defaults() and enabled() falls back to every registered
		// format, so an install that never ran this still generates
		if ( false === get_option( 'hein_settings', false ) ) {
			add_option( 'hein_settings', HEIN_Admin_Settings::defaults() );
		}

		HEIN_Invoice_Store::ensure_protected();
	}

	public static function deactivate(): void {
		delete_transient( 'hein_uploads_exposed' );
	}

	/**
	 * Runs on every boot, so an FTP-copied install that never fired the activation hook still
	 * provisions its tables
	 */
	public static function maybe_upgrade(): void {
		if ( self::DB_VERSION === get_option( 'hein_db_version' ) ) {
			return;
		}

		self::create_tables();

		update_option( 'hein_db_version', self::DB_VERSION );
	}

	/**
	 * The dbDelta parser is fussy: uppercase types, one column per line, two spaces after PRIMARY
	 * KEY, no backticks around the table name and KEY names that are stable across re-runs. A
	 * malformed statement silently creates nothing
	 */
	private static function create_tables(): void {
		global $wpdb;

		require_once ABSPATH . 'wp-admin/includes/upgrade.php';

		$collate  = $wpdb->get_charset_collate();
		$invoices = hein_invoices_table();
		$counters = hein_counters_table();
		$numbers  = hein_numbers_table();

		$schema = [
			"CREATE TABLE {$invoices} (
				id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
				order_id BIGINT UNSIGNED NOT NULL,
				format VARCHAR(32) NOT NULL,
				invoice_number VARCHAR(64) NOT NULL,
				issue_date DATE NOT NULL,
				currency CHAR(3) NOT NULL,
				payable_total DECIMAL(19,4) NOT NULL DEFAULT 0,
				mime VARCHAR(96) NOT NULL,
				filename VARCHAR(191) NOT NULL,
				content LONGBLOB NOT NULL,
				content_hash CHAR(64) NOT NULL,
				file_path VARCHAR(255) NOT NULL DEFAULT '',
				status VARCHAR(20) NOT NULL DEFAULT 'generated',
				remote_id VARCHAR(191) NOT NULL DEFAULT '',
				created_gmt DATETIME NOT NULL,
				updated_gmt DATETIME NOT NULL,
				PRIMARY KEY  (id),
				UNIQUE KEY order_format (order_id, format),
				KEY invoice_number (invoice_number),
				KEY status (status)
			) {$collate};",
			"CREATE TABLE {$counters} (
				series VARCHAR(64) NOT NULL,
				value BIGINT UNSIGNED NOT NULL DEFAULT 0,
				PRIMARY KEY  (series)
			) {$collate};",
			"CREATE TABLE {$numbers} (
				order_id BIGINT UNSIGNED NOT NULL,
				series VARCHAR(64) NOT NULL,
				sequence BIGINT UNSIGNED NOT NULL,
				number VARCHAR(64) NOT NULL,
				issue_date DATE NOT NULL,
				created_gmt DATETIME NOT NULL,
				PRIMARY KEY  (order_id),
				UNIQUE KEY number (number)
			) {$collate};",
		];

		dbDelta( $schema );
	}
}
