<?php

namespace WPT\Recipe\Recipe;

/**
 * Recipe.
 */
class Recipe {
    protected $container;

    protected $fields;

    /**
     * Constructor.
     */
    public function __construct( $post_id, $container ) {
        $this->post_id = $post_id;
        $this->container = $container;
        $this->fields = [];
    }

    /**
     * Get author
     */
    public function get_author() {
        if ( !isset( $this->fields['author'] ) ) {
            $author_type = carbon_get_post_meta( $this->post_id, 'wpt_recipe_author' );
            $author = '';
            $url = '';
            $image = '';
            switch ( $author_type ) {
                case 'post_author':
                    $current_post = get_post( $this->post_id );
                    $author = get_the_author_meta( 'display_name', $current_post->post_author );
                    $url = get_the_author_meta( 'user_url', $current_post->post_author );
                    $image = get_avatar_url( $current_post->post_author );
                    break;
                case 'custom':
                    $author = carbon_get_post_meta( $this->post_id, 'wpt_recipe_author_name' );
                    $url = carbon_get_post_meta( $this->post_id, 'wpt_recipe_author_url' );
                    $image = carbon_get_post_meta( $this->post_id, 'wpt_recipe_author_img' );
                    break;
                default:
                    # code...
                    break;
            }
            $this->fields['author'] = [
                'type'  => $author_type,
                'name'  => $author,
                'image' => $image,
                'url'   => $url,
            ];
        }
        return $this->fields['author'];
    }

    /**
     * Get categories
     * todo : add others.
     */
    public function get_categories() {
        if ( !isset( $this->fields['categories'] ) ) {
            $categories = carbon_get_post_meta( $this->post_id, 'wpt_recipe_categories' );
            if ( !is_array( $categories ) ) {
                $categories = [];
            }
            $others = trim( carbon_get_post_meta( $this->post_id, 'wpt_recipe_categories_others' ) );
            if ( $others ) {
                $others = array_map( 'trim', explode( ',', $others ) );
                $categories = array_merge( $categories, $others );
            }
            $this->fields['categories']['raw'] = $categories;
            $this->fields['categories']['formatted'] = implode( ', ', $categories );
        }
        return $this->fields['categories'];
    }

    /**
     * Get cook_time
     */
    public function get_cook_time() {
        if ( !isset( $this->fields['cook_time'] ) ) {
            $this->fields['cook_time']['raw'] = carbon_get_post_meta( $this->post_id, 'wpt_recipe_cook_time' );
            $this->fields['cook_time']['formatted'] = $this->fields['cook_time']['raw']['value'];
        }
        return $this->fields['cook_time'];
    }

    /**
     * Get cost
     */
    public function get_cost() {
        if ( !isset( $this->fields['cost'] ) ) {
            $this->fields['cost'] = carbon_get_post_meta( $this->post_id, 'wpt_recipe_cost' );
        }
        return $this->fields['cost'];
    }

    /**
     * Get cuisines
     * todo: get others
     */
    public function get_cuisines() {
        if ( !isset( $this->fields['cuisines'] ) ) {
            $cuisines = carbon_get_post_meta( $this->post_id, 'wpt_recipe_cuisines' );
            if ( !is_array( $cuisines ) ) {
                $cuisines = [];
            }
            $others = trim( carbon_get_post_meta( $this->post_id, 'wpt_recipe_cuisines_others' ) );
            if ( $others ) {
                $others = array_map( 'trim', explode( ',', $others ) );
                $cuisines = array_merge( $cuisines, $others );
            }
            $this->fields['cuisines']['raw'] = $cuisines;
            $this->fields['cuisines']['formatted'] = implode( ', ', $cuisines );
        }
        return $this->fields['cuisines'];
    }

    /**
     * Get description
     */
    public function get_description() {
        if ( !isset( $this->fields['description'] ) ) {
            $this->fields['description'] = carbon_get_post_meta( $this->post_id, 'wpt_recipe_description' );
        }
        return $this->fields['description'];
    }

    public function get_notes() {
        if ( !isset( $this->fields['notes'] ) ) {
            $this->fields['notes'] = carbon_get_post_meta( $this->post_id, 'wpt_recipe_notes' );
        }
        return $this->fields['notes'];
    }

    public function get_formatted_ingredients( $ingredients, $create_link = true ) {
        $output = [];
        foreach ( $ingredients as $group ) {
            foreach ( $group['ingredients'] as $ingredient ) {
                if ( !isset( $ingredient['ingredient'], $ingredient['ingredient'][0], $ingredient['ingredient'][0]['id'] ) ) {
                    continue;
                }
                $ingredient_id = $ingredient['ingredient'][0]['id'];
                $link = carbon_get_post_meta( $ingredient_id, 'wpt_recipe_ingredient_affliate_link' );
                $name = get_the_title( $ingredient_id );
                if ( $create_link && $link ) {
                    $name = sprintf( '<a href="%s" target="_blank">%s</a>', $link, $name );
                }
                $formatted_value = sprintf(
                    '%s%s%s%s',
                    ( $ingredient['quantity'] ? trim( $ingredient['quantity'] ) . ' ' : '' ),
                    ( $ingredient['unit'] ? trim( $ingredient['unit'] ) . ' ' . __( 'of', 'food-recipes' ) . ' ' : '' ),
                    trim( $name ),
                    ( $ingredient['notes'] ? ', ' . trim( $ingredient['notes'] ) : '' )
                );
                $output[$group['group_name']][] = $formatted_value;
            }
        }
        return $output;
    }

    /**
     * Get image
     */
    public function get_image() {
        if ( !isset( $this->fields['image'] ) ) {
            $this->fields['image'] = carbon_get_post_meta( $this->post_id, 'wpt_recipe_image' );
            if ( $this->fields['image'] ) {
                $this->fields['image'] = wp_get_attachment_metadata( $this->fields['image'] );
            }
        }
        return $this->fields['image'];
    }

    public function get_image_src() {
        $src = '';
        $image = $this->get_image();
        $upload_dir = wp_upload_dir();
        if ( isset( $image['file'] ) ) {
            $src = $upload_dir['baseurl'] . '/' . $image['file'];
        }
        return $src;
    }

    /**
     * Get ingredients
     * todo: format data.
     */
    public function get_ingredients() {
        if ( !isset( $this->fields['ingredients'] ) ) {
            $ingredients = carbon_get_post_meta( $this->post_id, 'wpt_recipe_ingredients' );
            $this->fields['ingredients']['raw'] = $ingredients;
        }
        return $this->fields['ingredients'];
    }

    /**
     * Get image
     */
    public function get_instruction_type() {
        if ( !isset( $this->fields['instruction_type'] ) ) {
            $this->fields['instruction_type'] = carbon_get_post_meta( $this->post_id, 'wpt_recipe_instruction_type' );
        }
        return $this->fields['instruction_type'];
    }

    /**
     * Get instructions
     */
    public function get_simple_instructions() {
        if ( !isset( $this->fields['instructions'] ) ) {
            $this->fields['instructions']['raw'] = carbon_get_post_meta( $this->post_id, 'wp_recipe_simple_instructions' );
            $permalink = get_the_permalink();
            // format data
            $formatted = [];
            foreach ( $this->fields['instructions']['raw'] as $i => $instruction ) {
                $formatted_instruction = [
                    '@type' => 'HowToStep',
                    'name'  => $instruction['name'],
                    'text'  => $instruction['instruction'],
                ];
                $formatted_instruction['url'] = sprintf( '%s#recipe-step-%s', $permalink, $i );
                switch ( $instruction['media_type'] ) {
                    case 'image':
                        $formatted_instruction['image'] = $this->container['bootstrap']->get_attachment_image( $instruction['step_image'] );
                        $this->fields['instructions']['raw'][$i]['image'] = $formatted_instruction['image'];
                        break;
                    case 'video':
                        $formatted_instruction['video'] = $this->get_video_seo__premium_only( $instruction['video'][0], $formatted_instruction['name'], $formatted_instruction['text'] );
                        break;
                    default:
                        # code...
                        break;
                }
                $formatted[] = $formatted_instruction;
            }
            $this->fields['instructions']['formatted'] = $formatted;
        }
        return $this->fields['instructions'];
    }

    public function get_grouped_instructions() {
        if ( !isset( $this->fields['instructions'] ) ) {
            $this->fields['instructions']['raw'] = carbon_get_post_meta( $this->post_id, 'wpt_recipe_grouped_instructions' );
            // format data
            $formatted = [];
            $permalink = get_the_permalink();
            foreach ( $this->fields['instructions']['raw'] as $i => $group ) {
                $formatted_instruction = [
                    "@type"           => "HowToSection",
                    "name"            => $group['name'],
                    'itemListElement' => [],
                ];
                foreach ( $group['steps'] as $j => $instruction ) {
                    # code...
                    $step = [
                        '@type' => 'HowToStep',
                        'name'  => $instruction['name'],
                        'text'  => $instruction['instruction'],
                    ];
                    $step['url'] = sprintf(
                        '%s#recipe-step%s-%s',
                        $permalink,
                        ( $group['name'] ? '-' . sanitize_title( $group['name'] ) : '' ),
                        $j
                    );
                    switch ( $instruction['media_type'] ) {
                        case 'image':
                            $step['image'] = $this->container['bootstrap']->get_attachment_image( $instruction['step_image'] );
                            $this->fields['instructions']['raw'][$i]['steps'][$j]['image'] = $step['image'];
                            break;
                        case 'video':
                            $step['video'] = $this->get_video_seo__premium_only( $instruction['video'][0], $step['name'], $step['text'] );
                            break;
                        default:
                            # code...
                            break;
                    }
                    $formatted_instruction['itemListElement'][] = $step;
                }
                $formatted[] = $formatted_instruction;
            }
            $this->fields['instructions']['formatted'] = $formatted;
        }
        return $this->fields['instructions'];
    }

    public function get_seo_instructions( $instructions ) {
    }

    /**
     * Get keywords
     */
    public function get_keywords() {
        if ( !isset( $this->fields['keywords'] ) ) {
            $this->fields['keywords'] = trim( carbon_get_post_meta( $this->post_id, 'wpt_recipe_keywords' ) );
        }
        return $this->fields['keywords'];
    }

    public function get_calories() {
        if ( !isset( $this->fields['calories'] ) ) {
            $this->fields['calories'] = trim( carbon_get_post_meta( $this->post_id, 'wpt_recipe_calories' ) );
        }
        return $this->fields['calories'];
    }

    /**
     * Get prep_time. pretty / formatted and raw
     */
    public function get_prep_time() {
        if ( !isset( $this->fields['prep_time'] ) ) {
            $this->fields['prep_time']['raw'] = carbon_get_post_meta( $this->post_id, 'wpt_recipe_prep_time' );
            $this->fields['prep_time']['formatted'] = $this->fields['prep_time']['raw']['value'];
        }
        return $this->fields['prep_time'];
    }

    public function get_publish_date() {
        return get_the_date( 'Y-m-d', $this->post_id );
    }

    /**
     * Get title
     */
    public function get_title() {
        if ( !isset( $this->fields['title'] ) ) {
            $this->fields['title'] = get_the_title( $this->post_id );
        }
        return $this->fields['title'];
    }

    public function get_total_time() {
        // all prep and cook time
        $cook_time = $this->get_cook_time();
        $prep_time = $this->get_prep_time();
        $total_seconds = $prep_time['raw']['seconds'] + $cook_time['raw']['seconds'];
        $total_minutes = $prep_time['raw']['minutes'] + $cook_time['raw']['minutes'] + (int) ($total_seconds / 60);
        $total_hours = $prep_time['raw']['hours'] + $cook_time['raw']['hours'] + (int) ($total_minutes / 60);
        $total_days = $prep_time['raw']['days'] + $cook_time['raw']['days'] + (int) ($total_hours / 24);
        $total_months = $prep_time['raw']['months'] + $cook_time['raw']['months'] + (int) ($total_days / 30);
        $total_years = $prep_time['raw']['years'] + $cook_time['raw']['years'] + (int) ($total_months / 12);
        $seconds = $total_seconds % 60;
        $minutes = $total_minutes % 60;
        $hours = $total_hours % 24;
        $days = $total_days % 30;
        $months = $total_months % 12;
        return [
            'formatted' => sprintf(
                'P%sY%sM%sDT%sH%sM%sS',
                $total_years,
                $months,
                $days,
                $hours,
                $minutes,
                $seconds
            ),
            'raw'       => [
                'years'   => $total_years,
                'months'  => $months,
                'days'    => $days,
                'hours'   => $hours,
                'minutes' => $minutes,
                'second'  => $seconds,
            ],
        ];
    }

    public function get_human_time( $time_array ) {
        $output = [];
        if ( isset( $time_array['years'] ) && $time_array['years'] ) {
            $output[] = sprintf( '%s %s', $time_array['years'], ( $time_array['years'] == '1' ? __( 'yr', 'food-recipes' ) : __( 'yrs', 'food-recipes' ) ) );
        }
        if ( isset( $time_array['months'] ) && $time_array['months'] ) {
            $output[] = sprintf( '%s %s', $time_array['months'], ( $time_array['months'] == '1' ? __( 'mo', 'food-recipes' ) : __( 'mos', 'food-recipes' ) ) );
        }
        if ( isset( $time_array['days'] ) && $time_array['days'] ) {
            $output[] = sprintf( '%s %s', $time_array['days'], ( $time_array['days'] == '1' ? __( 'day', 'food-recipes' ) : __( 'days', 'food-recipes' ) ) );
        }
        if ( isset( $time_array['hours'] ) && $time_array['hours'] ) {
            $output[] = sprintf( '%s %s', $time_array['hours'], ( $time_array['hours'] == '1' ? __( 'hr', 'food-recipes' ) : __( 'hrs', 'food-recipes' ) ) );
        }
        if ( isset( $time_array['minutes'] ) && $time_array['minutes'] ) {
            $output[] = sprintf( '%s %s', $time_array['minutes'], ( $time_array['minutes'] == '1' ? __( 'min', 'food-recipes' ) : __( 'mins', 'food-recipes' ) ) );
        }
        if ( isset( $time_array['seconds'] ) && $time_array['seconds'] ) {
            $output[] = sprintf( '%s %s', $time_array['seconds'], ( $time_array['seconds'] == '1' ? __( 'sec', 'food-recipes' ) : __( 'secs', 'food-recipes' ) ) );
        }
        return implode( ', ', $output );
    }

    /**
     * Get yield
     */
    public function get_yield() {
        if ( !isset( $this->fields['yield'] ) ) {
            $this->fields['yield']['quantity'] = carbon_get_post_meta( $this->post_id, 'wpt_recipe_yield' );
            $this->fields['yield']['unit'] = carbon_get_post_meta( $this->post_id, 'wpt_recipe_yield_unit' );
            $this->fields['yield']['formatted'] = sprintf( '%s%s', ( $this->fields['yield']['quantity'] ? $this->fields['yield']['quantity'] : '' ), ( $this->fields['yield']['unit'] ? ' ' . $this->fields['yield']['unit'] : '' ) );
        }
        return $this->fields['yield'];
    }

    /**
     * Get yield_unit
     */
    public function get_yield_unit() {
        if ( !isset( $this->fields['yield_unit'] ) ) {
            $this->fields['yield_unit'] = carbon_get_post_meta( $this->post_id, 'wpt_recipe_yield_unit' );
        }
        return $this->fields['yield_unit'];
    }

}
