<?php
/**
 * Email Logger Class
 *
 * Handles logging of all emails sent by the subscription system
 *
 * @link       https://mediahubster.in
 * @since      1.0.6
 *
 * @package    Subs_Sys
 * @subpackage Subs_Sys/includes
 */

// If this file is called directly, abort.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! class_exists( 'Subs_Sys_Email_Logger' ) ) {
	/**
	 * Handles email logging functionality.
	 *
	 * @since      1.0.6
	 * @package    Subs_Sys
	 * @subpackage Subs_Sys/includes
	 * @author     Media Hubster <support@subscriptionplugin.com>
	 */
	class Subs_Sys_Email_Logger {

		/**
		 * Log an email that was sent
		 *
		 * @param array $email_data Email data to log
		 * @return int|false Log ID on success, false on failure
		 */
		public static function log_email( $email_data ) {
			global $wpdb;

			// Check if table exists
			if ( ! Subs_Sys_DB_Updater::email_logs_table_exists() ) {
				error_log( 'Subs_Sys: Email logs table does not exist. Skipping log.' );
				return false;
			}

			$table_name = $wpdb->prefix . 'subscription_email_logs';

			// Prepare data
			$insert_data = array(
				'user_id'          => isset( $email_data['user_id'] ) ? absint( $email_data['user_id'] ) : null,
				'recipient_email'  => sanitize_email( $email_data['recipient_email'] ),
				'recipient_name'   => isset( $email_data['recipient_name'] ) ? sanitize_text_field( $email_data['recipient_name'] ) : null,
				'post_id'          => isset( $email_data['post_id'] ) ? absint( $email_data['post_id'] ) : null,
				'post_title'       => isset( $email_data['post_title'] ) ? sanitize_text_field( $email_data['post_title'] ) : null,
				'post_url'         => isset( $email_data['post_url'] ) ? esc_url_raw( $email_data['post_url'] ) : null,
				'content_plan_id'  => isset( $email_data['content_plan_id'] ) ? absint( $email_data['content_plan_id'] ) : null,
				'subject'          => sanitize_text_field( $email_data['subject'] ),
				'email_type'       => isset( $email_data['email_type'] ) ? sanitize_text_field( $email_data['email_type'] ) : 'content_notification',
				'status'           => isset( $email_data['status'] ) ? sanitize_text_field( $email_data['status'] ) : 'sent',
				'error_message'    => isset( $email_data['error_message'] ) ? sanitize_text_field( $email_data['error_message'] ) : null,
				'sent_at'          => current_time( 'mysql' )
			);

			// Insert log
			$result = $wpdb->insert( $table_name, $insert_data );

			if ( false === $result ) {
				error_log( 'Subs_Sys: Failed to insert email log: ' . $wpdb->last_error );
				return false;
			}

			return $wpdb->insert_id;
		}

		/**
		 * Get email logs with pagination and filtering
		 *
		 * @param array $args Query arguments
		 * @return array Array of log objects
		 */
		public static function get_logs( $args = array() ) {
			global $wpdb;

			// Check if table exists
			if ( ! Subs_Sys_DB_Updater::email_logs_table_exists() ) {
				return array();
			}

			$table_name = $wpdb->prefix . 'subscription_email_logs';

			$defaults = array(
				'email_type'      => '',
				'status'          => '',
				'user_id'         => 0,
				'post_id'         => 0,
				'recipient_email' => '',
				'orderby'         => 'sent_at',
				'order'           => 'DESC',
				'limit'           => 20,
				'offset'          => 0,
				'search'          => ''
			);

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

			// Build WHERE clause
			$where_conditions = array( '1=1' );

			if ( ! empty( $args['email_type'] ) ) {
				$where_conditions[] = $wpdb->prepare( 'email_type = %s', $args['email_type'] );
			}

			if ( ! empty( $args['status'] ) ) {
				$where_conditions[] = $wpdb->prepare( 'status = %s', $args['status'] );
			}

			if ( ! empty( $args['user_id'] ) ) {
				$where_conditions[] = $wpdb->prepare( 'user_id = %d', $args['user_id'] );
			}

			if ( ! empty( $args['post_id'] ) ) {
				$where_conditions[] = $wpdb->prepare( 'post_id = %d', $args['post_id'] );
			}

			if ( ! empty( $args['recipient_email'] ) ) {
				$where_conditions[] = $wpdb->prepare( 'recipient_email = %s', $args['recipient_email'] );
			}

			if ( ! empty( $args['search'] ) ) {
				$search_term = '%' . $wpdb->esc_like( $args['search'] ) . '%';
				$where_conditions[] = $wpdb->prepare( 
					'(recipient_email LIKE %s OR recipient_name LIKE %s OR post_title LIKE %s OR subject LIKE %s)',
					$search_term,
					$search_term,
					$search_term,
					$search_term
				);
			}

			$where_clause = 'WHERE ' . implode( ' AND ', $where_conditions );

			// Build ORDER BY clause
			$orderby = sanitize_sql_orderby( $args['orderby'] . ' ' . $args['order'] );
			$order_clause = $orderby ? "ORDER BY $orderby" : 'ORDER BY sent_at DESC';

			// Build LIMIT clause
			$limit_clause = '';
			if ( $args['limit'] > 0 ) {
				$limit_clause = $wpdb->prepare( 'LIMIT %d OFFSET %d', $args['limit'], $args['offset'] );
			}

			// Execute query
			$sql = "SELECT * FROM $table_name $where_clause $order_clause $limit_clause";
			$logs = $wpdb->get_results( $sql );

			return $logs ? $logs : array();
		}

		/**
		 * Count email logs with filtering
		 *
		 * @param array $args Query arguments
		 * @return int Count of logs
		 */
		public static function count_logs( $args = array() ) {
			global $wpdb;

			// Check if table exists
			if ( ! Subs_Sys_DB_Updater::email_logs_table_exists() ) {
				return 0;
			}

			$table_name = $wpdb->prefix . 'subscription_email_logs';

			$defaults = array(
				'email_type'      => '',
				'status'          => '',
				'user_id'         => 0,
				'post_id'         => 0,
				'recipient_email' => '',
				'search'          => ''
			);

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

			// Build WHERE clause
			$where_conditions = array( '1=1' );

			if ( ! empty( $args['email_type'] ) ) {
				$where_conditions[] = $wpdb->prepare( 'email_type = %s', $args['email_type'] );
			}

			if ( ! empty( $args['status'] ) ) {
				$where_conditions[] = $wpdb->prepare( 'status = %s', $args['status'] );
			}

			if ( ! empty( $args['user_id'] ) ) {
				$where_conditions[] = $wpdb->prepare( 'user_id = %d', $args['user_id'] );
			}

			if ( ! empty( $args['post_id'] ) ) {
				$where_conditions[] = $wpdb->prepare( 'post_id = %d', $args['post_id'] );
			}

			if ( ! empty( $args['recipient_email'] ) ) {
				$where_conditions[] = $wpdb->prepare( 'recipient_email = %s', $args['recipient_email'] );
			}

			if ( ! empty( $args['search'] ) ) {
				$search_term = '%' . $wpdb->esc_like( $args['search'] ) . '%';
				$where_conditions[] = $wpdb->prepare( 
					'(recipient_email LIKE %s OR recipient_name LIKE %s OR post_title LIKE %s OR subject LIKE %s)',
					$search_term,
					$search_term,
					$search_term,
					$search_term
				);
			}

			$where_clause = 'WHERE ' . implode( ' AND ', $where_conditions );

			// Execute query
			$sql = "SELECT COUNT(*) FROM $table_name $where_clause";
			return (int) $wpdb->get_var( $sql );
		}

		/**
		 * Delete old email logs
		 *
		 * @param int $days Number of days to keep (delete older than this)
		 * @return int Number of rows deleted
		 */
		public static function delete_old_logs( $days = 90 ) {
			global $wpdb;

			// Check if table exists
			if ( ! Subs_Sys_DB_Updater::email_logs_table_exists() ) {
				return 0;
			}

			$table_name = $wpdb->prefix . 'subscription_email_logs';
			$date_threshold = date( 'Y-m-d H:i:s', strtotime( "-{$days} days" ) );

			$deleted = $wpdb->query( $wpdb->prepare(
				"DELETE FROM $table_name WHERE sent_at < %s",
				$date_threshold
			) );

			if ( false !== $deleted ) {
				error_log( "Subs_Sys: Deleted {$deleted} email logs older than {$days} days" );
			}

			return $deleted !== false ? $deleted : 0;
		}

		/**
		 * Clear all email logs
		 *
		 * @return int Number of rows deleted
		 */
		public static function clear_all_logs() {
			global $wpdb;

			// Check if table exists
			if ( ! Subs_Sys_DB_Updater::email_logs_table_exists() ) {
				return 0;
			}

			$table_name = $wpdb->prefix . 'subscription_email_logs';
			$deleted = $wpdb->query( "TRUNCATE TABLE $table_name" );

			if ( false !== $deleted ) {
				error_log( 'Subs_Sys: Cleared all email logs' );
			}

			return $deleted !== false ? $deleted : 0;
		}

		/**
		 * Get email statistics
		 *
		 * @return array Statistics array
		 */
		public static function get_statistics() {
			global $wpdb;

			// Check if table exists
			if ( ! Subs_Sys_DB_Updater::email_logs_table_exists() ) {
				return array(
					'total'      => 0,
					'sent'       => 0,
					'failed'     => 0,
					'today'      => 0,
					'this_week'  => 0,
					'this_month' => 0
				);
			}

			$table_name = $wpdb->prefix . 'subscription_email_logs';

			$stats = array();

			// Total emails
			$stats['total'] = (int) $wpdb->get_var( "SELECT COUNT(*) FROM $table_name" );

			// Sent emails
			$stats['sent'] = (int) $wpdb->get_var( $wpdb->prepare(
				"SELECT COUNT(*) FROM $table_name WHERE status = %s",
				'sent'
			) );

			// Failed emails
			$stats['failed'] = (int) $wpdb->get_var( $wpdb->prepare(
				"SELECT COUNT(*) FROM $table_name WHERE status = %s",
				'failed'
			) );

			// Today
			$stats['today'] = (int) $wpdb->get_var( $wpdb->prepare(
				"SELECT COUNT(*) FROM $table_name WHERE DATE(sent_at) = %s",
				current_time( 'Y-m-d' )
			) );

			// This week
			$stats['this_week'] = (int) $wpdb->get_var( $wpdb->prepare(
				"SELECT COUNT(*) FROM $table_name WHERE YEARWEEK(sent_at, 1) = YEARWEEK(%s, 1)",
				current_time( 'Y-m-d H:i:s' )
			) );

			// This month
			$stats['this_month'] = (int) $wpdb->get_var( $wpdb->prepare(
				"SELECT COUNT(*) FROM $table_name WHERE YEAR(sent_at) = YEAR(%s) AND MONTH(sent_at) = MONTH(%s)",
				current_time( 'Y-m-d H:i:s' ),
				current_time( 'Y-m-d H:i:s' )
			) );

			return $stats;
		}

		/**
		 * Delete a specific log entry
		 *
		 * @param int $log_id Log ID
		 * @return bool True on success, false on failure
		 */
		public static function delete_log( $log_id ) {
			global $wpdb;

			// Check if table exists
			if ( ! Subs_Sys_DB_Updater::email_logs_table_exists() ) {
				return false;
			}

			$table_name = $wpdb->prefix . 'subscription_email_logs';
			$result = $wpdb->delete( $table_name, array( 'id' => absint( $log_id ) ) );

			return false !== $result;
		}
	}
}


