<?php

// Exit if accessed directly.
if (!defined('ABSPATH')) exit;

class Rdg_Blocks_Preview_Template extends Rdg_Blocks_Base
{
    protected $block_name = BLOCK_RDG_PREVIEW_TEMPLATE;
    private $block_folder_name = BLOCK_RDG_PREVIEW_TEMPLATE;
    protected $block_title = 'RDG Preview Template';
    private $block_description = '';
    private $block_icon = 'admin-links';
    private $block_keywords = ['rdg', 'custom', 'preview', 'template'];
    private $block_mode = 'preview';
    private $block_category = RDGBLOCKS_NAME_SLUG;
    protected $is_styles_load = true;

    public function init() {
        $this->register_block();
        add_action('init', [$this, 'register_fields'], 2000);
        add_action('acf/init', [$this, 'register_image_size'], 20);
    }

    private function register_block() {
        if (function_exists('acf_register_block_type')) {
            $rdg_helpers = new Rdg_Blocks_Helpers();
            acf_register_block_type([
                'name' => $this->block_name,
                'title' => __($this->block_title),
                'description' => __($this->block_description),
                'category' => $this->block_category,
                'icon' => $this->block_icon,
                'keywords' => $this->block_keywords,
                'mode' => $this->block_mode,
                'render_template' => RDGBLOCKS_PLUGIN_DIR . "/blocks/".$this->block_folder_name."/template.php",
                'enqueue_style' => $rdg_helpers->webpack('rdg_preview_template.css'),
                'example' => array(
                    'attributes' => array(
                        'mode' => 'preview',
                        'data' => array(
                            'isExample' => true,
                            'preview_image' => RDGBLOCKS_PLUGIN_URL."dist/images/rdg-preview-template-preview.jpg",
                        ),
                    ),
                ),
                'supports' => [
                    'jsx' => true,
                    'color' => [
                        'background' => true,
                        'gradients'  => false,
                        'text' => false,
                    ],
                ],
            ]);
        }
    }

    public function register_fields() {
        $post_type = $this->get_post_type_taxonomy();

        $fields = [
            array(
                'key' => 'key_preview_template_order',
                'label' => 'Order',
                'name' => 'order',
                'aria-label' => '',
                'type' => 'select',
                'instructions' => '',
                'required' => 1,
                'conditional_logic' => 0,
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'choices' => array(
                    'asc' => 'Ascendent',
                    'desc' => 'Descendent',
                ),
                'default_value' => 'asc',
                'return_format' => 'value',
                'multiple' => 0,
                'allow_null' => 0,
                'ui' => 0,
                'ajax' => 0,
                'placeholder' => '',
                'allow_custom' => 0,
                'search_placeholder' => '',
                'prepend' => '',
                'append' => '',
                'min' => '',
                'max' => '',
            ),
            array(
                'key' => 'key_preview_template_show',
                'label' => 'Show',
                'name' => 'show',
                'aria-label' => '',
                'type' => 'select',
                'instructions' => '',
                'required' => 1,
                'conditional_logic' => 0,
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'choices' => array(
                    'latest' => 'Latest Posts',
                    'specific' => 'Specific Posts',
                ),
                'default_value' => 'latest',
                'return_format' => 'value',
                'multiple' => 0,
                'allow_null' => 0,
                'ui' => 0,
                'ajax' => 0,
                'placeholder' => '',
                'allow_custom' => 0,
                'search_placeholder' => '',
                'prepend' => '',
                'append' => '',
                'min' => '',
                'max' => '',
            ),
            array(
                'key' => 'key_preview_template_parent',
                'label' => 'Parent',
                'name' => 'parent',
                'aria-label' => '',
                'type' => 'post_object',
                'instructions' => '',
                'required' => 1,
                'conditional_logic' => array(
                    array(
                        array(
                            'field' => 'key_preview_template_show',
                            'operator' => '==',
                            'value' => 'latest',
                        ),
                    ),
                ),
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'post_type' => array(
                    0 => $post_type['slug'],
                ),
                'post_status' => array(
                    0 => 'publish',
                ),
                'taxonomy' => '',
                'return_format' => 'id',
                'multiple' => 0,
                'max' => '',
                'save_custom' => 0,
                'save_post_status' => 'publish',
                'allow_null' => 0,
                'allow_in_bindings' => 0,
                'bidirectional' => 0,
                'ui' => 1,
                'bidirectional_target' => array(
                ),
                'save_post_type' => '',
                'min' => '',
            ),
        ];

        $fields[] = [
            'key' => 'key_preview_template_elements',
            'label' => 'Elements',
            'name' => 'elements',
            'aria-label' => '',
            'type' => 'relationship',
            'instructions' => '',
            'required' => 1,
            'conditional_logic' => array(
                array(
                    array(
                        'field' => 'key_preview_template_show',
                        'operator' => '==',
                        'value' => 'specific',
                    ),
                ),
            ),
            'wrapper' => array(
                'width' => '',
                'class' => '',
                'id' => '',
            ),
            'post_type' => array(
                0 => $post_type['slug'],
            ),
            'taxonomy' => '',
            'filters' => array(
                0 => 'search',
                1 => 'taxonomy',
            ),
            'return_format' => 'object',
            'min' => 1,
            'max' => 20,
            'elements' => array(
                0 => 'featured_image',
            ),
        ];

        $last_fields = [
            array(
                'key' => 'key_preview_template_quantity',
                'label' => 'Quantity',
                'name' => 'quantity',
                'aria-label' => '',
                'type' => 'number',
                'instructions' => '',
                'required' => 1,
                'conditional_logic' => array(
                    array(
                        array(
                            'field' => 'key_preview_template_show',
                            'operator' => '==',
                            'value' => 'latest',
                        ),
                    ),
                ),
                'wrapper' => array(
                    'width' => '',
                    'class' => '',
                    'id' => '',
                ),
                'default_value' => 3,
                'min' => 1,
                'max' => 12,
                'placeholder' => '',
                'step' => '',
                'prepend' => '',
                'append' => '',
            ),
        ];

        $fields = array_merge($fields, $last_fields);

        if (function_exists('acf_add_local_field_group')):
            acf_add_local_field_group(array(
                'key' => 'group_preview_template',
                'title' => 'RDG Preview Template',
                'fields' => $fields,
                'location' => array(
                    array(
                        array(
                            'param' => 'block',
                            'operator' => '==',
                            'value' => 'acf/rdg-preview-template',
                        ),
                    ),
                ),
                'menu_order' => 1,
                'position' => 'normal',
                'style' => 'default',
                'label_placement' => 'top',
                'instruction_placement' => 'label',
                'hide_on_screen' => '',
                'active' => true,
                'description' => '',
            ));

        endif;
    }

    public function register_image_size() {
        add_image_size('posts-list', 800, 500, true);
    }

    public function get_elements_type($fields, $paged, $order) {
        $show = (!empty($fields['show'])) ? $fields['show'] : 'latest';

        if (BLOCK_RDG_TYPE_SPECIFIC == $show) {
            $count_elements = 0;

            try {
                count($fields['elements']);
            } catch (\Throwable $th) {
                //throw $th;
            }

            $data = [
                'max' => $count_elements,
                'posts' => $fields['elements'],
            ];
            
            return $data;
        }

        if (!isset($fields['parent']) || empty($fields['parent'])) {
            return [
                'max' => 0,
                'posts' => [],
            ];
        }

        $posts = $this->getCustomQueryData($fields, $paged, $order);

        return $posts;
    }

    public function getCustomQueryData($fields, $paged, $order) {
        global $wpdb;
        $data = [
            'max' => 0,
            'posts' => [],
        ];

        $post_type = $this->get_post_type_taxonomy();
        $quantity = (isset($fields['quantity']) && !empty($fields['quantity'])) ? $fields['quantity'] : 3;

        $query_count = "
            SELECT COUNT(p.ID) AS max
            FROM {$wpdb->posts} p
            WHERE p.post_type = '{$post_type['slug']}'
                AND p.post_status = 'publish'
                AND p.post_parent = '{$fields['parent']}'
                AND EXISTS (
                    SELECT 1
                    FROM {$wpdb->postmeta} meta
                    WHERE meta.post_id = p.ID
                    AND meta.meta_key = 'shg_external_id'
                    AND meta.meta_value != ''
                );
        ";

        $posts_cout = $wpdb->get_var($query_count);
        if (empty($posts_cout)) {
            return $data;
        }

        $data['max'] = $posts_cout;
        $offeset = ($paged - 1) * $quantity;
                
        $query_data = "
            SELECT 
                p.ID, p.post_content, m5.meta_value AS shg_game_date
            FROM {$wpdb->posts} p 
            INNER JOIN {$wpdb->postmeta} m5 ON p.ID = m5.post_id AND m5.meta_key = 'shg_game_date' AND m5.meta_value <> '' 
            WHERE p.post_type = '{$post_type['slug']}' 
                AND p.post_status = 'publish' 
                AND p.post_parent = '{$fields['parent']}'
                AND EXISTS (
                        SELECT 1
                        FROM {$wpdb->postmeta} meta
                        WHERE meta.post_id = p.ID
                        AND meta.meta_key = 'shg_external_id'
                        AND meta.meta_value != ''
                    )
            ORDER BY shg_game_date {$order}
            LIMIT {$quantity} OFFSET {$offeset};
        ";

        $posts = $wpdb->get_results($query_data);
        if (empty($posts)) {
            return $data;
        }

        $data['posts'] = $posts;

        return $data;
    }

    public function get_image($url_image, $attributes = []) {
        $rdgb_helpers = New Rdg_Blocks_Helpers;
        $url_image = $rdgb_helpers->getImageSource($url_image, $attributes);

        if (isset($url_image['url']) && !empty($url_image['url']) && $this->isValidImage($url_image['url'])) {
            return $url_image;
        }

        return [
            'url' => RDGBLOCKS_PLUGIN_URL."dist/images/rdg-preview-template-team-logo.webp",
            'alt' => 'Team Logo',
        ];
    }

    public function isValidImage($url) {
        $headers = @get_headers($url);

        if ($headers && strpos($headers[0], '200')) {
            return true; 
        }

        return false; 
    }

    public function getContentDescription($content) {
        $blocks = parse_blocks($content);
        $count_words = 0;
        $description = '';

        foreach ($blocks as $key => $block) {
            if ($block['blockName'] == 'core/paragraph' && !empty($block['innerHTML'])) {
                $words = wp_trim_words($block['innerHTML'], 130, false);
                
                if (!empty($words)) {
                    $count_words += count(explode(' ', $words));
                    $description .= $words. ' ';
                    if ($count_words < 130) {
                        continue;
                    } else {
                        break;
                    }
                }
            }
        }
        return $description;
    }

    public function get_description($element) {
        if (isset($element->post_excerpt) && !empty($element->post_excerpt)) {
            return $element->post_excerpt;
        }

        if (is_array($element) && isset($element['content']) && !empty($element['content'])) {
            return wp_strip_all_tags($element['content']);
        }

        if (isset($element->post_content) && !empty($element->post_content)) {
            return wp_strip_all_tags($element->post_content);
        }

        return '';
    }

    private function get_post_type_taxonomy() {
        if (defined('SHG_SLUG')) {
            $slug = json_decode(SHG_SLUG, true);
        } else {
            error_log(print_r([
                'message' => 'RDG Blocks: The constant SHG_SLUG is not defined.',
            ], true));

            $slug = ['slug' => 'preview','label' => 'Preview'];
        }

        $taxonomies = get_object_taxonomies($slug['slug']);

        if (is_array($taxonomies) && isset($taxonomies[0])) {
            $slug['taxonomy'] = $taxonomies[0];
        }

        return $slug;
    }

    public function getColorsToloadGeneratePress() {
        return [
            ['name' => 'color-preview-template-bg','slug' => 'color-preview-template-bg','color' => '#ffffff'],
            ['name' => 'color-preview-template-description','slug' => 'color-preview-template-description','color' => '#111111'],
            ['name' => 'color-preview-template-border','slug' => 'color-preview-template-border','color' => '#F1F1F1'],
            ['name' => 'color-preview-template-title','slug' => 'color-preview-template-title','color' => '#eaf6ff'],
            ['name' => 'color-preview-template-light','slug' => 'color-preview-template-light','color' => '#0160ac'],
            ['name' => 'color-preview-template-link-hover','slug' => 'color-preview-template-link-hover','color' => '#3a96e0'],
            ['name' => 'color-preview-template-title-bg','slug' => 'color-preview-template-title-bg','color' => '#03467d'],

        ];
    }

    public function getStylesToloadGeneratePress() {
        return [
            [
                'customSelector' => '.rdg-preview-template .body .previews a',
                'textDecoration' => 'none',
            ],
            [
                'customSelector' => '.rdg-preview-template .body .previews .preview .preview-header',
                'fontWeight' => '600',
                'fontSize' => '1rem',
            ],
            [
                'customSelector' => '.rdg-preview-template .body .previews .preview .preview-body .preview-teams .preview-vs span',
                'fontWeight' => '600',
                'fontSize' => '.9rem',
            ],
            [
                'customSelector' => '.rdg-preview-template .body .previews .preview .preview-body .preview-title',
                'fontWeight' => '700',
                'fontSize' => '1rem',
            ],
            [
                'customSelector' => '.rdg-preview-template .body .previews .preview .preview-body .preview-description span',
                'fontWeight' => '600',
                'fontSize' => '.85rem',
                'lineHeight' => '1.2rem',
            ],
            [
                'customSelector' => '.rdg-preview-template .body .previews .preview .preview-body .preview-list ul li',
                'fontWeight' => '700',
                'fontSize' => '1rem',
            ],
            [
                'customSelector' => '.rdg-preview-template .body .previews .preview .preview-footer',
                'fontWeight' => '600',
                'fontSize' => '1rem',
            ],
            [
                'customSelector' => '.rdg-preview-template .body .previews .preview .preview-body .preview-date',
                'fontSize' => '1rem',
                'fontWeight' => '700',
            ],
        ];
    }
}

$rdg_preview_template_class = new Rdg_Blocks_Preview_Template();
$rdg_preview_template_class->init();

return $rdg_preview_template_class;
