<?php
/**
 * Audit log: who did what, when, and what changed. Rows are always written
 * (they are the store's own data); the history VIEW is a Pro feature.
 *
 * @package Stocktake_For_WooCommerce
 */

defined( 'ABSPATH' ) || exit;

// phpcs:disable WordPress.DB.DirectDatabaseQuery -- custom-table plugin: the schema lives in our own stwc_* tables; every query is fully $wpdb->prepare()d with %i table identifiers.

class STWC_Log {

	public static function table() {
		global $wpdb;
		return $wpdb->prefix . 'stwc_log';
	}

	/**
	 * Append an event.
	 *
	 * @param array $args session_id, item_id, product_id, variation_id, name,
	 *                    event, qty_before, qty_after, note.
	 */
	public static function add( $args ) {
		global $wpdb;
		$d = wp_parse_args(
			$args,
			array(
				'session_id'   => 0,
				'item_id'      => 0,
				'product_id'   => 0,
				'variation_id' => 0,
				'name'         => '',
				'event'        => '',
				'qty_before'   => null,
				'qty_after'    => null,
				'note'         => '',
			)
		);
		$wpdb->insert(
			self::table(),
			array(
				'session_id'   => (int) $d['session_id'],
				'item_id'      => (int) $d['item_id'],
				'product_id'   => (int) $d['product_id'],
				'variation_id' => (int) $d['variation_id'],
				'name'         => (string) $d['name'],
				'user_id'      => get_current_user_id(),
				'event'        => (string) $d['event'],
				'qty_before'   => is_null( $d['qty_before'] ) ? null : (float) $d['qty_before'],
				'qty_after'    => is_null( $d['qty_after'] ) ? null : (float) $d['qty_after'],
				'note'         => (string) $d['note'],
				'created_at'   => current_time( 'mysql' ),
			),
			array( '%d', '%d', '%d', '%d', '%s', '%d', '%s', '%f', '%f', '%s', '%s' )
		);
	}


	/**
	 * @param int $session_id
	 */
	public static function delete_for_session( $session_id ) {
		global $wpdb;
		$wpdb->delete( self::table(), array( 'session_id' => $session_id ), array( '%d' ) );
	}
}
