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

class Woocom_Pay_DB {

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

	public static function insert( array $data ): int|false {
		global $wpdb;
		$result = $wpdb->insert( self::table(), $data );
		return $result ? $wpdb->insert_id : false;
	}

	public static function update( array $data, array $where ): bool {
		global $wpdb;
		return false !== $wpdb->update( self::table(), $data, $where );
	}

	public static function get_by_order( int $order_id ): array {
		global $wpdb;
		$table = self::table();
		$rows  = $wpdb->get_results(
			$wpdb->prepare( "SELECT * FROM {$table} WHERE order_id = %d ORDER BY id ASC", $order_id ),
			ARRAY_A
		);
		return $rows ?: [];
	}

	public static function get_by_id( int $id ): array|null {
		global $wpdb;
		$table = self::table();
		$row   = $wpdb->get_row(
			$wpdb->prepare( "SELECT * FROM {$table} WHERE id = %d", $id ),
			ARRAY_A
		);
		return $row ?: null;
	}

	public static function get_all( array $args = [] ): array {
		global $wpdb;
		$table  = self::table();
		$where  = 'WHERE 1=1';
		$params = [];

		if ( ! empty( $args['verification_status'] ) ) {
			$where   .= ' AND verification_status = %s';
			$params[] = $args['verification_status'];
		}

		$limit  = isset( $args['limit'] ) ? (int) $args['limit'] : 20;
		$offset = isset( $args['offset'] ) ? (int) $args['offset'] : 0;

		$sql = "SELECT * FROM {$table} {$where} ORDER BY id DESC LIMIT %d OFFSET %d";
		array_push( $params, $limit, $offset );

		return $wpdb->get_results(
			$wpdb->prepare( $sql, ...$params ),
			ARRAY_A
		) ?: [];
	}

	public static function count( string $status = '' ): int {
		global $wpdb;
		$table = self::table();
		if ( $status ) {
			return (int) $wpdb->get_var(
				$wpdb->prepare( "SELECT COUNT(*) FROM {$table} WHERE verification_status = %s", $status )
			);
		}
		return (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" );
	}
}
