<?php
/*
 * Million Dollar Script Two
 *
 * @author      Ryan Rhode
 * @copyright   (C) 2025, Ryan Rhode
 * @license     https://opensource.org/licenses/GPL-3.0 GNU General Public License, version 3
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *
 *    Million Dollar Script
 *    Pixels to Profit: Ignite Your Revolution
 *    https://milliondollarscript.com/
 *
 */

use MillionDollarScript\Classes\Data\Options;
use MillionDollarScript\Classes\System\Functions;

defined( 'ABSPATH' ) or exit;

ini_set( 'max_execution_time', 300 );

global $wpdb;

if ( isset( $_REQUEST['mds-action'] ) ) {
	if ( $_REQUEST['mds-action'] == 'delall' ) {

		$sql = "SELECT * FROM " . MDS_DB_PREFIX . "mail_queue";
		$result = $wpdb->get_results( $sql );
		if ( $wpdb->last_error ) {
			die( 'Database error: ' . $wpdb->last_error );
		}
		foreach ( $result as $row ) {

			if ( $row->att1_name != '' ) {
				unlink( $row->att1_name );
			}

			if ( $row->att2_name != '' ) {
				unlink( $row->att2_name );
			}

			if ( $row->att3_name != '' ) {
				unlink( $row->att3_name );
			}

			$wpdb->delete( 
				MDS_DB_PREFIX . 'mail_queue', 
				array( 'mail_id' => intval( $row->mail_id ) ), 
				array( '%d' ) 
			);
			if ( $wpdb->last_error ) {
				die( 'Database error: ' . $wpdb->last_error );
			}
		}
	}
	if ( $_REQUEST['mds-action'] == 'delsent' ) {
		$sql = "SELECT * FROM " . MDS_DB_PREFIX . "mail_queue WHERE status = 'sent'";
		$result = $wpdb->get_results( $sql );
		if ( $wpdb->last_error ) {
			die( 'Database error: ' . $wpdb->last_error );
		}
		foreach ( $result as $row ) {

			if ( $row->att1_name != '' ) {
				unlink( $row->att1_name );
			}

			if ( $row->att2_name != '' ) {
				unlink( $row->att2_name );
			}

			if ( $row->att3_name != '' ) {
				unlink( $row->att3_name );
			}

			$wpdb->delete( 
				MDS_DB_PREFIX . 'mail_queue', 
				array( 'mail_id' => intval( $row->mail_id ) ), 
				array( '%d' ) 
			);
			if ( $wpdb->last_error ) {
				die( 'Database error: ' . $wpdb->last_error );
			}
		}
	}
	if ( $_REQUEST['mds-action'] == 'delerror' ) {
		$sql = "SELECT * FROM " . MDS_DB_PREFIX . "mail_queue WHERE status = 'error'";
		$result = $wpdb->get_results( $sql );
		if ( $wpdb->last_error ) {
			die( 'Database error: ' . $wpdb->last_error );
		}
		foreach ( $result as $row ) {

			if ( $row->att1_name != '' ) {
				unlink( $row->att1_name );
			}

			if ( $row->att2_name != '' ) {
				unlink( $row->att2_name );
			}

			if ( $row->att3_name != '' ) {
				unlink( $row->att3_name );
			}

			$wpdb->delete( 
				MDS_DB_PREFIX . 'mail_queue', 
				array( 'mail_id' => intval( $row->mail_id ) ), 
				array( '%d' ) 
			);
			if ( $wpdb->last_error ) {
				die( 'Database error: ' . $wpdb->last_error );
			}
		}
	}
	if ( $_REQUEST['mds-action'] == 'resend' ) {

		$wpdb->update( 
			MDS_DB_PREFIX . 'mail_queue', 
			array( 'status' => 'queued' ), 
			array( 'mail_id' => intval( $_REQUEST['mail_id'] ) ), 
			array( '%s' ), 
			array( '%d' ) 
		);
		if ( $wpdb->last_error ) {
			die( 'Database error: ' . $wpdb->last_error );
		}

		process_mail_queue( 1, $_REQUEST['mail_id'] );
	}
}

$EMAILS_PER_BATCH = Options::get_option( 'emails-per-batch' );
if ( $EMAILS_PER_BATCH == '' ) {
	$EMAILS_PER_BATCH = 10;
}

if ( isset( $_REQUEST['mds-action'] ) && $_REQUEST['mds-action'] == 'send' ) {
	process_mail_queue( $EMAILS_PER_BATCH );
}

if ( isset( $_POST['mds_dest'] ) ) {
	return;
}

$q_username = isset( $_REQUEST['q_username'] ) && is_string( $_REQUEST['q_username'] ) ? $_REQUEST['q_username'] : '';

$q_to_add          = isset( $_REQUEST['q_to_add'] ) && is_string( $_REQUEST['q_to_add'] ) ? $_REQUEST['q_to_add'] : '';
$q_to_name         = isset( $_REQUEST['q_to_name'] ) && is_string( $_REQUEST['q_to_name'] ) ? $_REQUEST['q_to_name'] : '';
$q_subj            = isset( $_REQUEST['q_subj'] ) && is_string( $_REQUEST['q_subj'] ) ? $_REQUEST['q_subj'] : '';
$q_msg             = isset( $_REQUEST['q_msg'] ) && is_string( $_REQUEST['q_msg'] ) ? $_REQUEST['q_msg'] : '';
$q_status          = isset( $_REQUEST['q_status'] ) && is_string( $_REQUEST['q_status'] ) ? $_REQUEST['q_status'] : '';
$q_type            = isset( $_REQUEST['q_type'] ) ? intval( $_REQUEST['q_type'] ) : 0;
$search            = isset( $_REQUEST['search'] ) && is_string( $_REQUEST['search'] ) ? $_REQUEST['search'] : '';
$q_string          = "&q_to_add=$q_to_add&q_subj=$q_subj&q_to_name=$q_to_name&q_msg=$q_msg&q_status=$q_status&q_type=$q_type&search=$search";
$additional_params = [
	'q_to_add'  => $q_to_add,
	'q_subj'    => $q_subj,
	'q_to_name' => $q_to_name,
	'q_msg'     => $q_msg,
	'q_status'  => $q_status,
	'q_type'    => $q_type,
	'search'    => $search
];

$sql = "SELECT COUNT(*) as c FROM " . MDS_DB_PREFIX . "mail_queue";
$total = $wpdb->get_var( $sql );
if ( $wpdb->last_error ) {
	die( 'Database error: ' . $wpdb->last_error );
}

$sql = "SELECT COUNT(*) as c FROM " . MDS_DB_PREFIX . "mail_queue WHERE status = 'queued'";
$queued = $wpdb->get_var( $sql );
if ( $wpdb->last_error ) {
	die( 'Database error: ' . $wpdb->last_error );
}

$sql = "SELECT COUNT(*) as c FROM " . MDS_DB_PREFIX . "mail_queue WHERE status = 'sent'";
$sent = $wpdb->get_var( $sql );
if ( $wpdb->last_error ) {
	die( 'Database error: ' . $wpdb->last_error );
}

$sql = "SELECT COUNT(*) as c FROM " . MDS_DB_PREFIX . "mail_queue WHERE status = 'error'";
$error = $wpdb->get_var( $sql );
if ( $wpdb->last_error ) {
	die( 'Database error: ' . $wpdb->last_error );
}

?>
<?php echo $total; ?> Total Email(s) |
<?php echo $queued; ?> Email(s) on Queue |
<?php echo $sent; ?> Email(s) Sent |
<?php echo $error; ?> Email(s) Failed<br>
    <input type='button' value="Delete Sent" onclick="window.location.href='<?php echo esc_url( admin_url( 'admin.php?page=mds-outgoing-email&mds-action=delsent' . $q_string ) ); ?>'">
    | <input type='button' value="Delete Error" onclick="window.location.href='<?php echo esc_url( admin_url( 'admin.php?page=mds-outgoing-email&mds-action=delerror' . $q_string ) ); ?>'">
    | <input type='button' value="Delete All" onclick="window.location.href='<?php echo esc_url( admin_url( 'admin.php?page=mds-outgoing-email&mds-action=delall' . $q_string ) ); ?>'">

    <br>

    <hr>
<form style="margin: 0" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" method="post">
<?php wp_nonce_field( 'mds-admin' ); ?>
    <input type="hidden" name="action" value="mds_admin_form_submission"/>
    <input type="hidden" name="mds_dest" value="outgoing-email"/>
    <input type="hidden" name="search" value="Y"/>

    <div class="table-responsive">
        <table>

            <tr>
                <td>
                    To Addr
                </td>
                <td>
                    <label>
                        <input type="text" name="q_to_add" size="39" value="<?php echo $q_to_add; ?>"/>
                    </label>
                </td>
                <td>
                    To Name
                </td>
                <td>
                    <label>
                        <input type="text" name="q_to_name" size="28" value="<?php echo $q_to_name; ?>"/>
                    </label>
                </td>
            </tr>
            <tr>
                <td>
                    Subject
                </td>
                <td>
                    <label>
                        <input type="text" name="q_subj" size="39" value="<?php echo $q_subj; ?>"/>
                    </label>
                </td>
                <td>
                    Message
                </td>
                <td>
                    <label>
                        <input type="text" name="q_msg" size="28" value="<?php echo $q_msg; ?>"/>
                    </label>
                </td>
            </tr>
            <tr>
                <td>
                    Status
                </td>
                <td>

                    <label>
                        <select name="q_status">
                            <option value='' <?php if ( $q_status == '' ) {
								echo ' selected ';
							} ?>></option>
                            <option value='queued' <?php if ( $q_status == 'queued' ) {
								echo ' selected ';
							} ?>>queued
                            </option>
                            <option value='error' <?php if ( $q_status == 'error' ) {
								echo ' selected ';
							} ?>>error
                            </option>
                            <option value='sent' <?php if ( $q_status == 'sent' ) {
								echo ' selected ';
							} ?>>sent
                            </option>
                        </select>
                    </label>
                </td>
                <td>
                    Type
                </td>
                <td>
                    <label>
                        <select name="q_type">
                            <option value='' <?php if ( $q_type == '' ) {
								echo ' selected ';
							} ?>></option>
                            <option value='1' <?php if ( $q_type == '1' ) {
								echo ' selected ';
							} ?>>1 - Complete Order
                            </option>
                            <option value='2' <?php if ( $q_type == '2' ) {
								echo ' selected ';
							} ?>>2 - Confirm Order
                            </option>
                            <option value='3' <?php if ( $q_type == '3' ) {
								echo ' selected ';
							} ?>>3 - Pend Order
                            </option>
                            <option value='4' <?php if ( $q_type == '4' ) {
								echo ' selected ';
							} ?>>4 - Expire Order
                            </option>
                            <option value='5' <?php if ( $q_type == '5' ) {
								echo ' selected ';
							} ?>>5 - Account Confirmation
                            </option>
                            <option value='6' <?php if ( $q_type == '6' ) {
								echo ' selected ';
							} ?>>6 - Forgot Pass
                            </option>
                            <option value='7' <?php if ( $q_type == '7' ) {
								echo ' selected ';
							} ?>>7 - Pixels Published
                            </option>
                            <option value='8' <?php if ( $q_type == '8' ) {
								echo ' selected ';
							} ?>>8 - Order Renewed
                            </option>
                        </select>
                    </label>
                </td>
            </tr>
            <tr>
                <td colspan="4">

                    <input type="submit" value="Find Emails" name="B1">
					<?php if ( $search == 'y' ) { ?>
                        &nbsp; [<a href="<?php echo esc_url( admin_url( 'admin.php?page=mds-outgoing-email' ) ); ?>">Start a New Search</a>]
					<?php } ?>
                </td>
            </tr>
        </table>
    </div>
<?php
$where_conditions = array();
$where_values = array();
$where_formats = array();

if ( $q_to_add != '' ) {
	$where_conditions[] = "to_address LIKE %s";
	$where_values[] = '%' . $wpdb->esc_like( $q_to_add ) . '%';
	$where_formats[] = '%s';
}

if ( $q_to_name != '' ) {
	$where_conditions[] = "to_name LIKE %s";
	$where_values[] = '%' . $wpdb->esc_like( $q_to_name ) . '%';
	$where_formats[] = '%s';
}

if ( $q_msg != '' ) {
	$where_conditions[] = "message LIKE %s";
	$where_values[] = '%' . $wpdb->esc_like( $q_msg ) . '%';
	$where_formats[] = '%s';
}

if ( $q_subj != '' ) {
	$where_conditions[] = "subject LIKE %s";
	$where_values[] = '%' . $wpdb->esc_like( $q_subj ) . '%';
	$where_formats[] = '%s';
}

if ( ! empty( $q_type ) ) {
	$where_conditions[] = "template_id = %s";
	$where_values[] = $q_type;
	$where_formats[] = '%s';
}

if ( $q_status != '' ) {
	$where_conditions[] = "status = %s";
	$where_values[] = $q_status;
	$where_formats[] = '%s';
}

$where_sql = '';
if ( ! empty( $where_conditions ) ) {
	$where_sql = ' WHERE ' . implode( ' AND ', $where_conditions );
}

$sql = "SELECT * FROM " . MDS_DB_PREFIX . "mail_queue" . $where_sql . " ORDER BY mail_date DESC";

if ( ! empty( $where_values ) ) {
	$sql = $wpdb->prepare( $sql, $where_values );
}

$result = $wpdb->get_results( $sql );
if ( $wpdb->last_error ) {
	die( 'Database error: ' . $wpdb->last_error );
}
$count = count( $result );

$records_per_page = 40;
$offset           = isset( $_REQUEST['offset'] ) ? intval( $_REQUEST['offset'] ) : 0;

// Apply pagination by slicing the results array
if ( $count > $records_per_page ) {
	$result = array_slice( $result, $offset, $records_per_page );
}
if ( $count > $records_per_page ) {
	$pages    = ceil( $count / $records_per_page );
	$cur_page = $offset / $records_per_page;
	$cur_page ++;

	?>
    <div style="text-align: center;"><?php echo $count; ?> Emails on Queue returned (<?php echo $pages; ?> pages)</div>
	<?php
	echo Functions::generate_navigation( $cur_page, $count, $records_per_page, $additional_params, admin_url( 'admin.php?page=mds-outgoing-email' ) );
}

?>
    <div class="table-responsive">
        <table>
            <tr>
                <th>Date</th>
                <th>Type</th>
                <th>To Addr</th>
                <th>To Name</th>
                <th>Fr Addr</th>
                <th>Fr Name</th>
                <th>Subj</th>
                <th>Msg</th>
                <th>Html Msg</th>
                <th>Att</th>
                <th>Status</th>
                <th>Err</th>
                <th>Retry</th>
                <th>Action</th>
            </tr>
			<?php

			$i = 0;
			foreach ( $result as $row ) {
				if ( $i >= $records_per_page ) break;
				$i ++;

				?>

                <tr>
                    <td><?php echo get_date_from_gmt( $row->mail_date ); ?></td>
                    <td><?php echo $row->template_id; ?></td>
                    <td><?php echo $row->to_address; ?></td>
                    <td><?php echo $row->to_name; ?></td>
                    <td><?php echo $row->from_address; ?></td>
                    <td><?php echo $row->from_name; ?></td>
                    <td><?php echo substr( $row->subject, 0, 7 ); ?><a
                                href="<?php echo esc_url( admin_url( 'admin.php?page=mds-show-email' ) ); ?>&amp;mail_id=<?php echo intval( $row->mail_id ); ?>">...</a>
                    </td>
                    <td><?php echo substr( $row->message, 0, 7 ); ?><a
                                href="<?php echo esc_url( admin_url( 'admin.php?page=mds-show-email' ) ); ?>&amp;mail_id=<?php echo intval( $row->mail_id ); ?>">...</a>
                    </td>
                    <td><?php echo substr( $row->html_message, 0, 7 ); ?><a
                                href="<?php echo esc_url( admin_url( 'admin.php?page=mds-show-email' ) ); ?>&amp;mail_id=<?php echo intval( $row->mail_id ); ?>">...</a></td>
                    <td><?php echo $row->attachments; ?></td>
                    <td><span style="color: <?php if ( $row->status == 'sent' ) {
							echo 'green';
						} ?>; "><?php echo $row->status; ?></td>
                    <td><?php echo $row->error_msg; ?></td>
                    <td><?php echo $row->retry_count; ?></td>
                    <td><a href='<?php echo esc_url( admin_url( 'admin.php?page=mds-outgoing-email&mds-action=resend&mail_id=' . $row->mail_id . $q_string ) ); ?>'>Resend</a></td>
                </tr>

				<?php
			}

			?>

        </table>
    </div>
<?php
if ( $count > $records_per_page ) {
	$pages    = ceil( $count / $records_per_page );
	$cur_page = $offset / $records_per_page;
	$cur_page ++;

	echo Functions::generate_navigation( $cur_page, $count, $records_per_page, $additional_params, admin_url( 'admin.php?page=mds-outgoing-email' ) );
}

?>