<?php

require_once(ABSPATH . 'wp-admin/includes/file.php');

class FreshopRESTSoliloquy extends FreshopREST
{

    public function __construct()
    {
        $this->register_routes();
    }

    /**
     * Register the routes for the objects of the controller.
     */
    public function register_routes()
    {
        $version = '1';
        $namespace = 'freshop/v' . $version;

        register_rest_route($namespace, 'content/soliloquy-json', array(
            array(
                'methods' => WP_REST_Server::READABLE,
                'callback' => [&$this, 'load_soliloquy_json'],
                'permission_callback' => [$this, 'get_items_permissions_check'],
                'args' => []
            )
        ));
    }

    /**
     * Return a Soliloquy slider for a site.
     *
     * @param WP_REST_Request $request
     * @return mixed|string|WP_Error
     */
    function load_soliloquy_json(WP_REST_Request $request) {
        $store_id       = $request->get_param('store_id');
        $slider_slug    = $request->get_param('slider_slug');
        $storeGroupIds  = explode(',', get_store_group($store_id));
        $soliloquy      = Soliloquy::get_instance();
        $slider         = $soliloquy->get_slider_by_slug($slider_slug);
        $data           = [];
        $items          = [];

        if (!isset($slider_slug)) {
            return new WP_Error( 'freshop_no_slider_slug', 'Undefined slider_slug.', array( 'status' => 404 ) );
        }

        if (!$slider) {
            return new WP_Error( 'freshop_no_slider', 'Slider not found.', array( 'status' => 404 ) );
        }

        $config         = $slider['config'];
        $width          = $config['slider_width'];
        $height         = $config['slider_height'];

        foreach ($slider['slider'] as $key=>$slide) {
            $inGroup = false;

            foreach ($storeGroupIds as $groupId) {
                if (!empty($slide['custom_fields_meta_store_group_' . trim($groupId)])) {
                    $inGroup = true;
                    continue;
                }
            }

            if (!isset($store_id)) {
                $inGroup = true;
            }

            if ($inGroup && !empty($slide['schedule_meta_start']) && time() < strtotime($slide['schedule_meta_start'])) {
                $inGroup = false;
            }

            if ($inGroup && !empty($slide['schedule_meta_end']) && time() > strtotime($slide['schedule_meta_end'])) {
                $inGroup = false;
            }

            if (isset($width) && isset($height)) {
                $src = $slide['src'];
                $original = basename($src);

                $extensions = ['.jpg', '.jpeg', '.png', '.gif'];
                foreach ($extensions as $extension) {
                    if (substr($original, -strlen($extension)) == $extension) {
                        $cropped = str_replace($extension, '-' . $width . 'x' . $height . '_c' . $extension, $original);

                        $absolute = str_replace($original, $cropped, $src);
                        $relative = parse_url($absolute, PHP_URL_PATH);

                        if (file_exists(ABSPATH . $relative)) {
                            $slide['src'] = $absolute;
                        }

                        break;
                    }
                }
            }

            $status = $slide['status'];
            if ($inGroup && $status == 'active') {
                array_push($items, $slide);
            }
        }

        $data['total'] = count($items);
        $data['items'] = $items;

        return $this->send_data($data);
    }
}