<?php
/**
 * Orphan Cleanup View — NEW in v4.1
 *
 * Variables in scope:
 *   $scan_status   - array: scan state (see get_scan_status)
 *   $is_configured - bool: whether R2 credentials are present
 *
 * @package Wrenio_Media_Offload
 */

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

<div class="wrenio-media-offload-admin">

    <div class="notice notice-error" style="border-left-color: #d63638;">
        <p><strong><?php echo esc_html__( 'Destructive operation — deletes R2 objects permanently.', 'wrenio-media-offload' ); ?></strong></p>
        <p>
            <?php echo esc_html__( 'Scan your bucket for objects that are not referenced by any WordPress attachment. The list of orphans is stored; nothing is deleted until you explicitly click Delete. Always preview the list before deleting, and take a backup of critical R2 objects first.', 'wrenio-media-offload' ); ?>
        </p>
    </div>

    <div class="card">
        <h2 class="title"><?php echo esc_html__( 'What this does', 'wrenio-media-offload' ); ?></h2>
        <p>
            <?php echo esc_html__( 'An orphan is an R2 object whose key does not appear in any attachment\'s `_r2_key` or `_r2_key_{size}` post meta. Orphans accumulate when thumbnails are regenerated (old sizes no longer match current sizes), when attachments are deleted but R2 objects remain, or when a filename changes.', 'wrenio-media-offload' ); ?>
        </p>
        <p><strong><?php echo esc_html__( 'Workflow:', 'wrenio-media-offload' ); ?></strong></p>
        <ol style="margin-left: 20px;">
            <li><?php echo esc_html__( 'Scan: walks the entire R2 bucket and compares against referenced keys. Read-only.', 'wrenio-media-offload' ); ?></li>
            <li><?php echo esc_html__( 'Preview: inspect the list of orphans. Spot-check sample URLs.', 'wrenio-media-offload' ); ?></li>
            <li><?php echo esc_html__( 'Delete in batches: removes orphans from R2. Failed deletions are kept in the list for retry.', 'wrenio-media-offload' ); ?></li>
        </ol>
        <p>
            <strong><?php echo esc_html__( 'Prerequisites:', 'wrenio-media-offload' ); ?></strong>
            <?php echo esc_html__( 'Run Bulk Sync first to ensure all current thumbnails are uploaded to R2. Running orphan cleanup before sync risks deleting legitimate objects that are temporarily unreferenced during migration.', 'wrenio-media-offload' ); ?>
        </p>
    </div>

    <div class="card" style="margin-top: 20px;">
        <h2 class="title"><?php echo esc_html__( 'Scan Status', 'wrenio-media-offload' ); ?></h2>

        <?php if ( ! $is_configured ) : ?>
            <div class="notice notice-error inline" style="margin: 16px 0; padding: 10px;">
                <p>
                    <?php
                    printf(
                        /* translators: %s: settings page URL */
                        esc_html__( 'R2 is not configured. %s', 'wrenio-media-offload' ),
                        '<a href="' . esc_url( admin_url( 'admin.php?page=wrenio-media-offload' ) ) . '">' . esc_html__( 'Configure R2 credentials', 'wrenio-media-offload' ) . '</a>'
                    );
                    ?>
                </p>
            </div>
        <?php else : ?>
            <table class="widefat striped" style="margin-bottom: 20px;">
                <tbody>
                    <tr>
                        <td><strong><?php echo esc_html__( 'Referenced keys (from WordPress)', 'wrenio-media-offload' ); ?></strong></td>
                        <td><span id="orphan-referenced-count"><?php echo esc_html( number_format_i18n( (int) ( $scan_status['referenced_count'] ?? 0 ) ) ); ?></span></td>
                    </tr>
                    <tr>
                        <td><strong><?php echo esc_html__( 'R2 objects scanned', 'wrenio-media-offload' ); ?></strong></td>
                        <td><span id="orphan-scanned-count"><?php echo esc_html( number_format_i18n( (int) ( $scan_status['objects_scanned'] ?? 0 ) ) ); ?></span></td>
                    </tr>
                    <tr>
                        <td><strong><?php echo esc_html__( 'Orphans found', 'wrenio-media-offload' ); ?></strong></td>
                        <td><span id="orphan-count"><?php echo esc_html( number_format_i18n( (int) ( $scan_status['orphans_found'] ?? 0 ) ) ); ?></span></td>
                    </tr>
                    <tr>
                        <td><strong><?php echo esc_html__( 'Scan state', 'wrenio-media-offload' ); ?></strong></td>
                        <td>
                            <span id="orphan-scan-state">
                            <?php
                            if ( ! empty( $scan_status['in_progress'] ) ) {
                                echo esc_html__( 'In progress (resumable)', 'wrenio-media-offload' );
                            } elseif ( ! empty( $scan_status['completed'] ) ) {
                                echo esc_html__( 'Complete', 'wrenio-media-offload' );
                            } else {
                                echo esc_html__( 'Not started', 'wrenio-media-offload' );
                            }
                            ?>
                            </span>
                        </td>
                    </tr>
                </tbody>
            </table>

            <h3><?php echo esc_html__( 'Scan Options', 'wrenio-media-offload' ); ?></h3>
            <table class="form-table">
                <tr>
                    <th scope="row">
                        <label for="orphan_prefix"><?php echo esc_html__( 'Prefix (optional)', 'wrenio-media-offload' ); ?></label>
                    </th>
                    <td>
                        <input type="text" id="orphan_prefix" value="" placeholder="e.g. 2022/01/" style="width: 300px;" />
                        <p class="description"><?php echo esc_html__( 'Limit scan to objects starting with this prefix. Leave empty to scan the whole bucket.', 'wrenio-media-offload' ); ?></p>
                    </td>
                </tr>
            </table>

            <p>
                <button type="button" id="orphan-start-scan" class="button button-primary">
                    <?php echo esc_html__( 'Start Scan', 'wrenio-media-offload' ); ?>
                </button>
                <button type="button" id="orphan-stop-scan" class="button" style="display: none;">
                    <?php echo esc_html__( 'Stop', 'wrenio-media-offload' ); ?>
                </button>
                <button type="button" id="orphan-reset" class="button">
                    <?php echo esc_html__( 'Reset', 'wrenio-media-offload' ); ?>
                </button>
                <span id="orphan-scan-status" style="margin-left: 12px;"></span>
            </p>

            <div id="orphan-scan-progress" style="display: none; margin-top: 16px;">
                <div style="background: #f0f0f1; border-radius: 4px; height: 20px; overflow: hidden;">
                    <div id="orphan-scan-progress-bar" style="background: #2271b1; height: 100%; width: 0; transition: width 0.3s;"></div>
                </div>
                <p id="orphan-scan-progress-status" style="margin-top: 6px; font-size: 13px;"></p>
            </div>
        <?php endif; ?>
    </div>

    <?php if ( $is_configured ) : ?>
    <div class="card" style="margin-top: 20px;">
        <h2 class="title"><?php echo esc_html__( 'Preview Orphans', 'wrenio-media-offload' ); ?></h2>
        <p>
            <button type="button" id="orphan-preview" class="button"><?php echo esc_html__( 'Load first 20', 'wrenio-media-offload' ); ?></button>
            <button type="button" id="orphan-preview-next" class="button" style="display: none;"><?php echo esc_html__( 'Next 20', 'wrenio-media-offload' ); ?></button>
        </p>
        <div id="orphan-preview-container" style="display: none;">
            <table class="widefat striped">
                <thead>
                    <tr>
                        <th><?php echo esc_html__( 'R2 Key', 'wrenio-media-offload' ); ?></th>
                        <th><?php echo esc_html__( 'URL (spot-check)', 'wrenio-media-offload' ); ?></th>
                    </tr>
                </thead>
                <tbody id="orphan-preview-rows"></tbody>
            </table>
        </div>
    </div>

    <?php if ( wrenio_studio_can_use_pro() ) : ?>
    <div class="card" style="margin-top: 20px;">
        <h2 class="title"><?php echo esc_html__( 'Delete Orphans', 'wrenio-media-offload' ); ?></h2>

        <div class="notice notice-error inline" style="margin: 0 0 16px 0; padding: 10px;">
            <p><strong><?php echo esc_html__( 'Permanent deletion', 'wrenio-media-offload' ); ?></strong></p>
            <p><?php echo esc_html__( 'Deletion cannot be undone. Preview the orphan list above and spot-check a few URLs before proceeding. Once the scan result looks correct, delete in small batches and verify the site remains working.', 'wrenio-media-offload' ); ?></p>
        </div>

        <table class="form-table">
            <tr>
                <th scope="row">
                    <label for="orphan_delete_batch_size"><?php echo esc_html__( 'Batch size', 'wrenio-media-offload' ); ?></label>
                </th>
                <td>
                    <input type="number" id="orphan_delete_batch_size" value="25" min="1" max="100" />
                    <p class="description"><?php echo esc_html__( 'Orphans deleted per AJAX call (1–100). Higher values finish faster but put more load on R2.', 'wrenio-media-offload' ); ?></p>
                </td>
            </tr>
        </table>

        <p>
            <button type="button" id="orphan-start-delete" class="button button-primary"
                <?php disabled( empty( $scan_status['completed'] ) || (int) ( $scan_status['orphans_found'] ?? 0 ) === 0 ); ?>>
                <?php echo esc_html__( 'Delete All Orphans', 'wrenio-media-offload' ); ?>
            </button>
            <button type="button" id="orphan-stop-delete" class="button" style="display: none;">
                <?php echo esc_html__( 'Stop', 'wrenio-media-offload' ); ?>
            </button>
            <span id="orphan-delete-status" style="margin-left: 12px;"></span>
        </p>

        <div id="orphan-delete-progress" style="display: none; margin-top: 16px;">
            <div style="background: #f0f0f1; border-radius: 4px; height: 20px; overflow: hidden;">
                <div id="orphan-delete-progress-bar" style="background: #d63638; height: 100%; width: 0; transition: width 0.3s;"></div>
            </div>
            <p id="orphan-delete-progress-status" style="margin-top: 6px; font-size: 13px;"></p>
        </div>
    </div>
    <?php endif; ?>

    <div class="card" style="margin-top: 20px;">
        <h2 class="title"><?php echo esc_html__( 'Activity Log', 'wrenio-media-offload' ); ?></h2>
        <div id="orphan-log" style="background: #f6f7f7; border: 1px solid #c3c4c7; border-radius: 4px; padding: 10px; max-height: 400px; overflow-y: auto; font-family: monospace; font-size: 12px;"></div>
    </div>
    <?php endif; ?>
</div>
