<?php
if ( !defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

// Hourly
if ( !wp_next_scheduled( 'mobile_api_cron_hourly' ) ) {
	wp_schedule_event( time(), 'hourly', 'mobile_api_cron_hourly' );
}
add_action( 'mobile_api_cron_hourly', 'mobile_api_update_vehicles' );
add_action( 'mobile_api_cron_hourly', 'mobile_api_delete_vehicles' );

function mobile_api_update_vehicles() {
	$last_sync = get_option( 'mobile_api_last_sync' );
	if ( empty( $last_sync ) || !mobile_api_is_licensed() ) return;

	// Retrieve all ad ids
	$url = 'https://services.mobile.de/search-api/search?page.size=100&modificationTime.min='.$last_sync;
	$json = mobile_api_request( $url );

	if ( empty( $json ) || !property_exists( $json, 'ads' ) )
		return;

	foreach ( $json->ads AS $ad ) :
		// Retrieve data of individual vehicles
		$url = 'https://services.mobile.de/search-api/ad/'.$ad->mobileAdId;
		$json = mobile_api_request( $url );

		// Check if vehicle already exists
		$args = array(
			// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
			'meta_key' => 'mobile_api_mobileAdId',
			// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value
			'meta_value' => $ad->mobileAdId,
			'post_type' => 'mobile-api-vehicle',
			'posts_per_page' => 1
		);
		$posts = get_posts( $args );

		if ( $posts )
			mobile_api_update_vehicle( $json, $posts[0]->ID );
		else
			mobile_api_create_vehicle( $json );
	endforeach;

	$now = new DateTime( 'now', new DateTimeZone( 'UTC' ) );
	update_option( 'mobile_api_last_sync', $now->format('Y-m-d\TH:i:s.0\Z') ); // ISO-8601
}

function mobile_api_delete_vehicles( $reset = false ) {
	$args = array(
		'post_type' => 'mobile-api-vehicle',
		'posts_per_page' => -1
	);
	$posts = get_posts( $args );

	if ( $posts ) :
		foreach ( $posts as $post ) :
			$post_id = $post->ID;
			$mobileAdId = get_post_meta( $post_id, 'mobile_api_mobileAdId', true );

			if ( !$reset && !empty( $mobileAdId ) ) {
				$url = 'https://services.mobile.de/search-api/ad/'.$mobileAdId;
				$json = mobile_api_request( $url );
				if ( !property_exists( $json, 'errors' ) )
					continue;
			}

			if ( has_post_thumbnail( $post_id ) )
				wp_delete_attachment( get_post_thumbnail_id( $post_id ), true );

			wp_delete_post( $post_id );

			mobile_api_log( $mobileAdId, $post_id, 'DELETE' );
		endforeach;
	endif;
}

// Weekly
if ( !wp_next_scheduled( 'mobile_api_cron_weekly' ) ) {
	wp_schedule_event( time(), 'daily', 'mobile_api_cron_weekly' );
}
add_action( 'mobile_api_cron_weekly', 'mobile_api_clean_database' );

function mobile_api_clean_database() {
	global $wpdb;

	// Delete old entries to keep databases small and clean
	$timestamp = gmdate( 'Y-m-d', strtotime( '-12 months' ) );
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
	$wpdb->get_results( $wpdb->prepare( "DELETE FROM {$wpdb->prefix}mobile_api_logs WHERE timestamp < %s", array( $timestamp ) ) );
}
