<?php defined('ABSPATH') || exit;
/** @var JRA_Merchant_Auth   $auth */
/** @var JRA_Merchant_Logger $logger */

$settings   = $auth->getSettings();
$tokens     = $auth->getTokens();
$connected  = $auth->isConnected();
$lastSync   = $auth->getLastSyncedAt();
$merchantId = $auth->getMerchantId();
$lastError  = $auth->getLastError();

$recentErrors  = $logger->getRecent(5, 0, 'error');
$showPreview   = isset($_GET['preview']) && $_GET['preview'] === '1'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$previewData   = $showPreview ? get_transient('jra_merchant_preview') : null;
if ($previewData) {
    delete_transient('jra_merchant_preview');
}

// Availability badge helper
$availBadge = function(string $a): string {
    $map = [
        'in stock'     => 'green',
        'out of stock' => 'red',
        'preorder'     => 'orange',
    ];
    $colour = $map[$a] ?? 'blue';
    return '<span class="jra-badge jra-badge--' . $colour . '">' . esc_html($a) . '</span>';
};
?>
<div class="wrap jra-merchant">
    <h1>Google Merchant Feed — Sync</h1>

    <?php if (!$auth->hasSettings()): ?>
        <div class="notice notice-warning">
            <p>You need to <a href="<?php echo esc_url(admin_url('admin.php?page=jra-merchant-feed-settings')) ?>">configure your Google API credentials</a> before syncing.</p>
        </div>
    <?php elseif (!$connected): ?>
        <div class="notice notice-warning">
            <p>Not connected to Google Merchant Center.
               <a href="<?php echo esc_url(admin_url('admin.php?page=jra-merchant-feed-settings')) ?>">Connect now →</a>
            </p>
        </div>
    <?php endif; ?>

    <?php if ($lastError): ?>
        <div class="notice notice-error">
            <p><strong>Last connection error:</strong> <?php echo esc_html($lastError) ?></p>
        </div>
    <?php endif; ?>

    <!-- Status card -->
    <div class="jra-card">
        <h2>Status</h2>
        <table class="jra-status-table">
            <tr>
                <th>Connection</th>
                <td>
                    <?php if ($connected): ?>
                        <span class="jra-badge jra-badge--green">Connected</span>
                    <?php else: ?>
                        <span class="jra-badge jra-badge--red">Not connected</span>
                    <?php endif; ?>
                </td>
            </tr>
            <tr>
                <th>Merchant ID</th>
                <td><?php echo $merchantId ? esc_html($merchantId) : '<em>not set</em>' ?></td>
            </tr>
            <tr>
                <th>Last sync</th>
                <td><?php echo $lastSync ? esc_html($lastSync->format('Y-m-d H:i:s') . ' UTC') : '<em>never</em>' ?></td>
            </tr>
        </table>
    </div>

    <!-- Sync actions -->
    <?php if ($connected && $merchantId): ?>
    <div class="jra-card">
        <h2>Sync actions</h2>
        <div class="jra-sync-actions">

            <div class="jra-sync-block">
                <h3>Delta sync</h3>
                <p>Push products modified since the last sync, and remove products deleted since then. Runs in the background.</p>
                <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')) ?>">
                    <?php wp_nonce_field('jra_merchant_sync') ?>
                    <input type="hidden" name="action" value="jra_merchant_delta_sync">
                    <button type="submit" class="button button-primary">Run delta sync</button>
                </form>
            </div>

            <div class="jra-sync-block">
                <h3>Full sync</h3>
                <p>Push <strong>all</strong> eligible products and remove any orphans from Google. Use this after changes to mappings or exclusions. Runs in the background.</p>
                <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')) ?>">
                    <?php wp_nonce_field('jra_merchant_sync') ?>
                    <input type="hidden" name="action" value="jra_merchant_full_sync">
                    <button type="submit" class="button" onclick="return confirm('Run a full sync? This will push all products to Google Merchant Center.')">Run full sync</button>
                </form>
            </div>

        </div>
    </div>
    <?php endif; ?>

    <!-- Preview / dry run -->
    <div class="jra-card">
        <h2>Preview sync (dry run)</h2>
        <p>Maps up to N products and shows exactly what would be submitted to Google — <strong>no data is sent to Google</strong>. Useful for verifying mappings, prices, availability dates, and images before running a real sync.</p>

        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')) ?>" style="display:flex;align-items:center;gap:10px;">
            <?php wp_nonce_field('jra_merchant_preview') ?>
            <input type="hidden" name="action" value="jra_merchant_preview_sync">
            <label for="preview_limit">Products to preview:</label>
            <input type="number" id="preview_limit" name="preview_limit" value="10" min="1" max="50" style="width:60px;">
            <button type="submit" class="button">Run preview</button>
        </form>
    </div>

    <?php if ($previewData): ?>
    <div class="jra-card" style="max-width:none;">
        <h2>
            Preview results
            <span style="font-size:13px;font-weight:normal;color:#777;margin-left:10px;">
                Showing <?php echo count($previewData['rows']) ?> of <?php echo esc_html($previewData['total']) ?> eligible products
                &mdash; run at <?php echo esc_html($previewData['ran_at']) ?>
            </span>
        </h2>

        <?php if (!empty($previewData['errors'])): ?>
        <div style="margin-bottom:16px;padding:12px 16px;background:#fdf2f2;border:1px solid #f5c2c2;border-radius:3px;">
            <strong style="color:#d63638;">Mapping errors (<?php echo count($previewData['errors']) ?> products skipped):</strong>
            <ul style="margin:6px 0 0;padding-left:20px;">
                <?php foreach ($previewData['errors'] as $id => $msg): ?>
                    <li><?php echo esc_html($msg) ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
        <?php endif; ?>

        <?php if (!empty($previewData['rows'])): ?>
        <div style="overflow-x:auto;">
        <table class="widefat striped" style="font-size:12px;">
            <thead>
                <tr>
                    <th>Offer ID <small style="font-weight:normal;">(→ Google)</small></th>
                    <th>Group ID</th>
                    <th>Title</th>
                    <th>Price</th>
                    <th>Sale</th>
                    <th>Availability</th>
                    <th>Avail. date</th>
                    <th>Image</th>
                    <th>+Images</th>
                    <th>GTIN</th>
                    <th>ID exists</th>
                    <th>Weight</th>
                    <th>Color</th>
                    <th>Size</th>
                    <th>Link</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($previewData['rows'] as $row): ?>
                <tr>
                    <td>
                        <?php if (!empty($row['offer_id_is_mapped'])): ?>
                            <code style="color:#8a6000;" title="Mapped from local ID: <?php echo esc_attr($row['offer_id_local']) ?>"><?php echo esc_html($row['offer_id']) ?></code>
                            <br><span style="font-size:10px;color:#999;" title="Auto-generated offer ID before mapping">← <code><?php echo esc_html($row['offer_id_local']) ?></code></span>
                        <?php else: ?>
                            <code><?php echo esc_html($row['offer_id']) ?></code>
                        <?php endif; ?>
                    </td>
                    <td><?php echo $row['item_group_id'] ? '<code>' . esc_html($row['item_group_id']) . '</code>' : '<span style="color:#ccc">—</span>' ?></td>
                    <td style="max-width:220px;" title="<?php echo esc_attr($row['title']) ?>">
                        <?php echo esc_html(mb_substr($row['title'], 0, 60)) ?><?php echo mb_strlen($row['title']) > 60 ? '…' : '' ?>
                    </td>
                    <td style="white-space:nowrap"><?php echo esc_html($row['price']) ?></td>
                    <td style="white-space:nowrap"><?php echo $row['sale_price'] ? esc_html($row['sale_price']) : '<span style="color:#ccc">—</span>' ?></td>
                    <td><?php echo $availBadge($row['availability']); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></td>
                    <td style="white-space:nowrap;font-size:11px">
                        <?php echo $row['availability_date'] ? esc_html($row['availability_date']) : '<span style="color:#ccc">—</span>' ?>
                    </td>
                    <td>
                        <?php if ($row['has_image']): ?>
                            <a href="<?php echo esc_url($row['image_link']) ?>" target="_blank" title="<?php echo esc_attr($row['image_link']) ?>">
                                <img src="<?php echo esc_url($row['image_link']) ?>" style="width:40px;height:40px;object-fit:cover;border:1px solid #ddd;">
                            </a>
                        <?php else: ?>
                            <span class="jra-badge jra-badge--red">missing</span>
                        <?php endif; ?>
                    </td>
                    <td><?php echo (int)$row['additional_images'] ?></td>
                    <td style="font-size:11px"><?php echo $row['gtin'] ? esc_html($row['gtin']) : '<span style="color:#ccc">—</span>' ?></td>
                    <td>
                        <?php
                        $idBadge = $row['identifier_exists'] === 'yes'
                            ? '<span class="jra-badge jra-badge--green">yes</span>'
                            : '<span class="jra-badge jra-badge--orange">no</span>';
                        echo $idBadge; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                        ?>
                    </td>
                    <td><?php echo $row['weight_g'] ? esc_html($row['weight_g']) : '<span style="color:#ccc">—</span>' ?></td>
                    <td><?php echo $row['color'] ? esc_html($row['color']) : '<span style="color:#ccc">—</span>' ?></td>
                    <td><?php echo $row['size'] ? esc_html($row['size']) : '<span style="color:#ccc">—</span>' ?></td>
                    <td style="max-width:160px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">
                        <a href="<?php echo esc_url($row['link']) ?>" target="_blank" title="<?php echo esc_attr($row['link']) ?>">
                            <?php echo esc_html(str_replace(['https://', 'http://'], '', $row['link'])) ?>
                        </a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        </div>

        <details style="margin-top:16px;">
            <summary style="cursor:pointer;color:#2271b1;">Show full descriptions</summary>
            <table class="widefat striped" style="margin-top:8px;font-size:12px;">
                <thead><tr><th style="width:160px">Offer ID</th><th>Description (first 120 chars)</th></tr></thead>
                <tbody>
                    <?php foreach ($previewData['rows'] as $row): ?>
                    <tr>
                        <td><code><?php echo esc_html($row['offer_id']) ?></code></td>
                        <td><?php echo esc_html($row['description']) ?><?php echo strlen($row['description']) >= 120 ? '…' : '' ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </details>

        <?php endif; ?>
    </div>
    <?php endif; ?>

    <!-- Recent errors -->
    <?php if (!empty($recentErrors)): ?>
    <div class="jra-card">
        <h2>Recent errors <a href="<?php echo esc_url(admin_url('admin.php?page=jra-merchant-feed-log&status=error')) ?>" style="font-size:13px;font-weight:normal;">view all →</a></h2>
        <table class="widefat striped">
            <thead>
                <tr><th>Time (UTC)</th><th>Offer ID</th><th>Message</th></tr>
            </thead>
            <tbody>
                <?php foreach ($recentErrors as $entry): ?>
                <tr>
                    <td style="white-space:nowrap"><?php echo esc_html($entry->created_at) ?></td>
                    <td><?php echo esc_html($entry->offer_id ?? '—') ?></td>
                    <td><?php echo esc_html($entry->message) ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>

    <p style="color:#777;font-size:12px;">
        Syncs run via Action Scheduler (WooCommerce). Check
        <a href="<?php echo esc_url(admin_url('admin.php?page=wc-status&tab=action-scheduler&s=jra_merchant')) ?>">Action Scheduler</a>
        for queue status, or the <a href="<?php echo esc_url(admin_url('admin.php?page=jra-merchant-feed-log')) ?>">log</a> for results.
    </p>
    <p style="color:#777;font-size:12px;">
        Enjoying the plugin? <a href="https://wordpress.org/support/plugin/jons-product-feed-for-google-merchant-center/reviews/#new-post" target="_blank" rel="noopener">Leave a review on WordPress.org &#9733;</a> &mdash; it helps others find it.
    </p>
</div>
