<?php
/**
 * Core functionality for TW Link Expiration Manager plugin.
 * Handles meta boxes, post meta saving, quick edit, and expiration logic.
 */

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

// Add Meta Box to All Public Post Types
add_action('add_meta_boxes', function () {
    $post_types = get_post_types(['public' => true], 'names');
    foreach ($post_types as $post_type) {
        add_meta_box(
            'tw_lem_expiration_box',
            __('Link Expiration', 'tw-link-expiration-manager'),
            'tw_lem_expiration_field_callback',
            $post_type,
            'side'
        );
    }
});

// Render Meta Box Field
function tw_lem_expiration_field_callback($post)
{
    $expiration = get_post_meta($post->ID, '_tw_lem_expiration', true);
    $value = '';

    if (!empty($expiration)) {
        $ts = strtotime($expiration);
        if ($ts !== false) {
            $value = gmdate('Y-m-d\TH:i', $ts);
        }
    }

    wp_nonce_field('tw_lem_expiration_nonce_action', 'tw_lem_expiration_nonce');

    echo '<label for="tw_lem_expiration" style="display: block; margin-bottom: 10px;">' .
        esc_html__('Expiration Time:', 'tw-link-expiration-manager') .
        '</label>';
    echo '<input type="datetime-local" id="tw_lem_expiration" name="tw_lem_expiration" value="' .
        esc_attr($value) . '" style="width:100%;" />';
}

// Save Meta on Post Save (All Types)
add_action('save_post', function ($post_id) {
    if (
        defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ||
        wp_is_post_revision($post_id) ||
        !current_user_can('edit_post', $post_id)
    ) {
        return;
    }

    // From Edit screen Meta Box
    if (
        isset($_POST['tw_lem_expiration_nonce']) &&
        wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['tw_lem_expiration_nonce'])), 'tw_lem_expiration_nonce_action')
    ) {
        if (isset($_POST['tw_lem_expiration'])) {
            $expiration = sanitize_text_field(wp_unslash($_POST['tw_lem_expiration']));
            tw_lem_save_expiration($post_id, $expiration);
        }
        return;
    }

    // From Quick Edit
    if (
        isset($_POST['tw_lem_quickedit_nonce']) &&
        wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['tw_lem_quickedit_nonce'])), 'tw_lem_quickedit_nonce_action')
    ) {
        if (isset($_POST['tw_lem_expiration'])) {
            $expiration = sanitize_text_field(wp_unslash($_POST['tw_lem_expiration']));
            tw_lem_save_expiration($post_id, $expiration);
        }
        return;
    }
});

function tw_lem_save_expiration($post_id, $raw_value)
{
    if (!empty($raw_value)) {
        $site_timezone = get_option('timezone_string') ?: 'UTC';
        $dt = DateTime::createFromFormat(
            'Y-m-d\TH:i',
            $raw_value,
            new DateTimeZone($site_timezone)
        );

        if ($dt) {
            $utc_value = $dt->format('Y-m-d\TH:i');
            update_post_meta($post_id, '_tw_lem_expiration', $utc_value);
            update_post_meta($post_id, '_tw_lem_expiration_ts', $dt->getTimestamp());
        }
    } else {
        delete_post_meta($post_id, '_tw_lem_expiration');
        delete_post_meta($post_id, '_tw_lem_expiration_ts');
    }
}

// Frontend Expiration Check
add_action('template_redirect', function () {
    if (!is_singular()) {
        return;
    }

    global $post;

    if (empty($post) || !isset($post->ID)) {
        return;
    }

    $expiration_ts = get_post_meta($post->ID, '_tw_lem_expiration_ts', true);

    if ($expiration_ts && time() > $expiration_ts) {
        // Set to draft
        wp_update_post([
            'ID' => $post->ID,
            'post_status' => 'draft'
        ]);

        // Force 404
        global $wp_query;
        $wp_query->set_404();
        status_header(404);
        nocache_headers();
        include get_query_template('404');
        exit;
    }
});

// Expiration Column for Admin (All Public Types + Product)
function tw_lem_add_expiration_column($columns)
{
    $columns['tw_lem_expiration_column'] = __('Expiration', 'tw-link-expiration-manager');
    return $columns;
}

function tw_lem_render_expiration_column($column_name, $post_id)
{
    if ($column_name === 'tw_lem_expiration_column') {
        $expiration = get_post_meta($post_id, '_tw_lem_expiration', true);
        echo '<div class="tw-lem-expiration-data">' . esc_attr($expiration) . '</div>';
    }
}

$all_post_types = array_merge(
    get_post_types(['public' => true], 'names'),
    ['product']
);
$all_post_types = array_unique($all_post_types);

foreach ($all_post_types as $post_type) {
    add_filter("manage_{$post_type}_posts_columns", 'tw_lem_add_expiration_column');
    add_action("manage_{$post_type}_posts_custom_column", 'tw_lem_render_expiration_column', 10, 2);
}

// Dynamic Column Registration (Redundant fallback, fine to keep)
add_action('admin_init', function () {
    $post_types = array_unique(array_merge(
        get_post_types(['public' => true], 'names'),
        ['product']
    ));

    foreach ($post_types as $type) {
        add_filter("manage_{$type}_posts_columns", 'tw_lem_add_expiration_column');
        add_action("manage_{$type}_posts_custom_column", 'tw_lem_render_expiration_column', 10, 2);
    }
});

// Dynamic Quick Edit Field
add_action('quick_edit_custom_box', function ($column_name, $post_type) {
    $supported_types = array_unique(array_merge(
        get_post_types(['public' => true], 'names'),
        ['product']
    ));

    if ($column_name === 'tw_lem_expiration_column' && in_array($post_type, $supported_types)) {
        ?>
        <fieldset class="inline-edit-col-right">
            <div class="inline-edit-col">
                <label style="display: flex; gap: 18px; padding: 5px 0;">
                    <span class="title"
                        style="white-space: nowrap; margin-bottom: 2px;"><?php esc_html_e('Link Expiration', 'tw-link-expiration-manager'); ?></span>
                    <input type="datetime-local" name="tw_lem_expiration" class="tw-lem-expiration-input"
                        style="max-width: 100%; padding: 4px 8px; font-size: 13px;">
                </label>
                <?php wp_nonce_field('tw_lem_quickedit_nonce_action', 'tw_lem_quickedit_nonce'); ?>
            </div>
        </fieldset>
        <?php
    }
}, 10, 2);


// WooCommerce Meta Save Hook with Nonce & Sanitization
add_action('woocommerce_process_product_meta', function ($post_id) {
    if (
        isset($_POST['tw_lem_expiration_nonce']) &&
        wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['tw_lem_expiration_nonce'])), 'tw_lem_expiration_nonce_action')
    ) {
        if (isset($_POST['tw_lem_expiration'])) {
            $expiration = sanitize_text_field(wp_unslash($_POST['tw_lem_expiration']));
            tw_lem_save_expiration($post_id, $expiration);
        }
    }
});