<?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;

        private static $foldername = 'pwh-dcfh-uploads';

        /**
         * Returns the singleton instance of the class.
         * @return self
         */
        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),
            ];

            return $directory[$base] ?? $directory;
        }

        /**
         * Move Files To Directory
         *
         * @param $contact_form_id
         * @param $filename
         * @param bool $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(); // phpcs:ignore
            $upload_folder = path_join(self::$foldername, "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
         * @param string $file_title
         *
         * @return array|string[]
         */
        public static function upload_files_to_media_library($file,  $file_title = '')
        {
            $attachments = ['attachment_id' => '', 'attachment_url' => ''];
            if (et_()->WPFS()->is_file($file) && et_()->WPFS()->exists($file)) {
                require_once(ABSPATH.'wp-admin/includes/image.php');
                $wp_upload_dir = wp_upload_dir();
                $file_title = !empty($file_title) ? $file_title : __('Divi Contact Form Helper', 'pwh-dcfh');
                $filename = pathinfo($file, PATHINFO_FILENAME);
                $filename_with_ext = wp_basename($file);
                $file_upload_dir = path_join($wp_upload_dir['path'], $filename_with_ext);
                $file_upload_url = path_join($wp_upload_dir['url'], $filename_with_ext);
                $file_upload_path = path_join($wp_upload_dir['path'], $filename_with_ext);
                $file_type = wp_check_filetype($filename_with_ext);
                if (copy($file, $file_upload_dir)) {
                    $attachment_data = [
                        'post_title' => $filename,
                        'post_name' => $filename,
                        'post_content' => $file_title,
                        'post_excerpt' => $file_title,
                        'post_mime_type' => $file_type['type'],
                        'post_parent' => 0,
                        'guid' => $file_upload_url,
                        'post_author' => get_current_user_id(),
                        'post_status' => 'inherit',
                        'comment_status' => 'closed',
                        'ping_status' => 'closed'
                    ];
                    $attachment_id = wp_insert_attachment($attachment_data, $file_upload_path, 0, true);
                    if (!is_wp_error($attachment_id)) {
                        $attach_data = wp_generate_attachment_metadata($attachment_id, $file_upload_path);
                        wp_update_attachment_metadata($attachment_id, $attach_data);
                        update_post_meta($attachment_id, '_wp_attachment_image_alt', $file_title);
                        $attachments = [
                            'attachment_id' => $attachment_id,
                            'attachment_url' => wp_get_attachment_url($attachment_id),
                        ];
                    }
                }

            }

            return $attachments;
        }

        /**
         * Get Temp Upload Dir
         * @return array|mixed
         */
        public static function get_tmp_upload_dir()
        {
            return self::get_wp_upload_dir(path_join(self::$foldername, 'tmp'), 'basedir');
        }

        /**
         * Get Temp Upload URL
         * @return array|mixed
         */
        public static function get_tmp_upload_url()
        {
            return self::get_wp_upload_dir(path_join(self::$foldername, 'tmp'), '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(self::$foldername, "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(self::$foldername, "forms/$contact_form_id/$subdir");
            $url = self::get_wp_upload_dir($folder, 'baseurl');

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