<?php

namespace KaizenCoders\MagicLink\EmailDigest;

use KaizenCoders\MagicLink\Helper;

class ReportGenerator {

	public function generate( $frequency = 'weekly', $is_preview = false ) {
		list( $start, $end ) = $this->get_time_range( $frequency, $is_preview );

		$generated_links = $this->get_generated_links_count( $start, $end );
		$used_links      = $this->get_used_links_count( $start, $end );
		$is_pro          = KC_ML()->is_pro();

		return [
			'start_date'           => $start,
			'end_date'             => $end,
			'date_range_label'     => wp_date( 'M j, Y', $start ) . ' - ' . wp_date( 'M j, Y', $end ),
			'frequency'            => $frequency,
			'is_preview'           => $is_preview,
			'is_pro'               => $is_pro,
			'site_name'            => get_bloginfo( 'name' ),
			'site_url'             => home_url(),
			'generated_links'      => $generated_links,
			'used_links'           => $used_links,
			'active_links'         => $this->get_active_links_count( $start, $end ),
			'expired_unused_links' => $this->get_expired_unused_links_count( $start, $end ),
			'unique_users'         => $this->get_unique_users_count( $start, $end ),
			'use_rate'             => $generated_links > 0 ? (int) round( ( $used_links / $generated_links ) * 100 ) : null,
			// Always fetch 3 rows; template blurs them for free users.
			'top_users'            => $this->get_top_users( $start, $end, 3 ),
			'recent_links'         => $this->get_recent_links( $start, $end ),
			'news_items'           => $this->get_news_items(),
		];
	}

	private function get_time_range( $frequency, $is_preview ) {
		$timezone = wp_timezone();
		$now      = new \DateTimeImmutable( 'now', $timezone );

		if ( $is_preview ) {
			$end   = $now->getTimestamp();
			$start = $end - ( 7 * DAY_IN_SECONDS );

			return [ $start, $end ];
		}

		switch ( $frequency ) {
			case 'daily':
				$yesterday = $now->modify( 'yesterday' );
				return [
					$yesterday->setTime( 0, 0, 0 )->getTimestamp(),
					$yesterday->setTime( 23, 59, 59 )->getTimestamp(),
				];
			case 'monthly':
				$start = $now->modify( 'first day of last month' )->setTime( 0, 0, 0 );
				$end   = $now->modify( 'last day of last month' )->setTime( 23, 59, 59 );
				return [ $start->getTimestamp(), $end->getTimestamp() ];
			default:
				$start_of_week            = (int) get_option( 'start_of_week', 1 );
				$day_of_week              = (int) $now->format( 'w' );
				$days_since_start_of_week = ( $day_of_week - $start_of_week + 7 ) % 7;
				$current_week_start       = $now->modify( '-' . $days_since_start_of_week . ' days' )->setTime( 0, 0, 0 );
				$last_week_start          = $current_week_start->modify( '-7 days' );
				$last_week_end            = $current_week_start->modify( '-1 second' );
				return [ $last_week_start->getTimestamp(), $last_week_end->getTimestamp() ];
		}
	}

	private function get_generated_links_count( $start, $end ) {
		global $wpdb;

		$table = $wpdb->prefix . 'kc_ml_magic_links';

		return (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*) FROM {$table} WHERE created_at BETWEEN %s AND %s",
				gmdate( 'Y-m-d H:i:s', $start ),
				gmdate( 'Y-m-d H:i:s', $end )
			)
		);
	}

	private function get_used_links_count( $start, $end ) {
		global $wpdb;

		$table = $wpdb->prefix . 'kc_ml_magic_links';

		return (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*) FROM {$table} WHERE used = 1 AND created_at BETWEEN %s AND %s",
				gmdate( 'Y-m-d H:i:s', $start ),
				gmdate( 'Y-m-d H:i:s', $end )
			)
		);
	}

	private function get_active_links_count( $start, $end ) {
		global $wpdb;

		$table = $wpdb->prefix . 'kc_ml_magic_links';
		$now   = gmdate( 'Y-m-d H:i:s', current_time( 'timestamp', true ) );

		return (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*) FROM {$table} WHERE used = 0 AND expires >= %s AND created_at BETWEEN %s AND %s",
				$now,
				gmdate( 'Y-m-d H:i:s', $start ),
				gmdate( 'Y-m-d H:i:s', $end )
			)
		);
	}

	private function get_expired_unused_links_count( $start, $end ) {
		global $wpdb;

		$table = $wpdb->prefix . 'kc_ml_magic_links';
		$now   = gmdate( 'Y-m-d H:i:s', current_time( 'timestamp', true ) );

		return (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(*) FROM {$table} WHERE used = 0 AND expires < %s AND created_at BETWEEN %s AND %s",
				$now,
				gmdate( 'Y-m-d H:i:s', $start ),
				gmdate( 'Y-m-d H:i:s', $end )
			)
		);
	}

	private function get_unique_users_count( $start, $end ) {
		global $wpdb;

		$table = $wpdb->prefix . 'kc_ml_magic_links';

		return (int) $wpdb->get_var(
			$wpdb->prepare(
				"SELECT COUNT(DISTINCT user_id) FROM {$table} WHERE created_at BETWEEN %s AND %s",
				gmdate( 'Y-m-d H:i:s', $start ),
				gmdate( 'Y-m-d H:i:s', $end )
			)
		);
	}

	private function get_top_users( $start, $end, $limit = 5 ) {
		global $wpdb;

		$table       = $wpdb->prefix . 'kc_ml_magic_links';
		$users_table = $wpdb->users;

		return $wpdb->get_results(
			$wpdb->prepare(
				"SELECT ml.user_id, u.display_name, u.user_email, COUNT(*) AS generated_count,
					SUM(CASE WHEN ml.used = 1 THEN 1 ELSE 0 END) AS used_count
				FROM {$table} AS ml
				LEFT JOIN {$users_table} AS u ON u.ID = ml.user_id
				WHERE ml.created_at BETWEEN %s AND %s
				GROUP BY ml.user_id
				ORDER BY generated_count DESC, used_count DESC, ml.user_id DESC
				LIMIT %d",
				gmdate( 'Y-m-d H:i:s', $start ),
				gmdate( 'Y-m-d H:i:s', $end ),
				$limit
			)
		);
	}

	private function get_recent_links( $start, $end, $limit = 5 ) {
		global $wpdb;

		$table       = $wpdb->prefix . 'kc_ml_magic_links';
		$users_table = $wpdb->users;

		return $wpdb->get_results(
			$wpdb->prepare(
				"SELECT ml.*, u.display_name, u.user_email
				FROM {$table} AS ml
				LEFT JOIN {$users_table} AS u ON u.ID = ml.user_id
				WHERE ml.created_at BETWEEN %s AND %s
				ORDER BY ml.created_at DESC, ml.id DESC
				LIMIT %d",
				gmdate( 'Y-m-d H:i:s', $start ),
				gmdate( 'Y-m-d H:i:s', $end ),
				$limit
			)
		);
	}

	private function get_news_items() {
		$items = [
			[
				'badge'       => __( 'Tip', 'magic-link' ),
				'title'       => __( 'Add Magic Link to a custom login page', 'magic-link' ),
				'description' => __( 'Use the shortcode to offer passwordless login anywhere on your site, including landing pages and member portals.', 'magic-link' ),
				'url'         => 'https://docs.kaizencoders.com/magic-link/shortcode-login-form',
				'url_label'   => __( 'Learn more ->', 'magic-link' ),
			],
			[
				'badge'       => __( 'Tip', 'magic-link' ),
				'title'       => __( 'Enable Magic Link on the default login screen', 'magic-link' ),
				'description' => __( 'Turn on the login form option so users can request a secure sign-in link from wp-login.php without extra setup.', 'magic-link' ),
				'url'         => 'https://docs.kaizencoders.com/magic-link/login-from-wordpress',
				'url_label'   => __( 'Learn more ->', 'magic-link' ),
			],
			[
				'badge'       => __( 'Tip', 'magic-link' ),
				'title'       => __( 'Tighten access with PRO security controls', 'magic-link' ),
				'description' => __( 'Use IP checks, request throttling, brute-force protection, and domain restriction to harden passwordless login.', 'magic-link' ),
				'url'         => 'https://kaizencoders.com/magic-link',
				'url_label'   => __( 'Explore PRO ->', 'magic-link' ),
			],

			[
				'badge'       => 'Tip',
				'title'       => __( 'Monitor WordPress Activity using Logify', 'url-shortify' ),
				'description' => __( 'Gain clear insights into events happening on your site, track changes effortlessly, and ensure accountability.', 'url-shortify' ),
				'url'         => 'https://kaizencoders.com/logify',
				'url_label'   => __( 'Learn more →', 'magic-link' ),
			],

			[
				'badge'       => 'Tip',
				'title'       => __( 'Ever wanted to do search and replace in WordPress?', 'url-shortify' ),
				'description' => __( 'Search & Replace Everything – Quick and Easy Way to Find and Replace Text, Links using Update URLS', 'url-shortify' ),
				'url'         => 'https://wordpress.org/plugins/update-urls/',
				'url_label'   => __( 'Learn more →', 'magic-link' ),
			],

			[
				'badge'       => 'Tip',
				'title'       => __( 'Want to create, manage, and track short links in WordPress effortlessly?', 'url-shortify' ),
				'description' => __( 'URL Shortify lets you generate branded short links, track clicks, and optimize your link performance—all from your WordPress dashboard.', 'url-shortify' ),
				'url'         => 'https://wordpress.org/plugins/url-shortify/',
				'url_label'   => __( 'Learn more →', 'url-shortify' ),
			],

		];


		// Tag every news item URL with UTM so click-through can be attributed
		// back to the email digest campaign.
		$utm = apply_filters(
			'kc_ml_news_items_utm',
			array(
				'source'   => 'email-digest',
				'medium'   => 'news-item',
				'campaign' => 'magic-link-news',
			)
		);
		foreach ( $items as $i => $item ) {
			if ( ! empty( $item['url'] ) ) {
				$items[ $i ]['url'] = Helper::add_utm_params( $item['url'], $utm );
			}
		}

		return [ $items[ array_rand( $items ) ] ];
	}
}
