<?php
defined( 'ABSPATH' ) || exit;

class Woocom_Pay_Activator {

	public static function activate(): void {
		self::create_tables();
		self::create_upload_dir();
		flush_rewrite_rules();
	}

	private static function create_tables(): void {
		global $wpdb;

		$charset = $wpdb->get_charset_collate();
		$table   = $wpdb->prefix . 'woocom_pay_transactions';

		$sql = "CREATE TABLE IF NOT EXISTS {$table} (
			id              BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
			order_id        BIGINT UNSIGNED NOT NULL,
			customer_id     BIGINT UNSIGNED NOT NULL DEFAULT 0,
			product_id      BIGINT UNSIGNED NOT NULL DEFAULT 0,
			payment_type    VARCHAR(20)  NOT NULL DEFAULT 'full',
			product_price   DECIMAL(15,2) NOT NULL DEFAULT 0.00,
			paid_amount     DECIMAL(15,2) NOT NULL DEFAULT 0.00,
			balance_amount  DECIMAL(15,2) NOT NULL DEFAULT 0.00,
			transaction_id  VARCHAR(100) NOT NULL DEFAULT '',
			screenshot_path VARCHAR(500) NOT NULL DEFAULT '',
			remarks         TEXT         NOT NULL DEFAULT '',
			verification_status VARCHAR(20) NOT NULL DEFAULT 'pending',
			verified_by     BIGINT UNSIGNED NOT NULL DEFAULT 0,
			verified_at     DATETIME     DEFAULT NULL,
			created_at      DATETIME     NOT NULL DEFAULT CURRENT_TIMESTAMP,
			updated_at      DATETIME     NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
			PRIMARY KEY (id),
			KEY order_id (order_id),
			KEY customer_id (customer_id)
		) {$charset};";

		require_once ABSPATH . 'wp-admin/includes/upgrade.php';
		dbDelta( $sql );
	}

	private static function create_upload_dir(): void {
		$upload = wp_upload_dir();
		$dir    = $upload['basedir'] . '/woocom-pay-screenshots';
		if ( ! file_exists( $dir ) ) {
			wp_mkdir_p( $dir );
			file_put_contents( $dir . '/.htaccess', "Options -Indexes\n<FilesMatch '\.(php|phtml|php3|php4|php5|php7|pht|phar)$'>\nDeny from all\n</FilesMatch>\n" );
			file_put_contents( $dir . '/index.php', '<?php // Silence is golden.' );
		}
	}
}
