<?php

namespace PWH_DCFH\App\Helpers;

if (!defined('ABSPATH')) exit;
if (!class_exists('PWH_DCFH_File_Helpers')) {
    class PWH_DCFH_File_Helpers
    {
        private static $_instance;

        /**
         * Get Class Instance
         * @return PWH_DCFH_File_Helpers
         */
        public static function instance()
        {
            if (self::$_instance == null) {
                self::$_instance = new self();
            }

            return self::$_instance;
        }

        /**
         * Create DIR
         *
         * @param $folder
         * @param bool $in_base
         *
         * @return bool
         */
        public static function create_dir($folder, $in_base = true)
        {

            $wp_upload_dir = wp_upload_dir();
            $path = path_join($wp_upload_dir['path'], $folder);
            $base_dir = path_join($wp_upload_dir['basedir'], $folder);
            $make_dir = $base_dir;
            if (!$in_base) {
                $make_dir = $path;
            }
            if (!is_dir($make_dir)) {
                wp_mkdir_p($make_dir);
                $index_file = path_join($make_dir, 'index.php');
                if (!et_()->WPFS()->exists($index_file)) {
                    et_()->WPFS()->put_contents($index_file, "<?php // Silence is golden.");
                }
                $htaccess_file = path_join($make_dir, '.htaccess');
                if (!et_()->WPFS()->exists($htaccess_file)) {
                    et_()->WPFS()->put_contents($htaccess_file, "## Prevent Directory Indexes\n\nOptions -Indexes");
                }

                return true;
            }

            return false;
        }

        /**
         * Get Year Month Dir
         * @return array
         */
        public static function get_subdir()
        {
            $time = current_time('mysql');

            return [
                substr($time, 0, 4),
                substr($time, 5, 2),
            ];
        }

        /**
         * Upload DIR
         *
         * @param $folder
         * @param null $base
         *
         * @return array|mixed
         */
        public static function get_wp_upload_dir($folder, $base = null)
        {
            $wp_upload_dir = wp_upload_dir();
            $directory = [
                'basedir' => path_join($wp_upload_dir['basedir'], $folder),
                'baseurl' => path_join($wp_upload_dir['baseurl'], $folder),
            ];
            if (isset($directory[$base])) {
                return $directory[$base];
            }

            return $directory;
        }

        /**
         * Move Files To Directory
         *
         * @param $contact_form_id
         * @param $filename
         * @param $is_increment
         *
         * @return array|false
         */
        public static function upload_files_to_dir($contact_form_id, $filename, $is_increment = false)
        {
            list($y, $m) = self::get_subdir();
            $upload_folder = path_join(pwh_dcfh_hc()::UPLOAD_DIR, "forms/$contact_form_id/$y/$m/");
            $upload_basedir = self::get_wp_upload_dir($upload_folder, 'basedir');
            $upload_baseurl = self::get_wp_upload_dir($upload_folder, 'baseurl');
            if (!is_dir($upload_basedir)) {
                if (!wp_mkdir_p($upload_basedir)) {
                    return false;
                }
                $index_file = path_join($upload_basedir, 'index.php');
                if (!et_()->WPFS()->exists($index_file)) {
                    et_()->WPFS()->put_contents($index_file, "<?php // Silence is golden.");
                }
                $htaccess_file = path_join($upload_basedir, '.htaccess');
                if (!et_()->WPFS()->exists($htaccess_file)) {
                    et_()->WPFS()->put_contents($htaccess_file, "## Prevent Directory Indexes\n\nOptions -Indexes");
                }
            }
            $file_extension = pathinfo($filename, PATHINFO_EXTENSION);
            $file_extension = '.'.$file_extension;
            $filename = sanitize_file_name(wp_basename($filename, $file_extension));
            $counter = 1;
            $basedir = path_join($upload_basedir, $filename.$file_extension);
            while ($is_increment && file_exists($basedir)) {
                $basedir = $upload_basedir.$filename."$counter".$file_extension;
                $counter++;
            }
            $basedir = trim($basedir, '.');
            $baseurl = str_replace($upload_basedir, $upload_baseurl, $basedir);

            return ['basedir' => $basedir, 'baseurl' => $baseurl];
        }

        /**
         * Attachments To Media
         *
         * @param $file
         *
         * @return array|string[]
         */
        public static function upload_files_to_media_library($file)
        {
            require_once(ABSPATH.'wp-admin/includes/media.php');
            require_once(ABSPATH.'wp-admin/includes/file.php');
            require_once(ABSPATH.'wp-admin/includes/image.php');
            $attachment_data = ['attachment_id' => '', 'attachment_url' => ''];
            if (wp_http_validate_url($file) && !empty($file)) {
                $download_url = download_url($file);
                if (!is_wp_error($download_url)) {
                    $filename = wp_basename($file);
                    $wp_filetype = wp_check_filetype($filename);
                    $upload_file['tmp_name'] = $download_url;
                    $upload_file['name'] = $filename;
                    $post_data = [
                        'post_mime_type' => $wp_filetype['type'],
                        'post_parent' => 0,
                        'post_author' => get_current_user_id(),
                        'post_title' => $filename,
                        'post_name' => $filename,
                        'post_status' => 'inherit',
                        'comment_status' => 'closed',
                        'ping_status' => 'closed'
                    ];
                    $attachment_id = media_handle_sideload($upload_file, 0, __('Divi Contact Form Attachment', 'pwh-dcfh'), $post_data);
                    if (!is_wp_error($attachment_id) && $attachment_id > 0) {
                        update_post_meta($attachment_id, '_wp_attachment_image_alt', $filename);
                        $attachment_data = [
                            'attachment_id' => $attachment_id,
                            'attachment_url' => wp_get_attachment_url($attachment_id),
                        ];
                    }
                }
            }

            return $attachment_data;
        }

        /**
         * Get Temp Upload Dir
         * @return array|mixed
         */
        public static function get_temp_upload_dir()
        {
            return self::get_wp_upload_dir(path_join(pwh_dcfh_hc()::UPLOAD_DIR, pwh_dcfh_hc()::TEMP_UPLOAD_DIR), 'basedir');
        }

        /**
         * Get Temp Upload URL
         * @return array|mixed
         */
        public static function get_temp_upload_url()
        {
            return self::get_wp_upload_dir(path_join(pwh_dcfh_hc()::UPLOAD_DIR, pwh_dcfh_hc()::TEMP_UPLOAD_DIR), 'baseurl');
        }

        /**
         * Get Upload Dir
         *
         * @param $contact_form_id
         * @param $subdir
         * @param $file
         *
         * @return string
         */
        public static function get_form_upload_dir($contact_form_id, $subdir, $file)
        {

            $folder = path_join(pwh_dcfh_hc()::UPLOAD_DIR, "forms/$contact_form_id/$subdir");
            $dir = self::get_wp_upload_dir($folder, 'basedir');

            return path_join($dir, $file);
        }

        /**
         * Get Upload URL
         *
         * @param $contact_form_id
         * @param $subdir
         * @param $file
         *
         * @return string
         */
        public static function get_form_upload_url($contact_form_id, $subdir, $file)
        {
            $folder = path_join(pwh_dcfh_hc()::UPLOAD_DIR, "forms/$contact_form_id/$subdir");
            $url = self::get_wp_upload_dir($folder, 'baseurl');

            return path_join($url, $file);
        }
    }
}