<?php
/**
 * Plugin Name: Culturando Cookie Consent
 * Description: Gerenciador de consentimento de cookies (Única Janela).
 * Version: 1.1
 * Author: Ana Nascimento - Culturando
 * Text Domain: culturando-cookie-consent
 * License: GPL v2 or later
 */

if ( ! defined( 'ABSPATH' ) ) exit;

define( 'CCC_PATH', plugin_dir_path( __FILE__ ) );
define( 'CCC_URL', plugin_dir_url( __FILE__ ) );

class Culturando_Cookie_Consent {

	private const CONSENT_COOKIE = 'culturando_cookie_consent';
	private const CONSENT_VERSION = '1.0';

	private $categories = [
		'essential'  => [ 'label' => 'Essenciais', 'required' => true ],
		'analytics'  => [ 'label' => 'Estatísticas', 'required' => false ],
		'marketing'  => [ 'label' => 'Marketing', 'required' => false ],
	];

	public function __construct() {
		add_action( 'init', [ $this, 'load_textdomain' ] );
		add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_assets' ] );
		
		// Renderiza a janela no footer
		add_action( 'wp_footer', [ $this, 'render_modal' ], 9999 );
		
		add_action( 'admin_menu', [ $this, 'add_admin_page' ] );
		add_action( 'admin_init', [ $this, 'register_settings' ] );
		
		// Shortcode para o link/botão de gerenciar
		add_shortcode( 'lgpd_consent_manager', [ $this, 'consent_shortcode' ] );
	}

	public function load_textdomain() {
		load_plugin_textdomain( 'culturando-cookie-consent', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
	}

	public function register_settings() {
		register_setting( 'ccc_options', 'ccc_banner_text', [
			'sanitize_callback' => 'wp_kses_post',
			'default' => __( 'Este site utiliza cookies para melhorar sua experiência. Você pode aceitar todos ou personalizar suas preferências.', 'culturando-cookie-consent' ),
		] );
		register_setting( 'ccc_options', 'ccc_privacy_link', [
			'sanitize_callback' => 'esc_url_raw',
			'default' => '',
		] );
	}

	public function add_admin_page() {
		add_options_page(
			__( 'Cookie Consent (LGPD)', 'culturando-cookie-consent' ),
			__( 'Cookie Consent', 'culturando-cookie-consent' ),
			'manage_options',
			'culturando-cookie-consent',
			[ $this, 'render_admin_page' ]
		);
	}

	public function render_admin_page() {
		?>
		<div class="wrap">
			<h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
			<form method="post" action="options.php">
				<?php settings_fields( 'ccc_options' ); ?>
				<table class="form-table">
					<tr>
						<th scope="row"><label for="ccc_banner_text"><?php esc_html_e( 'Texto da Janela', 'culturando-cookie-consent' ); ?></label></th>
						<td>
							<textarea id="ccc_banner_text" name="ccc_banner_text" class="large-text" rows="4"><?php echo esc_textarea( get_option( 'ccc_banner_text' ) ); ?></textarea>
						</td>
					</tr>
					<tr>
						<th scope="row"><label for="ccc_privacy_link"><?php esc_html_e( 'Link da Política de Privacidade', 'culturando-cookie-consent' ); ?></label></th>
						<td>
							<input type="url" id="ccc_privacy_link" name="ccc_privacy_link" value="<?php echo esc_url( get_option( 'ccc_privacy_link' ) ); ?>" class="regular-text">
						</td>
					</tr>
				</table>
				<?php submit_button(); ?>
			</form>
		</div>
		<?php
	}

	public function enqueue_assets() {
		wp_enqueue_style( 'ccc-style', CCC_URL . 'assets/cookie-consent.css', [], '1.1' );
		wp_enqueue_script( 'ccc-script', CCC_URL . 'assets/cookie-consent.js', [], '1.1', true );
		wp_localize_script( 'ccc-script', 'cccData', [
			'consentCookie' => self::CONSENT_COOKIE,
			'version'       => self::CONSENT_VERSION,
			'categories'    => $this->categories,
		] );
	}

    /**
     * Renderiza a ÚNICA janela.
     * Se não houver consentimento, ela já vem visível.
     * Se houver, vem com atributo 'hidden'.
     */
    public function render_modal() {
        $text    = get_option( 'ccc_banner_text' );
        $privacy = get_option( 'ccc_privacy_link' );
        
        // Verifica se já tem consentimento
        $has_consent = $this->has_consent();
        
        // Se já consentiu, adiciona 'hidden'. Se não, remove (fica visível).
        $hidden_attr = $has_consent ? 'hidden' : '';
        $aria_hidden = $has_consent ? 'true' : 'false';
        ?>
        <div id="ccc-modal" class="ccc-modal" <?php echo $hidden_attr; ?> aria-hidden="<?php echo $aria_hidden; ?>">
            <div class="ccc-modal-content" role="dialog" aria-modal="true" aria-label="<?php esc_attr_e( 'Gerenciamento de Cookies', 'culturando-cookie-consent' ); ?>">
                
                <button type="button" class="ccc-close-btn" aria-label="<?php esc_attr_e( 'Fechar', 'culturando-cookie-consent' ); ?>">&times;</button>

                <h3><?php esc_html_e( 'Preferências de Cookies', 'culturando-cookie-consent' ); ?></h3>
                
                <p class="ccc-modal-desc">
                    <?php echo wp_kses_post( $text ); ?>
                    <?php if ( $privacy ) : ?>
                        <br><a href="<?php echo esc_url( $privacy ); ?>" target="_blank" rel="noopener"><?php esc_html_e( 'Saiba mais', 'culturando-cookie-consent' ); ?></a>
                    <?php endif; ?>
                </p>

                <form id="ccc-form">
                    <fieldset class="ccc-categories">
                        <?php foreach ( $this->categories as $key => $cat ) : ?>
                            <label class="ccc-category">
                                <input type="checkbox" value="<?php echo esc_attr( $key ); ?>"
                                    <?php echo $cat['required'] ? 'checked disabled' : ''; ?>>
                                <span class="ccc-category-label">
                                    <strong><?php echo esc_html( $cat['label'] ); ?></strong>
                                    <?php if ( $cat['required'] ) : ?>
                                        <em>(<?php esc_html_e( 'obrigatório', 'culturando-cookie-consent' ); ?>)</em>
                                    <?php endif; ?>
                                </span>
                            </label>
                        <?php endforeach; ?>
                    </fieldset>

                    <div class="ccc-modal-actions">
                        <button type="button" class="ccc-btn ccc-btn-secondary" data-ccc-action="close"><?php esc_html_e( 'Cancelar', 'culturando-cookie-consent' ); ?></button>
                        <button type="submit" class="ccc-btn ccc-btn-primary"><?php esc_html_e( 'Salvar preferências', 'culturando-cookie-consent' ); ?></button>
                    </div>
                </form>
            </div>
        </div>
        <?php
    }

    public function consent_shortcode() {
        // Gera apenas o link/botão para abrir a janela manualmente
        return '<button type="button" class="ccc-manage-link" aria-label="' . esc_attr__( 'Gerenciar Cookies', 'culturando-cookie-consent' ) . '">' . esc_html__( 'Gerenciar cookies', 'culturando-cookie-consent' ) . '</button>';
    }

	public function has_consent( $category = null ) {
		if ( ! isset( $_COOKIE[ self::CONSENT_COOKIE ] ) ) return false;
		
		$consent = json_decode( stripslashes( $_COOKIE[ self::CONSENT_COOKIE ] ), true );
		if ( ! $consent || ! isset( $consent['version'] ) || $consent['version'] !== self::CONSENT_VERSION ) {
			return false; 
		}
		
		if ( ! $category ) return true;
		return ! empty( $consent['accepted'][ $category ] );
	}
}

function ccc_has_consent( $category ) {
    static $plugin = null;
    if ( ! $plugin ) $plugin = new Culturando_Cookie_Consent();
    return $plugin->has_consent( $category );
}

new Culturando_Cookie_Consent();