<?php
/**
 * Admin assets loader.
 *
 * @package PrimeLink
 */

namespace PrimeLink\Core\Admin;

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

final class Assets {

    /**
     * Get asset URL, preferring minified versions in production.
     *
     * @param string $relative Relative path under assets/admin (e.g. 'css/mt-primelink-admin.css').
     * @return string
     */
    public static function get_asset_url( $relative ) {
        $base_path = MT_PRIMELINK_PATH . 'assets/admin/';
        $base_url  = MT_PRIMELINK_URL . 'assets/admin/';

        $full_path = $base_path . $relative;
        $full_url  = $base_url . $relative;

        // In non-debug mode, prefer .min files when they exist.
        if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
            return $full_url;
        }

        // Try to swap to .min version if available.
        if ( str_ends_with( $relative, '.css' ) ) {
            $min_relative = substr( $relative, 0, -4 ) . '.min.css';
        } elseif ( str_ends_with( $relative, '.js' ) ) {
            $min_relative = substr( $relative, 0, -3 ) . '.min.js';
        } else {
            $min_relative = '';
        }

        if ( ! empty( $min_relative ) ) {
            $min_path = $base_path . $min_relative;
            if ( file_exists( $min_path ) ) {
                return $base_url . $min_relative;
            }
        }

        return $full_url;
    }

    /**
     * Get dynamic version string for an asset (filemtime fallback).
     *
     * @param string $relative Relative path under assets/admin.
     * @return string
     */
    public static function get_asset_version( $relative ) {
        $base_path = MT_PRIMELINK_PATH . 'assets/admin/';

        $full_path = $base_path . $relative;

        // Prefer filemtime for cache-busting in production.
        if ( file_exists( $full_path ) ) {
            $mtime = filemtime( $full_path );
            if ( $mtime ) {
                return MT_PRIMELINK_VERSION . '-' . $mtime;
            }
        }

        return MT_PRIMELINK_VERSION;
    }

    public static function register() {
        add_action( 'admin_enqueue_scripts', array( __CLASS__, 'enqueue' ) );
    }

    public static function enqueue( $hook ) {
        
        if ( false === strpos( $hook, 'mt-primelink' ) && false === strpos( $hook, 'primelink' ) ) {
            return;
        }

        $admin_css_relative = 'css/mt-primelink-admin.css';
        wp_enqueue_style(
            'mt-primelink-admin',
            self::get_asset_url( $admin_css_relative ),
            array(),
            self::get_asset_version( $admin_css_relative )
        );

        $glass_css_relative = 'css/mt-primelink-glass.css';
        wp_enqueue_style(
            'mt-primelink-glass',
            self::get_asset_url( $glass_css_relative ),
            array( 'mt-primelink-admin' ),
            self::get_asset_version( $glass_css_relative )
        );

        // Statistics page specific assets - Chart.js must be loaded before main script
        $dependencies = array( 'jquery' );
        // Check if this is the statistics page (hook can be 'toplevel_page_mt-primelink-statistics' or 'mt-primelink_page_mt-primelink-statistics')
        if ( false !== strpos( $hook, 'mt-primelink-statistics' ) || false !== strpos( $hook, 'statistics' ) ) {
            // Load Chart.js locally (Envato requirement: no CDN dependencies)
            // NOTE: Chart.js file must be downloaded and placed in assets/admin/js/chart.umd.min.js
            $chart_js_relative = 'js/chart.umd.min.js';
            $chart_js_path     = MT_PRIMELINK_PATH . 'assets/admin/js/chart.umd.min.js';
            if ( file_exists( $chart_js_path ) ) {
                wp_enqueue_script(
                    'chart-js',
                    MT_PRIMELINK_URL . 'assets/admin/js/chart.umd.min.js',
                    array(),
                    self::get_asset_version( $chart_js_relative ),
                    false // Load in header to ensure it's available before our script
                );
                $dependencies[] = 'chart-js';
            }
        }

        // Google Picker API will be loaded dynamically in JavaScript when needed

        $admin_js_relative = 'js/mt-primelink-admin.js';
        wp_enqueue_script(
            'mt-primelink-admin',
            self::get_asset_url( $admin_js_relative ),
            $dependencies,
            self::get_asset_version( $admin_js_relative ),
            true
        );

        $settings = get_option( 'mt_primelink_settings', array() );
        $gdrive_client_id = $settings['gdrive_client_id'] ?? '';
        $gdrive_api_key = $settings['gdrive_api_key'] ?? '';
        $gdrive_access_token = $settings['gdrive_access_token'] ?? '';
        $onedrive_access_token = $settings['onedrive_access_token'] ?? '';

       wp_localize_script(
        'mt-primelink-admin',
        'mtPrimeLink',
        array(
            'restUrl'   => esc_url_raw( rest_url( 'primelink/v1' ) ),
            'restNonce' => wp_create_nonce( 'wp_rest' ),
            'adminUrl'  => admin_url(),
            'ajaxUrl'   => admin_url( 'admin-ajax.php' ),
            'ajaxNonce' => wp_create_nonce( 'mt_primelink_nonce' ),
            'wpDebug'   => defined( 'WP_DEBUG' ) && WP_DEBUG,
            'gdrive'    => array(
                'clientId'    => esc_js( $gdrive_client_id ),
                'apiKey'      => esc_js( $gdrive_api_key ),
                'accessToken' => esc_js( $gdrive_access_token ),
            ),
            'onedrive'  => array(
                'accessToken' => esc_js( $onedrive_access_token ),
            ),
            'i18n'      => array(
                'restarting' => esc_js( __( 'Restarting...', 'primelink' ) ),
            ),
        )
        );
    }
}
