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

class Gift_Card_Pro_Cron
{

    public function __construct()
    {
        add_filter('cron_schedules', array($this, 'add_one_minute_interval'));
        add_action('init', array($this, 'schedule_cron_event'));
        add_action('wpgv_cron_recipients_email', array($this, 'send_recipient_email'));
    }

    public function add_one_minute_interval($schedules)
    {
        $schedules['one_minute'] = array(
            'interval' => 60, // 60 seconds = 1 minute
            'display'  => __('Every 1 Minute')
        );
        return $schedules;
    }

    public function schedule_cron_event()
    {
        $wpgv_allow_future_date = get_option('wpgv_allow_future_date', 0);

        // Only schedule cron job if $wpgv_allow_future_date is 1
        if ($wpgv_allow_future_date == 1) {
            if (!wp_next_scheduled('wpgv_cron_recipients_email')) {
                wp_schedule_event(time(), 'one_minute', 'wpgv_cron_recipients_email');
            }
        } else {
            // Clear the scheduled event if $wpgv_allow_future_date is not 1
            $timestamp = wp_next_scheduled('wpgv_cron_recipients_email');
            if ($timestamp) {
                wp_unschedule_event($timestamp, 'wpgv_cron_recipients_email');
            }
        }
    }

    public function send_recipient_email()
    {
        global $wpdb;

        $voucher_table = $wpdb->prefix . 'giftvouchers_list';
        $setting_table = $wpdb->prefix . 'giftvouchers_setting';
        $setting_options = $wpdb->get_row("SELECT * FROM $setting_table WHERE id = 1");

        // Get all vouchers that need to send email
        $vouchers = $wpdb->get_results("SELECT * FROM $voucher_table WHERE payment_status = 'Paid' AND email_send_date_time != 'send_instantly' AND check_send_mail = 'schedule'");

        if ($vouchers) {
            foreach ($vouchers as $voucher_options) {
                $voucher_id = $voucher_options->id;
                $email_send_date_time = $voucher_options->email_send_date_time;

                // Adjust the email send time by subtracting 1 hour
                $adjusted_email_send_time = date('Y-m-d H:i:s', strtotime($email_send_date_time . ' -5 minute'));

                // Get the current server time
                $current_time = current_time('mysql');
                $current_timestamp = current_time('timestamp');

                // // Log current time and adjusted email send time for debugging
                // error_log("Current time: $current_time, Adjusted email send time: $adjusted_email_send_time");

                // Compare the current time with the adjusted email send time
                if ($current_timestamp >= strtotime($adjusted_email_send_time)) {
                    $recipientemailsubject = get_option('wpgv_recipientemailsubject') ? get_option('wpgv_recipientemailsubject') : 'Gift Voucher - You have received a voucher from {company_name}';
                    $recipientemailbody = get_option('wpgv_recipientemailbody') ? get_option('wpgv_recipientemailbody') : '<p>Dear <strong>{recipient_name}</strong>,</p><p>You have received a gift voucher from <strong>{customer_name}</strong>.</p><p>You can download the voucher from {pdf_link}.</p><p>- For any clarifications please feel free to email us at {sender_email}.</p><p><strong>Warm Regards, <br /></strong> <strong>{company_name}<br />{website_url}</strong></p>';

                    $upload = wp_upload_dir();
                    $upload_dir = $upload['basedir'];
                    $attachments[0] = $upload_dir . '/voucherpdfuploads/' . $voucher_options->voucherpdf_link . '.pdf';
                    $headers = 'Content-type: text/html;charset=utf-8' . "\r\n";
                    $headers .= 'From: ' . stripslashes($setting_options->sender_name) . ' <' . $setting_options->sender_email . '>' . "\r\n";
                    $headers .= 'Reply-to: ' . stripslashes($setting_options->sender_name) . ' <' . $setting_options->sender_email . '>' . "\r\n";

                    /* Recipient Mail */
                    if ($voucher_options->shipping_type != 'shipping_as_post') {
                        $recipientsub = wpgv_mailvarstr($recipientemailsubject, $setting_options, $voucher_options);
                        $recipientmsg = wpgv_mailvarstr($recipientemailbody, $setting_options, $voucher_options);
                        $recipientto = stripslashes($voucher_options->to_name) . '<' . $voucher_options->shipping_email . '>';
                        if ($voucher_options->buying_for == 'yourself') {
                            $recipientto = stripslashes($voucher_options->from_name) . '<' . $voucher_options->email . '>';
                        }
                        // Send email
                        $schedule = wp_mail($recipientto, $recipientsub, $recipientmsg, $headers, $attachments);
                        if ($schedule) {
                            // Update status if email is sent successfully
                            $wpdb->update(
                                $voucher_table,
                                array('check_send_mail' => 'sent'),
                                array('id' => $voucher_id)
                            );
                        }
                    }
                }
            }
        }
    }
}

// Initialize the cron functionality
new Gift_Card_Pro_Cron();
