<?php
/**
 * Remote notification helpers for Chalak Driving School themes.
 * 
 * IMPORTANT: This theme is designed for customers who use our free theme.
 * The plugin (Notify Manager) is ONLY installed on our main site (luzukdemo.com).
 * Customers do NOT need to install any plugin - theme automatically fetches 
 * notifications from our centralized server.
 *
 * @package nirman_construction
 */

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

/**
 * Get the API endpoint for notifications.
 * 
 * CONCEPT:
 * - Default: Remote endpoint (luzukdemo.com) - for customers' sites
 * - If plugin active: Local endpoint - only for our main site (luzukdemo.com)
 * 
 * Customers' sites will always use remote endpoint since they don't have plugin.
 * Only our main site (luzukdemo.com) has the plugin, so it uses local endpoint.
 *
 * @return string Notification API endpoint URL
 */
function nirman_construction_get_notification_endpoint() {
    // Default remote endpoint for customers' sites
    // This is where our plugin is installed (luzukdemo.com)
    $default = defined( 'nirman_construction_NOTIFICATION_ENDPOINT' )
        ? nirman_construction_NOTIFICATION_ENDPOINT
        : 'https://www.luzukdemo.com/demo/testing/wp-json/notify-manager/v1/notifications';

    /**
     * Filter the notification endpoint used by the theme.
     *
     * @param string $endpoint Endpoint URL.
     */
    return apply_filters( 'nirman_construction_notification_endpoint', $default );
}

/**
 * Auto-detect endpoint based on plugin availability.
 * 
 * - If plugin is active (our main site): Use local endpoint
 * - If plugin is NOT active (customers' sites): Use remote endpoint (default)
 */
add_filter(
    'nirman_construction_notification_endpoint',
    function ( $endpoint ) {
        // Only our main site (luzukdemo.com) has the plugin installed
        // So if plugin exists, use local endpoint
        if ( class_exists( 'Notify_Manager' ) ) {
            return home_url( '/wp-json/notify-manager/v1/notifications' );
        }

        // Customers' sites don't have plugin, so use remote endpoint
        return $endpoint;
    }
);

/**
 * Retrieve remote notifications with caching.
 *
 * @return array[]
 */
function nirman_construction_get_remote_notifications() {
    $endpoint = nirman_construction_get_notification_endpoint();

    if ( empty( $endpoint ) || ! filter_var( $endpoint, FILTER_VALIDATE_URL ) ) {
        return array();
    }

    $cache_key      = 'nirman_construction_remote_notifications';
    $cached         = get_transient( $cache_key );
    $cache_duration = (int) apply_filters( 'nirman_construction_notification_cache_ttl', 15 * MINUTE_IN_SECONDS );

    if ( false !== $cached ) {
        return $cached;
    }

    $response = wp_remote_get(
        $endpoint,
        array(
            'timeout'    => 8,
            'user-agent' => 'nirman-construction-Gym-Fitness/' . wp_get_theme()->get( 'Version' ) . '; ' . home_url(),
        )
    );

    if ( is_wp_error( $response ) ) {
        // Log error for debugging
        if ( defined( 'WP_DEBUG' ) && WP_DEBUG && defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
            error_log( 'Chalak Driving School Notifications: Error fetching from ' . $endpoint . ' - ' . $response->get_error_message() );
        }
        set_transient( $cache_key, array(), $cache_duration );
        return array();
    }

    $status = wp_remote_retrieve_response_code( $response );
    if ( 200 !== $status ) {
        // Log non-200 response for debugging
        if ( defined( 'WP_DEBUG' ) && WP_DEBUG && defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
            $body = wp_remote_retrieve_body( $response );
            error_log( 'Chalak Driving School Notifications: HTTP ' . $status . ' from ' . $endpoint . ' - Response: ' . substr( $body, 0, 200 ) );
        }
        set_transient( $cache_key, array(), $cache_duration );
        return array();
    }

    $body = wp_remote_retrieve_body( $response );
    $data = json_decode( $body, true );

    // Store last response for debugging (always, not just on error)
    update_option( 'nirman_construction_notification_last_response', array(
        'code' => $status,
        'body' => substr( $body, 0, 500 ),
        'time' => current_time( 'mysql' ),
        'endpoint' => $endpoint,
        'data_structure' => is_array( $data ) ? 'array' : 'not_array',
        'has_notifications' => ( is_array( $data ) && ! empty( $data['notifications'] ) ) ? 'yes' : 'no',
    ), false );

    // Log response for debugging
    if ( defined( 'WP_DEBUG' ) && WP_DEBUG && defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
        error_log( 'Chalak Driving School Notifications: Response from ' . $endpoint . ' - Code: ' . $status . ' - Data: ' . wp_json_encode( $data ) );
    }

    if ( ! is_array( $data ) || empty( $data['notifications'] ) || ! is_array( $data['notifications'] ) ) {
        // Log empty response for debugging
        if ( defined( 'WP_DEBUG' ) && WP_DEBUG && defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
            $debug_msg = 'Chalak Driving School Notifications: Empty or invalid response from ' . $endpoint;
            if ( is_array( $data ) ) {
                $debug_msg .= ' - Array keys: ' . implode( ', ', array_keys( $data ) );
                if ( isset( $data['count'] ) ) {
                    $debug_msg .= ' - Count: ' . $data['count'];
                }
            } else {
                $debug_msg .= ' - Not an array, body: ' . substr( $body, 0, 200 );
            }
            error_log( $debug_msg );
        }
        set_transient( $cache_key, array(), $cache_duration );
        return array();
    }

    $allowed_tags = apply_filters(
        'nirman_construction_notification_allowed_tags',
        array_merge(
            wp_kses_allowed_html( 'post' ),
            array(
                'iframe' => array(
                    'src'             => true,
                    'height'          => true,
                    'width'           => true,
                    'frameborder'     => true,
                    'allow'           => true,
                    'allowfullscreen' => true,
                ),
            )
        )
    );

    $notifications = array();

    foreach ( $data['notifications'] as $notification ) {
        if ( empty( $notification['html'] ) ) {
            continue;
        }

        $notifications[] = array(
            'id'    => isset( $notification['id'] ) ? (int) $notification['id'] : 0,
            'title' => isset( $notification['title'] ) ? sanitize_text_field( $notification['title'] ) : '',
            'html'  => wp_kses( $notification['html'], $allowed_tags ),
            'start' => isset( $notification['start'] ) ? sanitize_text_field( $notification['start'] ) : '',
            'end'   => isset( $notification['end'] ) ? sanitize_text_field( $notification['end'] ) : '',
        );
    }

    set_transient( $cache_key, $notifications, $cache_duration );

    return $notifications;
}

/**
 * Return the latest notification.
 *
 * @return array|null
 */
function nirman_construction_get_latest_notification() {
    $notifications = nirman_construction_get_remote_notifications();

    if ( empty( $notifications ) ) {
        return null;
    }

    return $notifications[0];
}

/**
 * Output banner on the front-end for visitors.
 */
function nirman_construction_render_front_notification() {
    if ( ! apply_filters( 'nirman_construction_enable_front_notification', true ) ) {
        return;
    }

    $notification = nirman_construction_get_latest_notification();

    if ( empty( $notification ) ) {
        return;
    }

    echo '<div class="nirman-construction-remote-notification" role="complementary">';
    echo '<div class="nirman-construction-remote-notification__inner">';
    echo $notification['html']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
    echo '</div>';
    echo '</div>';
}
add_action( 'wp_body_open', 'nirman_construction_render_front_notification', 5 );

/**
 * Register dashboard widget for administrators.
 */
function nirman_construction_register_dashboard_notification_widget() {
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }

    if ( ! apply_filters( 'nirman_construction_enable_dashboard_notification', true ) ) {
        return;
    }

    wp_add_dashboard_widget(
        'nirman_construction_remote_notifications',
        __( 'Chalak Driving School Theme Updates', 'nirman-construction-gym-fitness' ),
        'nirman_construction_render_dashboard_notification_widget'
    );
}
add_action( 'wp_dashboard_setup', 'nirman_construction_register_dashboard_notification_widget' );

/**
 * Render dashboard widget content.
 */
function nirman_construction_render_dashboard_notification_widget() {
    // Handle cache clear request via form
    if ( isset( $_POST['clear_notification_cache'] ) && check_admin_referer( 'clear_notification_cache_action', 'clear_notification_cache_nonce' ) ) {
        delete_transient( 'nirman_construction_remote_notifications' );
        // Also clear the last response option to force fresh fetch
        delete_option( 'nirman_construction_notification_last_response' );
        echo '<div class="notice notice-success is-dismissible"><p><strong>' . esc_html__( 'Notification cache cleared!', 'nirman-construction-gym-fitness' ) . '</strong> ' . esc_html__( 'Page will refresh to fetch fresh data...', 'nirman-construction-gym-fitness' ) . '</p></div>';
        echo '<script>setTimeout(function(){ location.reload(); }, 1500);</script>';
    }

    $endpoint = nirman_construction_get_notification_endpoint();
    $notifications = nirman_construction_get_remote_notifications();

    // Show refresh button (only for admins)
    if ( current_user_can( 'manage_options' ) ) {
        echo '<form method="post" style="margin-bottom: 15px;">';
        wp_nonce_field( 'clear_notification_cache_action', 'clear_notification_cache_nonce' );
        echo '<button type="submit" name="clear_notification_cache" value="1" class="button button-small">';
        echo esc_html__( 'Refresh Notifications', 'nirman-construction-gym-fitness' );
        echo '</button>';
        echo '</form>';
    }

    if ( empty( $notifications ) ) {
        echo '<p>' . esc_html__( 'No announcements right now. Check back soon!', 'nirman-construction-gym-fitness' ) . '</p>';
        
        // Only show debug info if WP_DEBUG is enabled (for developers)
        if ( defined( 'WP_DEBUG' ) && WP_DEBUG && current_user_can( 'manage_options' ) ) {
            $cached = get_transient( 'nirman_construction_remote_notifications' );
            $last_response = get_option( 'nirman_construction_notification_last_response', array() );
            
            echo '<div style="margin-top: 15px; padding: 15px; background: #f9f9f9; border: 1px solid #ddd; border-radius: 4px; font-size: 12px;">';
            echo '<strong style="display: block; margin-bottom: 10px; color: #333;">Debug Information (WP_DEBUG enabled):</strong>';
            echo '<table style="width: 100%; border-collapse: collapse;">';
            echo '<tr><td style="padding: 5px; font-weight: bold; width: 150px;">Endpoint:</td><td style="padding: 5px;"><code>' . esc_html( $endpoint ) . '</code></td></tr>';
            echo '<tr><td style="padding: 5px; font-weight: bold;">Cache Status:</td><td style="padding: 5px;">' . ( false !== $cached ? '<span style="color: orange;">Cached (empty array)</span>' : '<span style="color: green;">No cache - will fetch fresh</span>' ) . '</td></tr>';
            echo '<tr><td style="padding: 5px; font-weight: bold;">Plugin Active:</td><td style="padding: 5px;">' . ( class_exists( 'Notify_Manager' ) ? '<span style="color: green;">Yes</span>' : '<span style="color: red;">No (using remote endpoint)</span>' ) . '</td></tr>';
            
            if ( ! empty( $last_response ) ) {
                echo '<tr><td style="padding: 5px; font-weight: bold;">Last API Response:</td><td style="padding: 5px;">';
                if ( isset( $last_response['code'] ) ) {
                    $code = $last_response['code'];
                    $color = ( $code >= 200 && $code < 300 ) ? 'green' : 'red';
                    echo '<span style="color: ' . esc_attr( $color ) . ';">HTTP ' . esc_html( $code ) . '</span>';
                }
                if ( isset( $last_response['body'] ) && ! empty( $last_response['body'] ) ) {
                    echo '<br><small style="color: #666; margin-top: 5px; display: block;">' . esc_html( substr( $last_response['body'], 0, 200 ) ) . '</small>';
                }
                if ( isset( $last_response['time'] ) ) {
                    echo '<br><small style="color: #999;">Last checked: ' . esc_html( $last_response['time'] ) . '</small>';
                }
                echo '</td></tr>';
            }
            
            echo '</table>';
            echo '<p style="margin-top: 10px; margin-bottom: 0;"><small style="color: #666;">💡 Tip: Click "Refresh Notifications" button above to clear cache and fetch fresh data from API.</small></p>';
            echo '</div>';
        }
        return;
    }

    foreach ( $notifications as $notification ) {
        echo '<div class="nirman-construction-dashboard-notification">';
        if ( ! empty( $notification['title'] ) ) {
            echo '<h3>' . esc_html( $notification['title'] ) . '</h3>';
        }
        echo '<div class="nirman-construction-dashboard-notification__content">';
        echo $notification['html']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        echo '</div>';
        if ( ! empty( $notification['start'] ) || ! empty( $notification['end'] ) ) {
            echo '<div style="margin-top: 10px; font-size: 11px; color: #666;">';
            if ( ! empty( $notification['start'] ) ) {
                echo 'Start: ' . esc_html( $notification['start'] ) . ' ';
            }
            if ( ! empty( $notification['end'] ) ) {
                echo 'End: ' . esc_html( $notification['end'] );
            }
            echo '</div>';
        }
        echo '</div>';
    }
}

/**
 * Output latest notification as an admin notice on the dashboard.
 */
function nirman_construction_admin_dashboard_notice() {
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }

    $screen = get_current_screen();

    if ( ! $screen || 'dashboard' !== $screen->base ) {
        return;
    }

    if ( ! apply_filters( 'nirman_construction_enable_dashboard_notice', true ) ) {
        return;
    }

    $notification = nirman_construction_get_latest_notification();

    if ( empty( $notification ) ) {
        return;
    }

    echo '<div class="notice notice-info nirman-construction-remote-admin-notice">';
    if ( ! empty( $notification['title'] ) ) {
        echo '<strong class="nirman-construction-remote-admin-notice__title">' . esc_html( $notification['title'] ) . '</strong>';
    }
    echo '<div class="nirman-construction-remote-admin-notice__content">';
    echo $notification['html']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
    echo '</div>';
    echo '</div>';
}
add_action( 'admin_notices', 'nirman_construction_admin_dashboard_notice' );

/**
 * Output latest notification as an admin notice on Posts, Pages, and Appearance menus.
 */
function nirman_construction_admin_menu_notices() {
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }

    $screen = get_current_screen();
    
    if ( ! $screen ) {
        return;
    }

    // Check if current screen is in allowed list
    $is_allowed = false;
    
    // Check for Posts menu - edit.php, post.php, post-new.php
    if ( ( 'edit' === $screen->base && 'post' === $screen->post_type ) || 
         ( 'post' === $screen->base && 'post' === $screen->post_type ) ||
         ( 'post' === $screen->id ) || 
         ( 'edit-post' === $screen->id ) ||
         ( strpos( $screen->id, 'post' ) !== false && $screen->base === 'post' ) ) {
        $is_allowed = true;
    }
    
    // Check for Pages menu - edit.php?post_type=page, page.php, page-new.php
    if ( ( 'edit' === $screen->base && 'page' === $screen->post_type ) || 
         ( 'post' === $screen->base && 'page' === $screen->post_type ) ||
         ( 'page' === $screen->id ) || 
         ( 'edit-page' === $screen->id ) ||
         ( strpos( $screen->id, 'page' ) !== false && $screen->base === 'post' ) ) {
        $is_allowed = true;
    }
    
    // Check for Appearance menu - themes, customize, widgets, menus, etc.
    if ( 'themes' === $screen->base || 
         'appearance' === $screen->base || 
         'customize' === $screen->base ||
         strpos( $screen->id, 'themes' ) !== false ||
         strpos( $screen->id, 'widgets' ) !== false ||
         strpos( $screen->id, 'nav-menus' ) !== false ||
         strpos( $screen->id, 'customize' ) !== false ||
         strpos( $screen->id, 'theme' ) !== false ||
         strpos( $screen->id, 'appearance' ) !== false ) {
        $is_allowed = true;
    }
    
    if ( ! $is_allowed ) {
        return;
    }

    if ( ! apply_filters( 'nirman_construction_enable_menu_notices', true ) ) {
        return;
    }

    $notification = nirman_construction_get_latest_notification();

    if ( empty( $notification ) ) {
        return;
    }

    echo '<div class="notice notice-info nirman-construction-remote-admin-notice nirman-construction-menu-notice" style="margin: 15px 0;">';
    if ( ! empty( $notification['title'] ) ) {
        echo '<strong class="nirman-construction-remote-admin-notice__title">' . esc_html( $notification['title'] ) . '</strong>';
    }
    echo '<div class="nirman-construction-remote-admin-notice__content">';
    echo $notification['html']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
    echo '</div>';
    echo '</div>';
}
add_action( 'admin_notices', 'nirman_construction_admin_menu_notices' );

/**
 * Add simple styling for dashboard widget and admin notices.
 */
function nirman_construction_dashboard_notification_styles() {
    $screen = get_current_screen();

    if ( ! $screen ) {
        return;
    }

    // Show styles on dashboard, posts, pages, and appearance screens
    $allowed_screens = array( 'dashboard', 'edit-post', 'post', 'post-new', 'edit-page', 'page', 'page-new', 'themes', 'theme-install', 'customize', 'widgets', 'nav-menus' );
    
    $is_allowed = false;
    if ( in_array( $screen->id, $allowed_screens, true ) ) {
        $is_allowed = true;
    }
    
    // Also check by base
    if ( 'edit' === $screen->base || 'themes' === $screen->base || 'appearance' === $screen->base || 'customize' === $screen->base || 'dashboard' === $screen->base ) {
        $is_allowed = true;
    }
    
    if ( ! $is_allowed ) {
        return;
    }

    echo '<style>
    #nirman_construction_remote_notifications .inside {
        padding: 15px;
    }
    .nirman-construction-dashboard-notification h3 {
        margin-top: 0;
        font-size: 16px;
    }
    .nirman-construction-dashboard-notification__content p:last-child {
        margin-bottom: 0;
    }
    .nirman-construction-remote-admin-notice {
        border-left-color: #e74c3c;
        border-left-width: 4px;
        padding: 15px 20px;
        margin: 15px 0;
        background: #fff;
        box-shadow: 0 1px 1px rgba(0,0,0,.04);
    }
    .nirman-construction-menu-notice {
        margin-top: 20px;
        margin-bottom: 20px;
        position: relative;
    }
    .wrap .nirman-construction-menu-notice {
        margin-top: 0;
        margin-bottom: 20px;
    }
    .nirman-construction-remote-admin-notice__title {
        display: block;
        margin-bottom: 6px;
        font-size: 15px;
        font-weight: 600;
    }
    .nirman-construction-remote-admin-notice__content {
        margin-top: 8px;
    }
    .nirman-construction-remote-admin-notice__content > :last-child {
        margin-bottom: 0;
    }
    .nirman-construction-remote-admin-notice__content p {
        margin: 0.5em 0;
    }
    </style>';
}
add_action( 'admin_head', 'nirman_construction_dashboard_notification_styles' );