<?php

// GET

if ( ! function_exists( 'wpj_get_webhook' ) ) {
	function wpj_get_webhook( $fields = '*', $where = '', $return = 'row' ) {
		$args = [
			'table'  => 'job_webhooks',
			'fields' => $fields,
			'where'  => $where,
			'return' => $return
		];

		return wpj_get_query_results( $args );
	}
}


// UPDATE

if ( ! function_exists( 'wpj_save_webhook' ) ) {
	function wpj_save_webhook( $args = [] ) {

		global $wpdb;

		$defaults = [
			'webhook_id'       => false,
			'payment_id'       => false,
			'status'           => false,
			'type'             => false,
			'description'      => false,
			'amount'           => false,
			'amount_currency'  => false,
			'fees'             => false,
			'fees_currency'    => false,
			'create_time'      => false,
			'payment_response' => false,
			'payment_type'     => false,
			'order_id'         => false
		];

		$args = wp_parse_args( $args, $defaults );

		$webhook_id       = $args['webhook_id'];
		$payment_id       = $args['payment_id'];
		$status           = $args['status'];
		$type             = $args['type'];
		$description      = $args['description'];
		$amount           = $args['amount'];
		$amount_currency  = $args['amount_currency'];
		$fees             = $args['fees'];
		$fees_currency    = $args['fees_currency'];
		$create_time      = $args['create_time'];
		$payment_response = $args['payment_response'];
		$payment_type     = $args['payment_type'];
		$order_id         = $args['order_id'];

		if ( ! wpj_get_webhook( 'webhook_id', ['webhook_id' => $webhook_id], 'row' ) ) {

			$wpdb->query( "INSERT INTO {$wpdb->prefix}job_webhooks VALUES ( NULL, '{$webhook_id}', '{$payment_id}', '{$status}', '{$type}', '{$description}', '{$amount}', '{$amount_currency}', '{$fees}', '{$fees_currency}', '{$create_time}', '{$payment_response}', '{$payment_type}', '{$order_id}' )" );

			return true;
		}

		return false;

	}
}

if ( ! function_exists( 'wpj_update_webhook' ) ) {
	function wpj_update_webhook( $data, $where ) {
		global $wpdb;

		if ( empty( $data ) === true ) return 0;

		if ( empty( $where ) === true ) return 0;

		$is_updated = $wpdb->update( $wpdb->prefix . 'job_webhooks', $data, $where );

		if ( $is_updated === false ) return 0;

		return $is_updated;
	}
}