<?php

defined('ABSPATH') or die('No script kiddies please!!');
if (!class_exists('STD_Downloader')) {

    class STD_Downloader extends STD_Library {

        function __construct() {
            add_action('template_redirect', array($this, 'initialize_downloader'));
        }

        function initialize_downloader() {
            if (!empty($_REQUEST['std_encryption_key']) && !empty($_REQUEST['form'])) {
                $encryption_key = sanitize_text_field($_REQUEST['std_encryption_key']);
                $form_alias = sanitize_text_field($_REQUEST['form']);
                global $wpdb;
                $subscriber_table = STD_SUBSCRIBERS_TABLE;
                $subscriber_row = $wpdb->get_row($wpdb->prepare("select * from $subscriber_table where subscriber_encryption_key = %s", $encryption_key));
                $form_row = $this->get_form_row_by_alias($form_alias);
                $form_details = maybe_unserialize($form_row->form_details);

                /**
                 * Link expiry check
                 */
                if (!empty($form_details['general']['link_expire']) && !empty($form_details['general']['link_expire_time'])) {
                    $transient_name = 'std_' . $encryption_key;
                    $is_not_expired = get_transient($transient_name);
                    if (false === $is_not_expired) {
                        die($this->output_converting_br($form_details['general']['link_expire_message']));
                    }
                }
                if (empty($subscriber_row) || empty($form_row)) {
                    return;
                }
                $user_ip = $this->get_user_IP();
                $key_check = false;
                if ($user_ip == $subscriber_row->subscribed_user_ip) {
                    $key_check = true;
                }
                if (isset($_COOKIE['std_encryption_key']) && $encryption_key == $_COOKIE['std_encryption_key']) {
                    $key_check = true;
                }

                if ($key_check) {
                    if (empty($form_details['general']['download_file_id'])) {
                        // If download file is not available in the settings
                        return;
                    }
                    $download_path = get_attached_file(intval($form_details['general']['download_file_id']));
                    $subscriber_email = $subscriber_row->subscriber_email;
                    $subscriber_name = $subscriber_row->subscriber_name;
                    if (!empty($form_details['email']['download_notification'])) {
                        $download_file_name = basename($form_details['general']['download_file']);
                        $download_notification_subject = $form_details['email']['download_notification_subject'];
                        $download_notification_subject = str_replace('#download_file', $download_file_name, $download_notification_subject);
                        $download_notification_email_message = $form_details['email']['download_notification_email_message'];
                        $download_notification_email_message = str_replace('#download_file', $download_file_name, $download_notification_email_message);
                        $download_notification_email_message = str_replace('#email', $subscriber_email, $download_notification_email_message);
                        $download_notification_email_message = str_replace('#name', $subscriber_name, $download_notification_email_message);
                        /**
                         * Here we will do the custom fields processing
                         */
                        $form_data_cf = maybe_unserialize($subscriber_row->subscriber_custom_fields);
                        if (!empty($form_details['form']['custom_fields'])) {
                            $custom_field_html_array = [];
                            foreach ($form_details['form']['custom_fields'] as $custom_field_key => $custom_field_details) {
                                $field_type = $custom_field_details['field_type'];
                                if ($field_type == 'hidden') {
                                    $custom_field_details['show'] = 1;
                                }
                                if (!empty($custom_field_details['show'])) {

                                    $custom_field_label =  $custom_field_details['label'];

                                    if (!empty($form_data_cf[$custom_field_key])) {

                                        $custom_field_value = (is_array($form_data_cf[$custom_field_key])) ? implode(', ', $form_data_cf[$custom_field_key]) : $form_data_cf[$custom_field_key];
                                    } else {
                                        $custom_field_value = '';
                                    }
                                    $custom_field_html_array[] = $custom_field_label . ': ' . $custom_field_value;
                                }
                            }
                            $custom_field_html = implode('<br/>', $custom_field_html_array);
                        }
                        $download_notification_email_message = str_replace('#custom_fields', $custom_field_html, $download_notification_email_message);
                        $from_email = (!empty($form_details['email']['from_email'])) ? $form_details['email']['from_email'] : $this->get_default_from_email();
                        $from_name = (!empty($form_details['email']['from_name'])) ? $form_details['email']['from_name'] : esc_html__('No Reply', 'subscribe-to-download');
                        $charset = get_option('blog_charset');
                        $headers[] = 'Content-Type: text/html; charset=' . $charset;
                        $headers[] = "From: $from_name <$from_email>";
                        $admin_email = get_option('admin_email');
                        $notification_emails = (!empty($form_details['email']['download_notification_emails'])) ? explode(',', $form_details['email']['download_notification_emails']) : array($admin_email);
                        add_filter('wp_mail_content_type', array($this, 'wpdocs_set_html_mail_content_type'));
                        foreach ($notification_emails as $notification_email) {

                            wp_mail($notification_email, $download_notification_subject, $download_notification_email_message, $headers);
                        }
                        remove_filter('wp_mail_content_type', array($this, 'wpdocs_set_html_mail_content_type'));
                    }
                    if (empty($form_details['general']['download_file_id'])) {
                        $download_url = $form_details['general']['download_file'];
                        wp_redirect($download_url);
                        exit;
                    }

                    /**
                     * Filters download path
                     *
                     * @param string $download_path
                     * @param string $encryption_key
                     *
                     * @since 1.0.0
                     */
                    $download_path = apply_filters('std_download_path', $download_path, $encryption_key);
                    if (file_exists($download_path)) {
                        setcookie("std_download_verified_key", $encryption_key, time() + 3600 * 24 * 365, '/');
                        header('Content-Description: File Transfer');
                        header('Content-Type: application/octet-stream');
                        header('Content-Disposition: attachment; filename="' . basename($download_path) . '"');
                        header('Expires: 0');
                        header('Cache-Control: must-revalidate');
                        header('Pragma: public');
                        header('Content-Length: ' . filesize($download_path));
                        readfile($download_path);
                        $this->update_download_status($encryption_key);
                        exit;
                    }
                }
            }
        }

        function update_download_status($encryption_key) {
            global $wpdb;
            $wpdb->update(STD_SUBSCRIBERS_TABLE, array('subscriber_download_status' => 1), array('subscriber_encryption_key' => $encryption_key), array('%d'), array('%s'));
        }
    }

    new STD_Downloader();
}
