<?php

namespace PWH_DCFH\App\Admin\Cron;

if (!defined('ABSPATH')) {
    exit;
}
if (!class_exists('PWH_DCFH_Entries_Auto_Delete')) {
    class PWH_DCFH_Entries_Auto_Delete
    {
        private $hook;

        private $recurrence;

        private $interval;

        /**
         * Initializer Of The Class
         * Add/Remove Necessary Actions/Filters
         */
        public function init()
        {
            if (pwh_dcfh_db()::is_setting_enabled('pwh_dcfh_delete_entries_enabled')) {
                $schedule = pwh_dcfh_db()::get_setting('pwh_dcfh_delete_entries_schedule');
                if (!empty($schedule)) {
                    $this->hook = 'pwh_dcfh_delete_entries_'.$schedule;
                    $this->interval = $schedule;
                    $this->recurrence = 'recurrence_'.$schedule;
                    add_filter('cron_schedules', [$this, 'maybe_add_custom_schedules']);
                    add_action('init', [$this, 'maybe_schedule_event']);
                    add_action($this->hook, [$this, 'maybe_process_cron']);
                }
            }
        }

        /**
         * Add Custom Cron Interval
         *
         * @param $schedules
         *
         * @return mixed
         */
        public function maybe_add_custom_schedules($schedules)
        {
            $schedules[$this->recurrence] = [
                'interval' => ($this->interval * DAY_IN_SECONDS),
                'display' => sprintf('Every %s Days', $this->interval),
            ];

            return $schedules;
        }

        /**
         * Regsiter Cron Event In WP
         */
        public function maybe_schedule_event()
        {
            if (!wp_next_scheduled($this->hook)) {
                wp_schedule_event(time(), $this->recurrence, $this->hook);
            }
        }

        /**
         *  Cron Event Process To Perform
         */
        public function maybe_process_cron()
        {
            $statuses = (array)pwh_dcfh_db()::get_setting('pwh_dcfh_delete_entries_status');
            if (!empty($statuses)) {
                $statuses = array_filter($statuses, static function ($e) {
                    return ($e !== 'off');
                });
                $statuses = array_keys($statuses);
                if (!empty($statuses)) {
                    $posts_ids = get_posts([
                        'fields' => 'ids',
                        'post_type' => 'pwh_dcfh',
                        'post_status' => [$statuses],
                        'posts_per_page' => -1,
                        'date_query' => [['before' => "$this->interval day ago"]],
                    ]);
                    if (!empty($posts_ids)) {
                        $upload_tmp_dir = pwh_dcfh_file_helpers()::get_tmp_upload_dir();
                        foreach ($posts_ids as $post_id) {
                            $post_excerpt = get_post_field('post_excerpt', $post_id);
                            if (is_serialized($post_excerpt)) {
                                $form_entries = pwh_dcfh_helpers()::maybe_unserialize($post_excerpt);
                                if (!empty($form_entries) && is_array($form_entries)) {
                                    $contact_form_id = pwh_dcfh_post_meta_handler()::get_contact_form_id_meta_value($post_id);
                                    foreach ($form_entries as $form_entry) {
                                        if ('file' === $form_entry['type'] || 'signature_pad' === $form_entry['type']) {
                                            $attachments = explode(',', $form_entry['value']);
                                            if (!empty($attachments) && is_array($attachments)) {
                                                foreach ($attachments as $attachment) {
                                                    if (isset($form_entry['is_media_library']) && $form_entry['is_media_library']) {
                                                        $attached_medias = get_attached_media('', $post_id);
                                                        foreach ($attached_medias as $attached_media) {
                                                            wp_delete_attachment($attached_media->ID, 'true');
                                                        }
                                                    } else {
                                                        $subdir = $form_entry['subdir'] ?? '';
                                                        $upload_dir = pwh_dcfh_file_helpers()::get_form_upload_dir($contact_form_id, $subdir, $attachment);
                                                        if (et_()->WPFS()->is_file($upload_dir) && et_()->WPFS()->exists($upload_dir)) {
                                                            wp_delete_file($upload_dir);
                                                        }
                                                    }
                                                    // Delete From Temp Directory
                                                    $upload_tmp_dir = path_join($upload_tmp_dir, $attachment);
                                                    if (et_()->WPFS()->is_file($upload_tmp_dir) && et_()->WPFS()->exists($upload_tmp_dir)) {
                                                        wp_delete_file($upload_tmp_dir);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    wp_delete_post($post_id);
                                    // Delete Sent Email Logs
                                    pwh_dcfh_logger()->delete_logs('sent_email_log', $post_id);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}