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

class Ftm_Blocks_Base
{

    public function load_css(&$block)
    {

        //If the request is coming from WP Admin NOR is coming from ajax don't even bother on loading/writing any CSS file
        /*
        * $_REQUEST["_locale"] -> This request it's being made by WP
        */
        // if ((!empty($_GET["post"]) && $_GET["action"] == 'edit') || ($_REQUEST["action"] == "acf/ajax/fetch-block") || ($_REQUEST["_locale"] == "user")) {
        //     return;
        // }

        // THE CODE BELOW WILL GENERATE A BLOCK ID ON THE FLY TO AVOID BLOCKS NOT DISPLAYING PROPERLY
        // HOWEVER WILL GENERATE A CSS FILE PER LOAD (NOT A GOOD IDEA)
        /*if ((empty($block["data"]["ftm_block_id"]) && (!empty($this->css_generate_fields)))) {
            $generated_block_id = 'block-' . uniqid();
            $block["data"]["ftm_block_id"] = $generated_block_id;
            $block["data"]["_ftm_block_id"] = $generated_block_id;
        }*/

        if (!empty($block["data"]["ftm_block_id"])) {
            $block_id       = $block["data"]["ftm_block_id"];
            $css_file       = Ftm_Blocks_Helpers::getCSSFolder() . $block_id . ".css";
            $css_file_url   = Ftm_Blocks_Helpers::getCSSFolder("url") . $block_id . ".css";

            if (!empty($_REQUEST["preview_id"])) {
                $block["data"]["ftm_block_id"] = $block["data"]["ftm_block_id"] . '-preview';
                $this->write_css($block);
                $css_file = Ftm_Blocks_Helpers::getCSSFolder() . $block_id . "-preview.css";
                $css_file_url   = Ftm_Blocks_Helpers::getCSSFolder("url") . $block_id . "-preview.css";
                $block_id = $block["data"]["ftm_block_id"] . '-preview';
            }

            //In case the generated css file has been deleted. Create it
            if (!empty($block_id) && !empty($block) && !file_exists($css_file)) {
                $this->write_css($block);
            }

            if (file_exists($css_file)) {
                wp_enqueue_style('ftm_' . $block_id, $css_file_url);
                if (is_user_logged_in()) {
                    add_action('admin_enqueue_scripts', function () use ($block_id, $css_file_url) {
                        wp_enqueue_style('admin_ftm_' . $block_id, $css_file_url);
                    });
                }
            }
        }
    }

    public function write_css($attributes)
    {
        if (empty($attributes["data"]["ftm_block_id"])) {
            return;
        }

        $temp = $temp_dynamic = $css_property_closer = "";
        $css_selector = ".";
        $css_fields = $this->get_css_fields();
        $file_name = Ftm_Blocks_Helpers::getCSSFolder() . $attributes["data"]["ftm_block_id"] . ".css";
        $key_dynamic = 'type';
        $value_dynamic = 'dynamic';
        $css_fields_quantity_total = count($css_fields);
        $count_fields_quantity_dynamic = count(array_filter($css_fields, function ($item) use ($key_dynamic, $value_dynamic) {
            return isset($item[$key_dynamic]) && $item[$key_dynamic] == $value_dynamic;
        }));
        $css_fields_quantity = $css_fields_quantity_total - $count_fields_quantity_dynamic;
        $counter = $counter_dynamic = 1;
        foreach ($css_fields as $field => $key) {

            $css_property_closer = "";

            if (array_key_exists("field_type", $key)) {

                /*
                 * BACKWARD COMPATIBILITY CODE BLOCK
                 */
                if ($key["field_type"] == "width-unit") {
                    continue;
                }

                if ($key["field_type"] == "color") {
                    $css_property = "color:";
                }

                if ($key["field_type"] == "font-size") {
                    $css_property = "font-size:";
                    $css_property_closer = "px";
                }

                if ($key["field_type"] == "bg-color") {
                    $css_property = "background-color:";
                }

                if ($key["field_type"] == "border-width") {
                    $css_property = "border-witdh:";
                    $css_property_closer = "px";
                }

                if ($key["field_type"] == "border-color") {
                    $css_property = "border-color:";
                }

                if ($key["field_type"] == "hv-color") {
                    $field .= ':hover';
                    $css_property = "background-color:";
                }

                if ($key["field_type"] == "hv-text-color") {
                    $field .= ':hover';
                    $css_property = "color:";
                }

                if ($key["field_type"] == "bg-url") {
                    $css_property = "background:url(";
                    $css_property_closer = ")";
                }

                if ($key["field_type"] == "max-width" || $key["field_type"] == "min-width") {
                    $css_property = ($key["field_type"] == "max-width") ? "max-width:" : "min-width:";
                    if ((!empty($css_fields["box-width-unit"]) && (!empty($attributes["data"][$key["field_name"]])))) {
                        if ($attributes["data"][$css_fields["box-width-unit"]["field_name"]] == "pixels") {
                            $css_property_closer = "px";
                        } else {
                            $css_property_closer = "%";
                        }
                    }
                }
            }

            if (!empty($key["tag"])) {
                $field = $key["tag"];
                $css_selector = "";
            }
            /*
             * BACKWARD COMPATIBILITY CODE BLOCK
             */

            //Only add to the css file if there's a value on the field
            if (!empty($attributes["data"][$key["field_name"]])) {
                //Check if the css should be added to the parent wrapper or not
                if (!empty($key["output_type"]) && $key["output_type"] == "variable") {

                    if ($counter == 1) {
                        $temp .= "#" . $attributes["data"]["ftm_block_id"] . " {" . "--" . $field . ": " . $attributes["data"][$key["field_name"]] . ";";
                    } elseif ($counter == $css_fields_quantity) {
                        $temp .= "--" . $field . ": " . $attributes["data"][$key["field_name"]] . ";}";
                    } else {
                        $temp .= "--" . $field . ": " . $attributes["data"][$key["field_name"]] . ";";
                    }

                    //$temp .= "#" . $attributes["data"]["ftm_block_id"] . " {" . "--" . $field . ": " . $attributes["data"][$key["field_name"]] . ";}";

                } elseif (!empty($key["on_parent_wrapper"]) && $key["on_parent_wrapper"] == "yes") {
                    $temp .= "#" . $attributes["data"]["ftm_block_id"] . $css_selector . $field . "{" . $css_property . $attributes["data"][$key["field_name"]] . $css_property_closer . "}";
                } else {
                    $temp .= "#" . $attributes["data"]["ftm_block_id"] . " " . $css_selector . $field . "{" . $css_property . $attributes["data"][$key["field_name"]] . $css_property_closer . "}";
                }
                unset($css_property);
                unset($css_property_closer);
            } elseif (($key["type"] == 'dynamic') && (!empty($key["output_type"]) && $key["output_type"] == "variable")) {
                $dynamic_fields = $this->search_dynamic_fields($attributes["data"], $key["field_name"]);
                $dynamic_field_total = count($dynamic_fields);
                foreach ($dynamic_fields as $field => $value) {
                    if ($counter_dynamic == 1) {
                        $temp_dynamic .= "#" . $attributes["data"]["ftm_block_id"] . " {" . "--" . $field . ": " . $value . ";";
                    } elseif ($counter_dynamic == $dynamic_field_total) {
                        $temp_dynamic .= "--" . $field . ": " . $value . ";}";
                    } else {
                        $temp_dynamic .= "--" . $field . ": " . $value . ";";
                    }
                    $counter_dynamic++;
                }
                $counter_dynamic = 1;
            }
            $temp .= $temp_dynamic;
            $counter++;
        }

        //Get current CSS file
        if (file_exists($file_name)) {

            $latest_file = fopen($file_name, "r");
            $temp_latest = fgets($latest_file);
            fclose($latest_file);
        }

        //Check if there's any difference and write the new css file if it does
        if ($temp_latest != $temp) {

            $css_file = fopen($file_name, "w+");
            fwrite($css_file, $temp);
            fclose($css_file);
        }
    }

    public function search_dynamic_fields($array, $regex)
    {
        // Result array
        $result = [];
        $counter = 1;
        // Loop through the array
        foreach ($array as $key => $value) {

            // Check if the key matches the pattern
            if (preg_match('/' . $regex . '/', $key)) {
                if (preg_match('/field_/', $value)) {
                    continue;
                }
                // Add to result
                $result[$regex . "-" . $counter] = $value;
                $counter++;
            }
        }
        return $result;
    }
}
