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


class Aysa_Public {
    private $plugin_name;
    private $version;

    public function __construct($plugin_name, $version) {
        $this->plugin_name = $plugin_name;
        $this->version = $version;
    }

    public function enqueue_styles() {
        wp_enqueue_style(
            $this->plugin_name,
            AYSA_PLUGIN_URL . 'assets/css/aysa.css',
            array(),
            $this->version,
            'all'
        );
    }

    public function enqueue_scripts() {
        wp_enqueue_script(
            $this->plugin_name,
            AYSA_PLUGIN_URL . 'assets/js/aysa.js',
            array('jquery'),
            $this->version,
            false
        );

        // Localize the script with new data
        wp_localize_script(
            $this->plugin_name,
            'aysa_ajax',
            array(
                'ajaxurl' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('aysa_ajax_nonce'),
                'home_url' => home_url()
            )
        );
    }

    /**
     * Handle front-end 301 redirects based on API records
     */
    public function handle_frontend_redirect() {
        if (is_admin()) {
            return;
        }
        
        // Enable this for extensive debugging
        $debug = defined('WP_DEBUG') && WP_DEBUG;
        
        // Normalize requested path to match stored SourceUrl
        $req = $_SERVER['REQUEST_URI'];
        if ($debug) aysa_debug_log("[AYSA] Original requested URI: $req");
        
        // Strip WordPress base path
        $base = parse_url(home_url(), PHP_URL_PATH) ?: '';
        if (strpos($req, $base) === 0) {
            $req = substr($req, strlen($base));
        }
        
        // Remove /index.php if present
        $path = preg_replace('#^/index\.php#', '', $req);
        
        if ($debug) aysa_debug_log("[AYSA] Normalized path for redirect check: $path");
        
        // Demo 410 for on-page testing without DB entries
        if ($path === '/fake-410-page') {
            if ($debug) aysa_debug_log("[AYSA] Demo 410 for $path");
            status_header(410);
            nocache_headers();
            exit;
        }
        
        // Fetch redirects from API using centralized config
        $api_url = Aysa_API_Config::get_endpoint_url('redirects');
        
        // Fallback to old method if config not available
        if (!$api_url) {
            $api_url = rtrim(AYSA_API_BASE_URL, '/') . '/api/Redirect';
        }
        
        if ($debug) aysa_debug_log("[AYSA] Fetching redirects from: $api_url");
        
        $response = wp_remote_get($api_url);
        if (is_wp_error($response)) {
            if ($debug) aysa_debug_log('[AYSA] wp_remote_get error: ' . $response->get_error_message());
            return;
        }
        
        $body = wp_remote_retrieve_body($response);
        $items = json_decode($body, true);
        
        if (!is_array($items)) {
            if ($debug) aysa_debug_log('[AYSA] Invalid redirects response: ' . substr($body, 0, 255));
            return;
        }
        
        if ($debug) aysa_debug_log('[AYSA] Found ' . count($items) . ' redirects to process');
        
        // Look for a matching SourceUrl
        foreach ($items as $r) {
            if (isset($r['SourceUrl']) && $r['SourceUrl'] === $path) {
                $dest = isset($r['DestinationUrl']) ? $r['DestinationUrl'] : '';
                if (!empty($dest)) {
                    if ($debug) {
                        aysa_debug_log("[AYSA] Matched redirect: $path → $dest");
                        aysa_debug_log("[AYSA] Redirect details: " . json_encode($r));
                    }
                    
                    // Add home_url to relative paths if needed
                    if (strpos($dest, 'http') !== 0) {
                        $dest = home_url($dest);
                        if ($debug) aysa_debug_log("[AYSA] Expanded destination URL: $dest");
                    }
                    
                    wp_redirect($dest, 301);
                    exit;
                }
            }
        }
        
        if ($debug) aysa_debug_log("[AYSA] No matching redirect found for: $path");
        
        // Get gone URLs from API using centralized config
        $gone_api = Aysa_API_Config::get_endpoint_url('gone_urls');
        
        // Fallback to old method if config not available
        if (!$gone_api) {
            $gone_api = rtrim(AYSA_API_BASE_URL, '/') . '/api/GoneUrl';
        }
        
        $gone_resp = wp_remote_get($gone_api);
        if (!is_wp_error($gone_resp)) {
            $gone_body = wp_remote_retrieve_body($gone_resp);
            $gone_items = json_decode($gone_body, true);
            
            if (is_array($gone_items)) {
                if ($debug) aysa_debug_log('[AYSA] Found ' . count($gone_items) . ' gone URLs');
                
                foreach ($gone_items as $g) {
                    if (isset($g['Url']) && $g['Url'] === $path) {
                        if ($debug) aysa_debug_log("[AYSA] Returning 410 for $path");
                        status_header(410);
                        nocache_headers();
                        exit;
                    }
                }
            }
        }
    }

    /**
     * Disable WordPress canonical redirects to allow plugin redirects to run
     */
    public function disable_canonical_redirect($redirect_url) {
        return false;
    }
} 