<?php

/*
Plugin Name: MultiWeather
Plugin URI: https://wordpress.org/plugins/multiweather/
Description: Beautiful weather, tide, and marine forecast cards for WordPress.
Version: 1.1.0
Author: ipodguy79
Author URI: https://profiles.wordpress.org/ipodguy79/
Requires at least: 5.8
Tested up to: 6.9
Requires PHP: 7.4
License: GPL2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Text Domain: multiweather
*/
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
if ( function_exists( 'mul_fs' ) ) {
    // Another version (free/pro) is already loaded – just set this file as the basename.
    mul_fs()->set_basename( false, __FILE__ );
} else {
    /**
	 * DO NOT REMOVE THIS IF – it is essential for the function_exists() call above
	 * to properly work when both free and premium are installed.
	 */
	if ( ! function_exists( 'mwpl_fs' ) ) {

		/**
		 * Freemius SDK init.
		 *
		 * @return Freemius
		 */
		function mwpl_fs() {
			global $mwpl_fs;

			if ( ! isset( $mwpl_fs ) ) {
				// Include Freemius SDK.
				require_once dirname( __FILE__ ) . '/vendor/freemius/start.php';

				$mwpl_fs = fs_dynamic_init(
					array(
						'id'              => '22214',
						'slug'            => 'multiweather',
						'is_org_compliant'=> true,
						'type'            => 'plugin',
						'public_key'      => 'pk_acb6005eb7a626b8273a1fc046c95',
						'is_premium'      => false,
						'has_addons'      => false,
						'has_paid_plans'  => true,
						'menu'            => array(
							'slug'    => 'multiweather',
							'support' => false,
							'parent'  => array(
								'slug' => 'options-general.php',
							),
						),
						'is_live'         => true,
					)
				);
			}

			return $mwpl_fs;
		}

		// Init Freemius.
		mwpl_fs();

		/**
		 * Fires once Freemius has loaded for MultiWeather.
		 */
		do_action( 'mwpl_fs_loaded' );
	}

}
require_once plugin_dir_path( __FILE__ ) . 'inc/utilities.php';
require_once plugin_dir_path( __FILE__ ) . 'inc/icon-loader.php';
require_once plugin_dir_path( __FILE__ ) . 'inc/animated-icons.php';
/** --------------------------------------------------------------------
 * Flags, paths
 * ------------------------------------------------------------------ */
define( 'MWPL_PRO', true );
define( 'MWPL_PATH', plugin_dir_path( __FILE__ ) );
define( 'MWPL_URL', plugin_dir_url( __FILE__ ) );
define( 'MWPL_VERSION', '1.0.1' );
/** --------------------------------------------------------------------
 * Includes
 * ------------------------------------------------------------------ */
require MWPL_PATH . 'inc/pro-timezone.php';
require_once MWPL_PATH . 'inc/settings-page.php';
require_once MWPL_PATH . 'inc/fetch-weather.php';

/** --------------------------------------------------------------------
 * REST: timezone
 * ------------------------------------------------------------------ */
add_action( 'rest_api_init', function () {

	register_rest_route( 'mwpl', '/tz', array(
		'methods'             => 'GET',
		'callback'            => 'mwpl_rest_timezone',
		'permission_callback' => '__return_true',
	) );
} );

/**
 * REST callback: timezone lookup
 */
function mwpl_rest_timezone( WP_REST_Request $request ) {

	$lat = $request->get_param( 'lat' );
	$lon = $request->get_param( 'lon' );

	if ( null === $lat || null === $lon ) {
		return new WP_Error(
			'tz_invalid',
			'Latitude and longitude are required',
			array( 'status' => 400 )
		);
	}

	$data = mwpl_get_location_time( $lat, $lon );
	if ( $data && isset( $data['name'] ) ) {
		return array( 'timezone' => $data['name'] );
	}

	return new WP_Error(
		'tz_not_found',
		'Could not determine timezone for provided coordinates',
		array( 'status' => 404 )
	);
}

/** --------------------------------------------------------------------
 * JS: timezone formatter (unchanged)
 * ------------------------------------------------------------------ */
add_action( 'wp_enqueue_scripts', function () {
    wp_enqueue_script(
        'mwpl-timezone-init',
        MWPL_URL . 'js/init-weather-zones.js',
        array(),
        '1.0.0',
        true
    );
}, 20 );
add_action( 'wp_enqueue_scripts', 'mwpl_enqueue_animate_css' );
function mwpl_enqueue_animate_css() {
    // Local copy of Animate.css v3.7.2.
    $relative_path = 'assets/css/animate.min.css';
    wp_enqueue_style(
        'mwpl-animate-css',
        plugin_dir_url( __FILE__ ) . $relative_path,
        array(),
        '3.7.2'
    );
}



/** --------------------------------------------------------------------
 * JS: enqueue front-end scripts
 * ------------------------------------------------------------------ */
function mwpl_enqueue_front_scripts() {
	wp_register_script(
		'mwpl-front',
		MWPL_URL . 'assets/js/mwpl-front.js',
		array(),
		MWPL_VERSION,
		true
	);
	wp_enqueue_script( 'mwpl-front' );
}
add_action( 'wp_enqueue_scripts', 'mwpl_enqueue_front_scripts', 9999 );
/** --------------------------------------------------------------------
 * CSS: enqueue AFTER theme (priority 9999)
 *  - Weather Icons
 *  - Base CSS (if present)
 *  - Per-card CSS (only those used on the page)
 *  - Optional site-wide style.css (if present)
 * ------------------------------------------------------------------ */
$GLOBALS['mwpl_cards_needed'] = $GLOBALS['mwpl_cards_needed'] ?? array();
add_action( 'wp_enqueue_scripts', function () {
    // Weather Icons.
    wp_enqueue_style(
        'mwpl-weather-icons',
        MWPL_URL . 'weather-icons/css/weather-icons.min.css',
        array(),
        '2.0.10'
    );
    // Base CSS (optional).
    $base_path = MWPL_PATH . 'assets/base.css';
    if ( file_exists( $base_path ) ) {
        wp_enqueue_style(
            'mwpl-base-style',
            MWPL_URL . 'assets/base.css',
            array(),
            filemtime( $base_path )
        );
    }
    // Optional site-wide overrides.
    $site_style = MWPL_PATH . 'assets/style.css';
    if ( file_exists( $site_style ) ) {
        wp_enqueue_style(
            'mwpl-site-style',
            MWPL_URL . 'assets/style.css',
            array(),
            filemtime( $site_style )
        );
    }
    // Per-card CSS collected during shortcode rendering.
    $cards = array_unique( array_map( 'intval', ( $GLOBALS['mwpl_cards_needed'] ?: array() ) ) );
    foreach ( $cards as $card_num ) {
        $rel = "assets/card/card{$card_num}-style.css";
        $file = MWPL_PATH . $rel;
        if ( file_exists( $file ) ) {
            wp_enqueue_style(
                "mwpl-card{$card_num}-style",
                MWPL_URL . $rel,
                array(),
                filemtime( $file )
            );
        }
    }
    // Compat CSS — load AFTER per-card CSS so it can override theme + per-card bleed.
    $compat_rel  = 'assets/compat.css';
    $compat_file = MWPL_PATH . $compat_rel;

    if ( file_exists( $compat_file ) ) {
        wp_enqueue_style(
            'mwpl-compat-style',
            MWPL_URL . $compat_rel,
            array(),
            filemtime( $compat_file )
        );
    }
}, 9999 );
/** --------------------------------------------------------------------
 * Shortcodes
 * ------------------------------------------------------------------
 * Keep the original [weather_card] shortcode for backward compatibility
 * (it is referenced in readme/docs and may already be used on sites),
 * and also provide a prefixed alias to reduce collision risk.
 */
add_shortcode( 'mwpl_weather_card', 'mwpl_render_weather_card' );
function mwpl_render_weather_card(  $atts  ) {
    $atts = shortcode_atts( array(
        'lat'   => '',
        'lon'   => '',
        'label' => '',
        'units' => 'metric',
        'card'  => '1',
    ), $atts );
    if ( !$atts['lat'] || !$atts['lon'] ) {
        return '🌩️ Error: lat/lon required';
    }
    $weather = mwpl_get_weather( $atts['lat'], $atts['lon'], $atts['units'] );
    if ( !$weather ) {
        return '☁️ Weather unavailable';
    }
    // Card number from shortcode.
	$card = absint( $atts['card'] );
	// Record required card style for late enqueue.
    $GLOBALS['mwpl_cards_needed'][] = $card;
    // Resolve template.
    $template = 'weather-card.php';
    $candidate = MWPL_PATH . "templates/weather-card-{$card}.php";
    if ( $card > 1 && file_exists( $candidate ) ) {
        $template = "weather-card-{$card}.php";
    }
    ob_start();
    include MWPL_PATH . "templates/{$template}";
    $html = ob_get_clean();

    // Theme-isolation wrapper (CSS sandbox target).
    $html = '<div class="mwpl-wrap mwpl-sandbox" data-mwpl="1">' . $html . '</div>';

    // Hard wrapper to isolate against theme CSS.
    $html = '<div class="mwpl-wrap" data-mwpl="1">' . $html . '</div>';

    // Ensure the root card has data-card + data-units (needed for AJAX swaps).
    if ( false === stripos( $html, 'data-card=' ) ) {
        $html = preg_replace(
            '/<div\\s+([^>]*\\bclass="[^"]*\\bmw-card\\b[^"]*"[^>]*)>/i',
            '<div $1 data-card="' . (int) $card . '">',
            $html,
            1
        );
    }
    if ( false === stripos( $html, 'data-units=' ) ) {
        $html = preg_replace(
            '/<div\\s+([^>]*\\bclass="[^"]*\\bmw-card\\b[^"]*"[^>]*)>/i',
            '<div $1 data-units="' . esc_attr( (string) ($atts['units'] ?? 'metric') ) . '">',
            $html,
            1
        );
    }

    return $html;
}

/** --------------------------------------------------------------------
 * Utility: wind formatting (kept)
 * ------------------------------------------------------------------ */
if ( !function_exists( 'mwpl_card15_format_wind' ) ) {
    function mwpl_card15_format_wind(  $speed_mps, $deg, $units = 'metric'  ) {
        $speed = ( 'imperial' === $units ? round( $speed_mps * 2.237, 1 ) : round( $speed_mps * 3.6, 1 ) );
        $dirs = array(
            'N',
            'NNE',
            'NE',
            'ENE',
            'E',
            'ESE',
            'SE',
            'SSE',
            'S',
            'SSW',
            'SW',
            'WSW',
            'W',
            'WNW',
            'NW',
            'NNW'
        );
        $index = (int) ($deg / 22.5 + 0.5) % 16;
        $compass = $dirs[$index];
        return "💨 Wind: {$speed} 🧭 {$compass}";
    }

}
/** --------------------------------------------------------------------
 * Cron: daily reset (unchanged)
 * ------------------------------------------------------------------ */
register_activation_hook( __FILE__, 'mwpl_schedule_daily_reset' );
function mwpl_schedule_daily_reset() {
    if ( !wp_next_scheduled( 'mwpl_reset_api_count' ) ) {
        wp_schedule_event( strtotime( 'midnight' ), 'daily', 'mwpl_reset_api_count' );
    }
}

register_deactivation_hook( __FILE__, 'mwpl_clear_scheduled_reset' );
function mwpl_clear_scheduled_reset() {
    wp_clear_scheduled_hook( 'mwpl_reset_api_count' );
}

add_action( 'mwpl_reset_api_count', 'mwpl_reset_api_call_counter' );
function mwpl_reset_api_call_counter() {
    update_option( 'multiweather_daily_call_count', 0 );
}
