<?php

use Blended\hostlib\TransformImage;

/* Blended Helper Functions
 *  @since 1.0
 */

/* Returns the site URL of the home pagenow
 *  @param none
 *  @returns string containing the home page URL
 */

function blended_home_url() {
    return network_site_url();
}

/**
 * Theme activation tasks
 * @param string $code
 * @param string $function
 */
function wp_register_theme_activation_hook($code, $function) {
    $optionKey = "theme_is_activated_" . $code;
    if (!get_option($optionKey)) {
        call_user_func($function);
        update_option($optionKey, 1);
    }
}

/**
 * Get menu page url
 * @todo add it to Rest functions
 * @param string $endPointName
 * @return string
 * @throws \Exception
 */
function blendedAppUrl($endPointName) {
    try {
        if (!$endPointName)
            throw new \Exception(json_encode(array("code" => 500, "message" => 'Please provide endpoint name')));

        $url = "";
        switch ($endPointName) {

            case "Library":
                $url = admin_url('admin.php?page=' . "Library");
                break;
            case "SourceCode":
                $url = admin_url('admin.php?page=' . "Source+Code");
                break;
            case "Onboard":
                $url = admin_url('admin.php?page=' . "Onboard");

                break;
            case "Settings":
                $url = admin_url('admin.php?page=' . "Setting");
                break;
        }
    } catch (\Exception $e) {
        throw $e;
    }

    $url = json_encode($url, JSON_UNESCAPED_SLASHES);
    $url = json_decode($url, true);
    return $url;
}

/**
 * Get rest prefix
 * @global object $blendedConfig
 * @return string Rest Prefix
 */
function blended_api() {
    global $blendedConfig;
    $prefix = $blendedConfig->get('swagger', 'BASE_PATH_1');
    return $prefix;
}

/* blended image function that can call Image_Transform class
  to make transformations on images and store it into cache directory. */

/**
 * Get image object
 * @global string $CACHE_IMAGE_DIRECTORY
 * @param object $imgObject
 * @param string $filters
 * @param int $height
 * @param int $width
 * @return boolean | string
 */
function imageDB($imgObject, $height, $width, $filters) {

    global $CACHE_IMAGE_DIRECTORY;

    $image_url = str_replace('\\', '/', $imgObject['location']);
    $CACHE_IMAGE_DIRECTORY = str_replace('\\', '/', $CACHE_IMAGE_DIRECTORY);

    /* making cache image name to be created and saved with this name. */
    $save_path = str_replace('/', '_', $image_url);
    $save_path = str_replace('.', '_', $save_path);
    $save_path = str_replace(':', '_', $save_path);
    $file_extension = explode('.', $image_url);
    $count = count($file_extension);
    $file_extension = strtolower($file_extension[$count - 1]);
    if (!empty($filters)) {
        $save_path = $save_path . '_' . $height . 'x' . $width . '_' . $filters . '.' . $file_extension;
    } else {
        $save_path = $save_path . '_' . $height . 'x' . $width . '.' . $file_extension;
    }
    $save_path = str_replace('#', '', $save_path);

    // This is the final path to store output images
    $save_path = $CACHE_IMAGE_DIRECTORY . '/' . $save_path;

    /* Applying effects to image, if does not found any image in the cache directory. */
    if (!file_exists($save_path)) {
        $obj = new TransformImage($imgObject['data'], $width, $height);

        if (!empty($width) || !empty($height)) {
            $filters = 'series(fill, crop(smart))';
        } else {
            $filters = null;
        }

        // applying filters here.
        if (!empty($filters)) {
            if (strpos($filters, "series") != false) {
                $img_obj = $obj->apply_filter($filters);
            } else {
                $filters = str_replace('series(', '', $filters);
                $filters = rtrim($filters, ')');
                $img_obj = $obj->series($filters);
            }
        } else {
            $img_obj = $obj->img;
        }
        // saving image object to cache directory.
        switch ($file_extension) {
            case "jpg":
                imagejpeg($img_obj, $save_path, 100);
                break;
            case "jpeg":
                imagejpeg($img_obj, $save_path, 100);
                break;
            case "bmp":
                imagewbmp($img_obj, $save_path);
                break;
            case "png":
                imagesavealpha($img_obj, true);
                imagepng($img_obj, $save_path, 0);
                break;
            case "gif":
                imagegif($img_obj, $save_path);
                break;
            case "webp":
                imagewebp($img_obj, $save_path);
                break;
            case "default":
                imagejpeg($img_obj, $save_path, '100');
                break;
        }
        // discarding image object after saving it to cache directory.
        if (isset($img_obj)) {
            imagedestroy($img_obj);
        }
    }
    // Retrieve absolute url of an image to be returned.
    $documentRoot = $_SERVER['DOCUMENT_ROOT'];
    $documentRoot = str_replace('\\', '/', $documentRoot);
    $findroot = stripos($save_path, $documentRoot);
    $basename = basename($documentRoot);
    $basename = '/' . $basename . '/';
    $finddomain = stripos($save_path, $basename);
    if ($findroot === false && $finddomain !== false) {
        $make_absolute_url = explode($basename, $save_path);
        $make_absolute_url = $make_absolute_url[1];
    } else {
        $make_absolute_url = str_ireplace($documentRoot, "", $save_path);
    }
    $get_absolute_url = $make_absolute_url;
    return $get_absolute_url;
}

/* blended image function that can call Image_Transform class
  to make transformations on images and store it into cache directory. */

/**
 * Get image src
 * @global string $CACHE_IMAGE_DIRECTORY
 * @global string $image_specif_path
 * @param string $image_url
 * @param string $filters
 * @param int $height
 * @param int $width
 * @return boolean | string
 */
function image($image_url, $height = 0, $width = 0, $filters = null) {
    global $CACHE_IMAGE_DIRECTORY;
    global $image_specif_path;

    if (isset($image_url['backend']) && $image_url['backend'] == 'ORM') {
        $get_absolute_url = imageDB($image_url, $height, $width, $filters);
        return $get_absolute_url;
    }
    /* making image url to complete path so that to find image on the server */
    $image_data = isset($image_url['data']) ? $image_url['data'] : "";

    if (!$image_data) {
        return false;
    }
    
    //Download image if its a url
    if (filter_var($image_data, FILTER_VALIDATE_URL)) { 
        BD()->backend->downloadFile($image_url['data'], $image_url['ref_file']);
        if (file_exists($image_url['ref_part'])) {
            unlink($image_url['ref_part']);
        }
        $image_url = $image_url['ref_file'];
    } else {
        $image_url = $image_data;
    }

    $image_url = str_replace('\\', '/', $image_url);
    $CACHE_IMAGE_DIRECTORY = str_replace('\\', '/', $CACHE_IMAGE_DIRECTORY);

    if (!file_exists($image_url)) {
        $img_path = $image_specif_path . '/' . $image_url;
        $image_url = realpath($img_path);
    }



    if ($image_url == false) {
        $image_url = $img_path;
    }

    /* making cache image name to be created and saved with this name. */
    $save_path = str_replace('/', '_', $image_url);
    $save_path = str_replace('.', '_', $save_path);
    $save_path = str_replace(':', '_', $save_path);
    $file_extension = explode('.', $image_url);
    $count = count($file_extension);
    $file_extension = strtolower($file_extension[$count - 1]);
    if (!empty($filters)) {
        $save_path = $save_path . '_' . $height . 'x' . $width . '_' . $filters . '.' . $file_extension;
    } else {
        $save_path = $save_path . '_' . $height . 'x' . $width . '.' . $file_extension;
    }
    $save_path = str_replace('#', '', $save_path);

    // This is the final path to store output images
    $save_path = $CACHE_IMAGE_DIRECTORY . '/' . $save_path;

    /* Applying effects to image, if does not found any image in the cache directory. */
    if (!file_exists($save_path)) {
        $obj = new TransformImage($image_url, $width, $height);

        if (!empty($width) || !empty($height)) {
            $filters = 'series(fill, crop(smart))';
        } else {
            $filters = null;
        }

        // applying filters here.
        if (!empty($filters)) {
            if (strpos($filters, "series") != false) {
                $img_obj = $obj->apply_filter($filters);
            } else {
                $filters = str_replace('series(', '', $filters);
                $filters = rtrim($filters, ')');
                $img_obj = $obj->series($filters);
            }
        } else {
            $img_obj = $obj->img;
        }
        // saving image object to cache directory.
        switch ($file_extension) {
            case "jpg":
                imagejpeg($img_obj, $save_path, 100);
                break;
            case "jpeg":
                imagejpeg($img_obj, $save_path, 100);
                break;
            case "bmp":
                imagewbmp($img_obj, $save_path);
                break;
            case "png":
                imagesavealpha($img_obj, true);
                imagepng($img_obj, $save_path, 0);
                break;
            case "gif":
                imagegif($img_obj, $save_path);
                break;
            case "webp":
                imagewebp($img_obj, $save_path);
                break;
            case "default":
                imagejpeg($img_obj, $save_path, '100');
                break;
        }
        // discarding image object after saving it to cache directory.
        if (isset($img_obj)) {
            imagedestroy($img_obj);
        }
    }
    // Retrieve absolute url of an image to be returned.
    $documentRoot = $_SERVER['DOCUMENT_ROOT'];
    $documentRoot = str_replace('\\', '/', $documentRoot);
    $findroot = stripos($save_path, $documentRoot);
    $basename = basename($documentRoot);
    $basename = '/' . $basename . '/';
    $finddomain = stripos($save_path, $basename);
    if ($findroot === false && $finddomain !== false) {
        $make_absolute_url = explode($basename, $save_path);
        $make_absolute_url = $make_absolute_url[1];
    } else {
        $make_absolute_url = str_ireplace($documentRoot, "", $save_path);
    }
    $get_absolute_url = $make_absolute_url;
    return $get_absolute_url;
}

function css_links($theme) {

    global $THEME_DIRECTORY;
    global $ROOT_DIRECTORY;
    global $SOURCE_DIRECTORY;
    global $active_dir;
    global $DEPENDENCY_PATH;
    $context['theme'] = $theme;

    try {
        if (isset($theme['meta']['css']['compile_targets']['0'])) {
            $style_path = $theme['meta']['css']['compile_targets']['0'];
            $compiled_css = Timber::compile_string($theme['css']['blendedcss'], $context);

            $temp_style = fopen("blended_style.css", "w");
            fwrite($temp_style, $compiled_css);
            fclose($temp_style);
            $css_path = site_url() . "/blended_style.css";
            $style = $css_path;
            return $style;
        }
    } catch (\Exception $e) {
        $msg = "Exception " . $e->getCode() . " / " . $e->getMessage();
        echo "<p>$msg</p>";
    }
}

function filter_writable_props($schema) {
    return empty($schema['readonly']);
}

function prepare_response_data($error, $code) {
    switch ($code) {
        case 409:
            $schema = error_response_409_schema();
            break;
        case 412:
            $schema = error_response_412_schema();
            break;
        case 401:
            $schema = error_response_401_schema();
            break;
        case 400:
            $schema = error_response_400_schema();
            break;
        case 500:
           // $data = error_response_500_schema();
            return [];
        default:
            break;
    }

    $data = [];
    $data_keys = array_keys(array_filter($schema['properties'], 'filter_writable_props'));
    foreach ($data_keys as $key) {
        $data[$key] = $error[$key];
    }
    return $data;
}

function error_response_409_schema() {
    $schema = array(
        '$schema' => 'http://json-schema.org/draft-04/schema#',
        'title' => "Rest response for HTTP-409",
        'type' => 'object',
        'properties' => array(
            'errors' => array(
                'description' => __('Validation error.', 'blended'),
                'type' => 'array',
                'items' => array('type' => 'string',),
            ),
            'status_code' => array(
                'description' => __('Error custom status code.', 'blended'),
                'type' => 'integer',
                'format' => 'int32',
                'readonly' => true
            ),
            'purchase_packages_required' => array(
                'description' => __("Validation error.", 'blended'),
                'type' => 'array',
                'items' => array(
                    'type' => 'string',
                ),
            ),
            'purchase_packages_given' => array(
                'description' => __("Validation error.", 'blended'),
                'type' => 'array',
                'items' => array(
                    'type' => 'string',
                ),
            ),
            'auto_share_packages_required' => array(
                'description' => __("Validation error.", 'blended'),
                'type' => 'array',
                'items' => array(
                    'type' => 'string',
                ),
            ),
            'auto_share_packages_given' => array(
                'description' => __("Validation error.", 'blended'),
                'type' => 'array',
                'items' => array(
                    'type' => 'string',
                ),
            ),
        ),
    );
    return $schema;
}

function error_response_412_schema() {
    $schema = array(
        '$schema' => 'http://json-schema.org/draft-04/schema#',
        'title' => "Rest response for HTTP-412",
        'type' => 'object',
        'properties' => array(
            'error' => array(
                'description' => __('Validation error.', 'blended'),
                'type' => 'array',
                'items' => array('type' => 'string',),
            ),
            'status_code' => array(
                'description' => __('Error custom status code.', 'blended'),
                'type' => 'integer',
                'format' => 'int32',
                'readonly' => true
            ),
            'message' => array(
                'description' => __('Error message.', 'blended'),
                'type' => 'string',
                'readonly' => true
            ),
            'items' => array(
                'description' => __("Validation error. List of private dependencies.", 'blended'),
                'type' => 'array',
                'items' => array(
                    'type' => 'string',
                ),
            ),
            'data' => array(
                'description' => __("Validation error. List of paid dependencies.", 'blended'),
                'type' => 'array',
                'items' => array(
                    'type' => 'string',
                ),
            ),
        ),
    );
    return $schema;
}

function error_response_401_schema() {
    $schema = array(
        '$schema' => 'http://json-schema.org/draft-04/schema#',
        'title' => "Rest response for HTTP-401",
        'type' => 'object',
        'properties' => array(
            'error' => array(
                'description' => __('Validation error.', 'blended'),
                'type' => 'array',
                'items' => array('type' => 'string',),
            ),
            'status_code' => array(
                'description' => __('Error custom status code.', 'blended'),
                'type' => 'integer',
                'format' => 'int32',
                'readonly' => true
            ),
        ),
    );
    return $schema;
}

function error_response_400_schema() {
    $schema = array(
        '$schema' => 'http://json-schema.org/draft-04/schema#',
        'title' => "Rest response for HTTP-400",
        'type' => 'object',
        'properties' => array(
            'errors' => array(
                'description' => __('Validation error.', 'blended'),
                'type' => 'object',
            ),
            'status_code' => array(
                'description' => __('Error custom status code.', 'blended'),
                'type' => 'integer',
                'format' => 'int32',
                'readonly' => true
            ),
        ),
    );
    return $schema;
}

function error_response_500_schema() {
    $schema = array(
        '$schema' => 'http://json-schema.org/draft-04/schema#',
        'title' => "Rest response for HTTP-500",
        'type' => 'object',
        'properties' => array(
            'status_code' => array(
                'description' => __('Error custom status code.', 'blended'),
                'type' => 'integer',
                'format' => 'int32',
                'readonly' => true
            ),
            'message' => array(
                'description' => __('Error message.', 'blended'),
                'type' => 'string',
                'readonly' => true
            ),
        ),
    );
    return $schema;
}
