<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ -- NUCLEAR+++
// File: /includes/class-store-channel.php
// Description: Store channel shim -- plugs store dashboard into the Social Media page nav - NUCLEAR+++
// Last Edited: 2026-05-15
// ==================================================

namespace AutoMarketerAI;

defined('ABSPATH') || exit;

final class StoreChannel implements ChannelInterface
{
    public function get_slug(): string
    {
        return 'store';
    }

    public function get_label(): string
    {
        return 'Store';
    }

    public function get_color(): string
    {
        return '#D97757';
    }

    public function is_available(): bool
    {
        return true;
    }

    public function get_connection_status(): string
    {
        return ProductCatalog::isConnected() ? 'connected' : 'disconnected';
    }

    public function handle_actions(): void
    {
        if (
            isset($_POST['amai_store_action']) &&
            (string) $_POST['amai_store_action'] === 'sync_now'
        ) {
            if (!current_user_can('manage_automarketer_ai')) {
                wp_die('Unauthorized');
            }

            if (!isset($_POST['_wpnonce']) || !wp_verify_nonce(
                sanitize_text_field(wp_unslash($_POST['_wpnonce'])),
                'amai_store_sync_now'
            )) {
                wp_die('Nonce verification failed.');
            }

            ProductCatalog::sync();

            wp_safe_redirect(admin_url('admin.php?page=automarketer-ai-woocommerce&tab=store&synced=1'));
            exit;
        }
    }

    public function render(): void
    {
        $is_connected   = ProductCatalog::isConnected();
        $catalog_count  = ProductCatalog::getCount();
        $catalog_health = ProductCatalog::getHealth();
        $last_synced_raw = (string) get_option('amai_store_last_synced', '');
        $last_synced    = $last_synced_raw !== '' ? gmdate('M j, Y', strtotime($last_synced_raw)) : '';
        $recent_posts   = $this->getRecentProductPosts();

        // $provider not needed for WooCommerce -- pass name and icon directly
        $provider_name = 'WooCommerce';
        $provider_icon = '<svg viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg" style="width:40px;height:40px;"><rect width="32" height="32" rx="8" fill="#7F54B3"/><path d="M5 9.5C5 8.4 5.9 7.5 7 7.5h18c1.1 0 2 .9 2 2v9c0 1.1-.9 2-2 2h-7l-4 4v-4H7c-1.1 0-2-.9-2-2v-9z" fill="white"/><path d="M8 13h2.5l1 4.5 2-4.5h1.5l2 4.5 1-4.5H20" stroke="#7F54B3" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round"/></svg>';

        include AMAI_PLUGIN_DIR . 'templates/social/store-dashboard.php';
    }

    // ------------------------------------------------------------------
    // Fetch the 10 most recent product_promotion posts
    // ------------------------------------------------------------------
    private function getRecentProductPosts(): array
    {
        global $wpdb;

        $rows = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT channel, post_content, status, scheduled_date
                 FROM {$wpdb->prefix}amai_scheduled_posts
                 WHERE post_type = %s
                 ORDER BY created_at DESC
                 LIMIT 10",
                'product_promotion'
            ),
            ARRAY_A
        );

        return is_array($rows) ? $rows : [];
    }
}