<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class IDVE_Frontend {

    public function __construct() {
        add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_styles' ) );
        add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_global_styles' ), 20 );
        add_filter( 'body_class', array( $this, 'body_class' ) );
    }

    public function body_class( $classes ) {
        if ( is_singular() ) {
            $post_id = get_queried_object_id();
            if ( $post_id && $this->has_idve_content( $post_id ) ) {
                $classes[] = 'idve-page';
            }
        }
        return $classes;
    }

    public function enqueue_styles() {
        if ( ! is_singular() ) {
            return;
        }
        $post_id = get_queried_object_id();
        if ( ! $post_id ) {
            return;
        }
        if ( ! $this->has_idve_content( $post_id ) ) {
            return;
        }

        wp_enqueue_style( 'idve-grid', IDVE_PLUGIN_URL . 'frontend/css/idve-grid.css', array(), IDVE_VERSION );

        $css = get_post_meta( $post_id, '_idve_css', true );
        if ( ! empty( $css ) ) {
            wp_add_inline_style( 'idve-grid', $css );
        }
    }

    public function enqueue_global_styles() {
        $upload_dir = wp_upload_dir();
        $file_path  = $upload_dir['basedir'] . '/idve-global-styles.css';
        $file_url   = $upload_dir['baseurl'] . '/idve-global-styles.css';

        if ( file_exists( $file_path ) ) {
            wp_enqueue_style( 'idve-global-styles', $file_url, array(), filemtime( $file_path ) );
            return;
        }

        $css = get_option( 'idve_global_styles', '' );
        if ( ! empty( $css ) ) {
            wp_register_style( 'idve-global-styles', false ); // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion
            wp_enqueue_style( 'idve-global-styles' );
            wp_add_inline_style( 'idve-global-styles', $css );
        }
    }

    /**
     * Check whether this post has IDVE-generated content that needs
     * the grid stylesheet and per-page CSS, regardless of whether
     * the editor is currently active on the page.
     */
    private function has_idve_content( $post_id ) {
        $css = get_post_meta( $post_id, '_idve_css', true );
        if ( ! empty( $css ) ) {
            return true;
        }
        $data = get_post_meta( $post_id, '_idve_data', true );
        if ( ! empty( $data ) ) {
            return true;
        }
        return false;
    }
}
