<?php

// GET

if ( ! function_exists( 'wpj_get_user_credit_log' ) ) {
	function wpj_get_user_credit_log( $fields = '*', $where = '', $return = 'row', $between = [] ) {
		if ( $between ) {
			if ( ! empty( $between['date_min'] ) && empty( $between['date_max'] ) )
				$where['fields_date'] = sprintf( ' AND %s >= %d ', $between['column'], $between['date_min'] );

			else if ( empty( $between['date_min'] ) && ! empty( $between['date_max'] ) )
				$where['fields_date'] = sprintf( ' AND %s <= %d ', $between['column'], $between['date_max'] );

			else if ( $between['date_min'] && $between['date_max'] )
				$where['fields_date'] = sprintf( ' AND %s >= %d AND %s <= %d', $between['column'], $between['date_min'], $between['column'], $between['date_max'] );
 		}

		$args = [
			'table'  => 'job_credits_balance_log',
			'fields' => $fields,
			'where'  => $where,
			'return' => $return
		];

		return wpj_get_query_results( $args );
	}
}

// INSERT

if ( ! function_exists( 'wpj_insert_user_credit_log' ) ) {
	function wpj_insert_user_credit_log( $data, $format, $uid = '' ) {
		global $wpdb;

		if ( ! $uid ) $uid = get_current_user_id();

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

		$data['datemade']       = current_time( 'timestamp', 1 );
		$data['uid']            = $uid;
		$data['credit_balance'] = wpj_get_user_credit( $uid );

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

		$format[] = '%d';
		$format[] = '%d';
		$format[] = '%f';

		$is_inserted = $wpdb->insert( $wpdb->prefix . 'job_credits_balance_log', $data, $format );

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

		return $wpdb->insert_id;
	}
}

if ( ! function_exists( 'wpj_insert_site_earnings' ) ) {
	function wpj_insert_site_earnings( $data, $format ) {
		global $wpdb;

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

		$data['datemade'] = current_time( 'timestamp', 1 );

		$format[] = '%d';

		$row_exist = $wpdb->get_var(
			$wpdb->prepare(
				"
				SELECT id
				FROM {$wpdb->prefix}job_admin_earnings
				WHERE datemade = %d
					AND orderid = %d
					AND pid = %d
					AND admin_fee = %s
				",
				$data['datemade'],
				$data['orderid'],
				$data['pid'],
				$data['admin_fee']
			)
		);

		if ( empty( $row_exist ) === false ) return 0;

		$is_inserted = $wpdb->insert( $wpdb->prefix . 'job_admin_earnings', $data, $format );

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

		return $wpdb->insert_id;
	}
}