<?php

namespace Miladmodaresi\Taamito\Base;

class Taamito extends Singleton
{
    public function view($name, array $args = array())
    {
        if (!is_string($name)) {
            echo json_encode($name);
            return exit(1);
        }

        ob_start();
        $args = apply_filters('taamito_view_arguments', $args, $name);

        foreach ($args as $key => $val) {
            $$key = $val;
        }

        $file = TAAMITO_PLUGIN_DIR . 'views/' . $name . '.php';

        include($file);

        $out = ob_get_clean();
        echo $out;
        return $out;
    }

    public function createAdminPage($title, $slug, $callBack, $icon)
    {
        return add_menu_page(__($title, $title), __($title, $title), 'manage_options', $slug, $callBack, $icon, 99);
    }


    function normalize_files($files)
    {
        $files2 = [];
        foreach ($files as $input => $infoArr) {
            $filesByInput = [];
            foreach ($infoArr as $key => $valueArr) {
                if (is_array($valueArr)) { // file input "multiple"
                    foreach ($valueArr as $i => $value) {
                        $filesByInput[$input][$i][$key] = $value;
                    }
                } else { // -> string, normal file input
                    $filesByInput[$input] = $infoArr;
                    break;
                }
            }
            $files2 = array_merge($files2, $filesByInput);
        }
        $files3 = [];
        foreach ($files2 as $key => $file) { // let's filter empty & errors
            if (!$file['error']) $files3[$key] = $file;
        }
        return $files3;
    }

    public function uploadImage($file, $details)
    {
        require_once(ABSPATH . 'wp-includes/pluggable.php');
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        require_once(ABSPATH . 'wp-admin/includes/image.php');

        if (is_string($file)) {
            $temp = download_url($file);
            $fileName = basename($file);
            $file = [
                'name' => $fileName,
                'type' => mime_content_type($temp),
                'tmp_name' => $temp,
                'error' => UPLOAD_ERR_OK,
                'size' => filesize($temp)
            ];
        }
        $file = wp_handle_sideload($file, array('test_form' => FALSE));

        $fileId = wp_insert_attachment(
            array(
                'guid' => $file['url'],
                'post_title' => sanitize_text_field($details['name'] ?? ''),
                'post_excerpt' => sanitize_text_field(isset($details['excerpt']) ? $details['excerpt'] : ''),
                'post_content' => sanitize_text_field(isset($details['content']) ? $details['content'] : ''),
                'post_mime_type' => $file['type'],
            ),
            $file['file'],
            0
        );

        return $fileId;
    }

    public function deleteImage($fileId)
    {
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        require_once(ABSPATH . 'wp-admin/includes/image.php');

        $fileId = wp_delete_attachment($fileId);

        return $fileId;
    }

    public function deleteImages($fileIds)
    {
        foreach ($fileIds as $id)
            $this->deleteImage($id);
    }

    public function ajax($name, $callBack)
    {
        return add_action("wp_ajax_taamito_{$name}", $callBack);
    }

    public function addCss($name, $address)
    {
        wp_register_style("taamito-$name", TAAMITO_PLUGIN_URL . "assets/css/{$address}", array());
        wp_enqueue_style("taamito-$name");
    }

    public function addJs($name, $address, $setAjaxUrl = false)
    {
        wp_register_script("taamito-$name", TAAMITO_PLUGIN_URL . "assets/js/{$address}", array('jquery'));
        if ($setAjaxUrl)
            wp_localize_script(
                "taamito-$name",
                'ajax_object',
                array('ajax_url' => admin_url('admin-ajax.php'))
            );
        wp_enqueue_script("taamito-$name");
    }

    public function saveOption($key, $value)
    {
        return update_option('taamito_' . $key, $value);
    }

    public function deleteOption($key)
    {
        return delete_option('taamito_' . $key);
    }

    public function getOption($key)
    {
        return get_option('taamito_' . $key);
    }
}
