<?php
/**
 * Schema, defaults, upgrades.
 *
 * @package FEPW
 */

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

/**
 * Class FEPW_Install
 */
class FEPW_Install {

	/**
	 * Activation.
	 */
	public static function activate() {
		self::create_tables();
		self::set_defaults();
		update_option( 'fepw_db_version', '1' );
	}

	/**
	 * Upgrade check.
	 */
	public static function maybe_upgrade() {
		if ( '1' !== (string) get_option( 'fepw_db_version' ) ) {
			self::create_tables();
			update_option( 'fepw_db_version', '1' );
		}
	}

	/**
	 * Tables: atomic number sequences + generated documents.
	 */
	public static function create_tables() {
		global $wpdb;
		require_once ABSPATH . 'wp-admin/includes/upgrade.php';
		$charset = $wpdb->get_charset_collate();

		// Claim table: one row INSERT per claimed number (atomic via AUTO_INCREMENT).
		dbDelta(
			"CREATE TABLE {$wpdb->prefix}fepw_sequences (
				id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
				seq_key VARCHAR(32) NOT NULL,
				order_id BIGINT(20) UNSIGNED NOT NULL,
				claimed_at DATETIME NOT NULL,
				PRIMARY KEY  (id),
				KEY seq_key (seq_key, id)
			) $charset;"
		);

		dbDelta(
			"CREATE TABLE {$wpdb->prefix}fepw_documents (
				id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
				order_id BIGINT(20) UNSIGNED NOT NULL,
				refund_id BIGINT(20) UNSIGNED NOT NULL DEFAULT 0,
				doc_type VARCHAR(12) NOT NULL DEFAULT 'invoice',
				doc_number VARCHAR(64) NOT NULL,
				issued_at DATETIME NOT NULL,
				total_ht DECIMAL(18,2) NOT NULL DEFAULT 0,
				total_tva DECIMAL(18,2) NOT NULL DEFAULT 0,
				total_ttc DECIMAL(18,2) NOT NULL DEFAULT 0,
				status VARCHAR(16) NOT NULL DEFAULT 'generated',
				PRIMARY KEY  (id),
				KEY order_id (order_id),
				KEY doc_type (doc_type, issued_at)
			) $charset;"
		);
	}

	/**
	 * Defaults (only when absent).
	 */
	public static function set_defaults() {
		if ( false !== get_option( 'fepw_settings', false ) ) {
			return;
		}
		update_option(
			'fepw_settings',
			array(
				'seller_siren'        => '',
				'seller_tva'          => '',
				'seller_legal_form'   => '',
				'seller_rcs'          => '',
				'seller_capital'      => '',
				'option_debits'       => 0,
				'operation_category'  => 'goods', // goods|services|mixed.
				'due_days'            => 30,
				'number_format'       => 'FA-{YYYY}-{SEQ:5}',
				'credit_format'       => 'AV-{YYYY}-{SEQ:5}',
				'vat_regime'          => 'reel_normal', // reel_normal|simplifie|franchise.
				'require_siren_b2b'   => 1,
			)
		);
	}
}
