<?php
/**
 * Database Installation
 *
 * Handles database table creation and upgrades for Warranty Cart.
 *
 * @package WarrantyCart
 */

namespace WarrantyCart\Core;

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

/**
 * Database Installation Class
 */
class DatabaseInstaller {

	/**
	 * Create database tables
	 *
	 * @return bool True on success, false on failure.
	 */
	public static function create_tables(): bool {
		global $wpdb;

		$charset_collate = $wpdb->get_charset_collate();

		// Warranty records table
		$table_name = $wpdb->prefix . 'warranty_cart_warranties';

		$sql = "CREATE TABLE $table_name (
			id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
			order_id bigint(20) unsigned NOT NULL,
			customer_id bigint(20) unsigned DEFAULT NULL,
			product_id bigint(20) unsigned NOT NULL,
			warranty_type varchar(50) NOT NULL,
			duration int(11) NOT NULL DEFAULT 1,
			duration_unit varchar(20) NOT NULL DEFAULT 'years',
			purchase_date datetime NOT NULL,
			expiration_date date NOT NULL,
			purchase_price decimal(10,2) NOT NULL,
			currency varchar(3) NOT NULL DEFAULT 'EUR',
			payment_method varchar(100) DEFAULT NULL,
			status varchar(20) NOT NULL DEFAULT 'active',
			source varchar(50) NOT NULL DEFAULT 'woocommerce',
			coverage_details longtext,
			reminder_sent tinyint(1) DEFAULT 0,
			expired_notified tinyint(1) DEFAULT 0,
			renewal_count int(11) DEFAULT 0,
			last_renewal_date datetime DEFAULT NULL,
			created_at datetime NOT NULL,
			updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
			PRIMARY KEY (id),
			KEY order_id (order_id),
			KEY customer_id (customer_id),
			KEY product_id (product_id),
			KEY expiration_date (expiration_date),
			KEY status (status),
			KEY warranty_type (warranty_type)
		) $charset_collate;";

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

		// Execute table creation
		$result = \dbDelta( $sql );

		// Check if table was created successfully
		if ( empty( $result ) ) {
			\wc_get_logger()->error( 'Failed to create warranty database tables', array( 'source' => 'warranty-cart-db' ) );

			return false;
		}

		// Verify table exists
		$table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table_name ) );
		if ( ! $table_exists ) {
			\wc_get_logger()->error( 'Warranty table creation failed - table does not exist', array( 'source' => 'warranty-cart-db' ) );

			return false;
		}

		// Store database version
		\update_option( 'warranty_cart_db_version', '1.0.0' );

		// Log successful table creation
		\wc_get_logger()->info( 'Warranty database tables created successfully', array( 'source' => 'warranty-cart-db' ) );

		return true;
	}

	/**
	 * Check if database needs upgrade
	 *
	 * @return bool
	 */
	public static function needs_upgrade(): bool {
		$current_version = \get_option( 'warranty_cart_db_version', '0' );

		return version_compare( $current_version, '1.0.0', '<' );
	}

	/**
	 * Run database upgrades
	 *
	 * @return bool True on success, false on failure.
	 */
	public static function upgrade(): bool {
		$current_version = \get_option( 'warranty_cart_db_version', '0' );

		// If no version set, assume fresh install
		if ( '0' === $current_version ) {
			$result = self::create_tables();
			if ( $result ) {
				\wc_get_logger()->info( 'Fresh warranty database installation completed', array( 'source' => 'warranty-cart-db' ) );
			}

			return $result;
		}

		// Check if upgrade is needed
		if ( ! self::needs_upgrade() ) {
			return true; // Already up to date
		}

		\wc_get_logger()->info(
			\sprintf( 'Upgrading warranty database from version %s to 1.0.0', $current_version ),
			array( 'source' => 'warranty-cart-db' )
		);

		// For now, just recreate tables (future versions may need migration logic)
		$result = self::create_tables();

		if ( $result ) {
			\wc_get_logger()->info( 'Warranty database upgrade completed successfully', array( 'source' => 'warranty-cart-db' ) );
		} else {
			\wc_get_logger()->error( 'Warranty database upgrade failed', array( 'source' => 'warranty-cart-db' ) );
		}

		return $result;
	}

	/**
	 * Get current database version
	 *
	 * @return string
	 */
	public static function get_version(): string {
		return \get_option( 'warranty_cart_db_version', '0' );
	}

	/**
	 * Check if database tables exist
	 *
	 * @return bool
	 */
	public static function tables_exist(): bool {
		global $wpdb;

		$table_name   = $wpdb->prefix . 'warranty_cart_warranties';
		$table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table_name ) );

		return ! empty( $table_exists );
	}
}
