<?php defined('ABSPATH') || exit; ?>

<div class="jra-merchant" style="max-width:1200px;">

<?php
// -------------------------------------------------------------------------
// Product list view for a single issue code
// -------------------------------------------------------------------------
if ($viewIssue && $reportData && isset($reportData['issues'][$viewIssue])):
    $issue      = $reportData['issues'][$viewIssue];
    $severityClass = match($issue['severity'] ?? '') {
        'disapproved' => 'jra-badge--red',
        'demoted'     => 'jra-badge--orange',
        default       => 'jra-badge--blue',
    };
    $backUrl    = admin_url('admin.php?page=jra-merchant-feed-reports');
    $csvUrl     = admin_url('admin-post.php?action=jra_merchant_report_csv_download&filter=' . urlencode($viewIssue) . '&_wpnonce=' . wp_create_nonce('jra_merchant_report_csv'));
?>
    <p style="margin-bottom:12px;">
        <a href="<?php echo esc_url($backUrl) ?>">&larr; Back to all issues</a>
    </p>

    <div class="jra-card">
        <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:4px;">
            <h2 style="margin:0;"><code style="font-size:16px;"><?php echo esc_html($viewIssue) ?></code></h2>
            <span class="jra-badge <?php echo esc_attr($severityClass) ?>"><?php echo esc_html($issue['severity'] ?? '') ?></span>
            <a href="<?php echo esc_url($csvUrl) ?>" class="button button-small" style="margin-left:auto;">Download CSV</a>
        </div>
        <?php if (!empty($issue['description'])): ?>
        <p style="margin:4px 0 16px;color:#555;"><?php echo esc_html($issue['description']) ?></p>
        <?php endif; ?>

        <table class="widefat striped" style="border-collapse:collapse;">
            <thead>
                <tr>
                    <th style="width:130px;">Offer ID</th>
                    <th>Title</th>
                    <th style="width:200px;">Detail</th>
                    <th style="width:80px;">Countries</th>
                    <th style="width:60px;text-align:center;">Edit</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($issue['products'] as $product): ?>
                <tr>
                    <td><code style="font-size:11px;"><?php echo esc_html($product['offer_id']) ?></code></td>
                    <td><?php echo esc_html($product['title']) ?></td>
                    <td style="font-size:12px;color:#555;"><?php echo esc_html($product['detail'] ?? '') ?></td>
                    <td style="font-size:12px;">
                        <?php
                        $countries = $product['countries'] ?? [];
                        $limit     = 5;
                        if (count($countries) <= $limit) {
                            echo esc_html(implode(', ', $countries));
                        } else {
                            echo esc_html(implode(', ', array_slice($countries, 0, $limit)));
                            echo ' <span style="color:#888;">+' . (count($countries) - $limit) . ' others</span>';
                        }
                        ?>
                    </td>
                    <td style="text-align:center;">
                        <?php
                        $postId  = $product['post_id'] ?? 0;
                        $editUrl = $postId ? get_edit_post_link($postId) : null;
                        ?>
                        <?php if ($editUrl): ?>
                        <a href="<?php echo esc_url($editUrl) ?>">Edit &rarr;</a>
                        <?php else: ?>
                        <span style="color:#999;">—</span>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

<?php
// -------------------------------------------------------------------------
// Main report view
// -------------------------------------------------------------------------
else:
?>
    <h1>Issue Reports</h1>

    <?php if (!$isRunning && !$reportData): ?>
    <div class="jra-card">
        <p>Generate a report of all product issues from Google Merchant Center. The scan runs in the background and may take a few minutes depending on your catalogue size.</p>
        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')) ?>">
            <input type="hidden" name="action" value="jra_merchant_generate_report">
            <?php wp_nonce_field('jra_merchant_generate_report'); ?>
            <button type="submit" class="button button-primary" style="margin-top:10px;">Generate Report</button>
        </form>
    </div>

    <?php elseif ($isRunning): ?>
    <div class="jra-card" style="border-left:4px solid #0073aa;">
        <p style="margin:0;">
            <span class="spinner is-active" style="float:none;vertical-align:middle;margin:0 6px 0 0;"></span>
            <strong>Report generation is running...</strong>
        </p>
        <?php if ($reportData && ($reportData['pages_scanned'] > 0 || $reportData['total_issues'] > 0)): ?>
        <p style="margin:8px 0 0;font-size:13px;color:#666;">
            <strong>Progress:</strong> <?php echo intval($reportData['pages_scanned']) ?> pages scanned,
            <?php echo intval($reportData['total_issues']) ?> issues found so far
        </p>
        <?php endif; ?>
        <p style="margin:8px 0 0;">Refresh this page to update progress.</p>
    </div>

    <?php elseif ($reportData && $reportData['status'] === 'complete'): ?>
    <div class="jra-card">
        <p style="margin:0 0 8px;">
            <strong>Report generated:</strong> <?php echo esc_html($reportData['generated_at']) ?>
            &nbsp;(<?php echo intval($reportData['pages_scanned']) ?> pages scanned,
            <?php echo intval($reportData['total_issues']) ?> total issues across <?php echo count($reportData['issues']) ?> issue types)
        </p>

        <?php if (empty($reportData['issues'])): ?>
        <p style="color:#00a32a;margin:8px 0 0;">&#10003; No issues found!</p>
        <?php else: ?>

        <table class="widefat striped" style="border-collapse:collapse;margin-top:16px;">
            <thead>
                <tr>
                    <th>Issue code</th>
                    <th>Description</th>
                    <th style="width:80px;text-align:center;">Products</th>
                    <th style="width:100px;">Severity</th>
                    <th style="width:150px;text-align:center;">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($reportData['issues'] as $code => $issue):
                    $severityClass = match($issue['severity'] ?? '') {
                        'disapproved' => 'jra-badge--red',
                        'demoted'     => 'jra-badge--orange',
                        default       => 'jra-badge--blue',
                    };
                    $viewUrl = admin_url('admin.php?page=jra-merchant-feed-reports&view=' . urlencode($code));
                    $csvUrl  = admin_url('admin-post.php?action=jra_merchant_report_csv_download&filter=' . urlencode($code) . '&_wpnonce=' . wp_create_nonce('jra_merchant_report_csv'));
                ?>
                <tr>
                    <td><code style="font-size:12px;"><?php echo esc_html($code) ?></code></td>
                    <td style="font-size:13px;"><?php echo esc_html($issue['description'] ?? '') ?></td>
                    <td style="text-align:center;font-weight:600;"><?php echo intval($issue['count']) ?></td>
                    <td><span class="jra-badge <?php echo esc_attr($severityClass) ?>"><?php echo esc_html($issue['severity'] ?? '') ?></span></td>
                    <td style="text-align:center;">
                        <a href="<?php echo esc_url($viewUrl) ?>" class="button button-small">View</a>
                        <a href="<?php echo esc_url($csvUrl) ?>" class="button button-small">CSV</a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <div style="margin-top:16px;padding:12px;background:#f6f7f7;border:1px solid #ddd;border-radius:2px;display:flex;align-items:center;gap:12px;">
            <a href="<?php echo esc_url(admin_url('admin-post.php?action=jra_merchant_report_csv_download&_wpnonce=' . wp_create_nonce('jra_merchant_report_csv'))) ?>"
               class="button button-secondary">
                Download All Issues (CSV)
            </a>
        </div>
        <?php endif; ?>

        <div style="margin-top:16px;">
            <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')) ?>" style="display:inline;">
                <input type="hidden" name="action" value="jra_merchant_generate_report">
                <?php wp_nonce_field('jra_merchant_generate_report'); ?>
                <button type="submit" class="button">Regenerate Report</button>
            </form>
        </div>
    </div>

    <?php elseif ($reportData && $reportData['status'] === 'failed'): ?>
    <div class="jra-card" style="border-left:4px solid #d63638;">
        <p style="margin:0;color:#d63638;"><strong>Report generation failed:</strong></p>
        <p style="margin:8px 0 0;color:#666;"><?php echo esc_html($reportData['error_message'] ?? 'Unknown error') ?></p>
        <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')) ?>" style="margin-top:16px;">
            <input type="hidden" name="action" value="jra_merchant_generate_report">
            <?php wp_nonce_field('jra_merchant_generate_report'); ?>
            <button type="submit" class="button button-primary">Try Again</button>
        </form>
    </div>
    <?php endif; ?>

<?php endif; ?>

</div>
