<?php
/**
 * NFe Invoices Page Template
 *
 * @var string $page_title
 * @var array $initial_invoices
 * @var array $initial_pagination
 */

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

<div class="wrap">
    <h1><?php echo esc_html($page_title); ?></h1>
    <div id="nfe-error-notice" class="notice notice-error" style="display:none;">
        <p id="nfe-error-notice-message"></p>
    </div>

    <!-- Filters -->
    <div class="nfe-filters" style="margin-bottom: 20px; padding: 15px; background: #f8f9fa; border: 1px solid #ddd;">
        <form id="nfe-filters-form" method="get">
            <input type="hidden" name="page" value="nfe-invoices">

            <div style="display: flex; gap: 15px; align-items: end; flex-wrap: wrap;">
                <!-- Year Filter -->
                <div>
                    <label for="filter_year" style="display: block; margin-bottom: 5px; font-weight: 600;">
                        <?php esc_html_e('Year', 'woocommerce-cloudxm-nfe'); ?>
                    </label>
                    <select id="filter_year" name="year" style="min-width: 120px;">
                        <option value=""><?php esc_html_e('All Years', 'woocommerce-cloudxm-nfe'); ?></option>
                        <?php
                        $current_year = date('Y');
                        for ($year = $current_year; $year >= $current_year - 5; $year--) {
                            $selected = (isset($_GET['year']) && $_GET['year'] == $year) ? 'selected' : '';
                            echo "<option value=\"{$year}\" {$selected}>{$year}</option>";
                        }
                        ?>
                    </select>
                </div>

                <!-- Status Filter -->
                <div>
                    <label for="filter_status" style="display: block; margin-bottom: 5px; font-weight: 600;">
                        <?php esc_html_e('Status', 'woocommerce-cloudxm-nfe'); ?>
                    </label>
                    <select id="filter_status" name="status" style="min-width: 140px;">
                        <option value=""><?php esc_html_e('All Statuses', 'woocommerce-cloudxm-nfe'); ?></option>
                        <option value="issued"><?php esc_html_e('Issued', 'woocommerce-cloudxm-nfe'); ?></option>
                        <option value="cancelled"><?php esc_html_e('Cancelled', 'woocommerce-cloudxm-nfe'); ?></option>
                        <option value="failed"><?php esc_html_e('Failed', 'woocommerce-cloudxm-nfe'); ?></option>
                        <option value="processing"><?php esc_html_e('Processing', 'woocommerce-cloudxm-nfe'); ?></option>
                        <option value="pending"><?php esc_html_e('Pending', 'woocommerce-cloudxm-nfe'); ?></option>
                        <option value="scheduled"><?php esc_html_e('Scheduled', 'woocommerce-cloudxm-nfe'); ?></option>
                        <option value="async_pending"><?php esc_html_e('Async Pending', 'woocommerce-cloudxm-nfe'); ?></option>
                    </select>
                </div>

                <!-- Date Range Filter -->
                <div>
                    <label style="display: block; margin-bottom: 5px; font-weight: 600;">
                        <?php esc_html_e('Date Range', 'woocommerce-cloudxm-nfe'); ?>
                    </label>
                    <div style="display: flex; gap: 5px; align-items: center;">
                        <input type="date" id="filter_start_date" name="start_date"
                               value="<?php echo isset($_GET['start_date']) ? esc_attr($_GET['start_date']) : ''; ?>"
                               style="min-width: 140px;">
                        <span><?php esc_html_e('to', 'woocommerce-cloudxm-nfe'); ?></span>
                        <input type="date" id="filter_end_date" name="end_date"
                               value="<?php echo isset($_GET['end_date']) ? esc_attr($_GET['end_date']) : ''; ?>"
                               style="min-width: 140px;">
                    </div>
                </div>

                <!-- Apply Filters Button -->
                <div>
                    <button type="button" id="apply-filters" class="button button-primary">
                        <?php esc_html_e('Apply Filters', 'woocommerce-cloudxm-nfe'); ?>
                    </button>
                    <button type="button" id="clear-filters" class="button">
                        <?php esc_html_e('Clear', 'woocommerce-cloudxm-nfe'); ?>
                    </button>
                </div>
            </div>
        </form>
    </div>

    <!-- Bulk Actions -->
    <div class="nfe-bulk-actions" style="margin-bottom: 15px;">
        <select id="bulk-action-selector" style="margin-right: 10px;">
            <option value=""><?php esc_html_e('Bulk Actions', 'woocommerce-cloudxm-nfe'); ?></option>
            <option value="download_xml"><?php esc_html_e('Download XML', 'woocommerce-cloudxm-nfe'); ?></option>
            <option value="download_pdf"><?php esc_html_e('Download PDF', 'woocommerce-cloudxm-nfe'); ?></option>
            <option value="download_csv"><?php esc_html_e('Download CSV', 'woocommerce-cloudxm-nfe'); ?></option>
        </select>
        <button type="button" id="apply-bulk-action" class="button">
            <?php esc_html_e('Apply', 'woocommerce-cloudxm-nfe'); ?>
        </button>
        <span id="bulk-progress" style="margin-left: 15px; display: none;">
            <?php esc_html_e('Processing...', 'woocommerce-cloudxm-nfe'); ?>
        </span>
    </div>

    <!-- Invoices Table -->
    <div class="nfe-invoices-container">
        <table id="nfe-invoices-table" class="wp-list-table widefat fixed striped">
            <thead>
                <tr>
                    <th class="check-column">
                        <input type="checkbox" id="select-all-invoices">
                    </th>
                    <th><?php esc_html_e('NFe Number', 'woocommerce-cloudxm-nfe'); ?></th>
                    <th><?php esc_html_e('Order ID', 'woocommerce-cloudxm-nfe'); ?></th>
                    <th><?php esc_html_e('Date', 'woocommerce-cloudxm-nfe'); ?></th>
                    <th><?php esc_html_e('Value', 'woocommerce-cloudxm-nfe'); ?></th>
                    <th><?php esc_html_e('Status', 'woocommerce-cloudxm-nfe'); ?></th>
                    <th><?php esc_html_e('Env', 'woocommerce-cloudxm-nfe'); ?></th>
                    <th><?php esc_html_e('Files', 'woocommerce-cloudxm-nfe'); ?></th>
                    <th><?php esc_html_e('Details', 'woocommerce-cloudxm-nfe'); ?></th>
                    <th><?php esc_html_e('Actions', 'woocommerce-cloudxm-nfe'); ?></th>
                </tr>
            </thead>
            <tbody id="nfe-invoices-body">
                <?php if (!empty($initial_invoices)): ?>
                    <?php foreach ($initial_invoices as $invoice): ?>
                        <tr>
                            <th class="check-column"><input type="checkbox" value="<?php echo esc_attr((string) $invoice['id']); ?>"></th>
                            <td><?php echo esc_html((string) ($invoice['display_number'] ?? '-')); ?></td>
                            <td><a href="<?php echo esc_url($invoice['order_url']); ?>" target="_blank">#<?php echo esc_html((string) $invoice['order_id']); ?></a></td>
                            <td><?php echo esc_html($invoice['emission_date_formatted']); ?></td>
                            <td><?php echo esc_html((string) $invoice['value']); ?></td>
                            <td><span class="nfe-status-badge nfe-status-<?php echo esc_attr($invoice['status'] ?? ''); ?>"><?php echo esc_html($invoice['status_label'] ?? ucfirst($invoice['status'] ?? '-')); ?></span></td>
                            <td><span class="nfe-env-badge nfe-env-<?php echo esc_attr($invoice['environment'] ?? ''); ?>"><?php echo esc_html($invoice['environment_label'] ?? \CloudXM\NFe\Config\Configuration::getEnvironmentLabel($invoice['environment'] ?? '')); ?></span></td>
                            <td>
                                <?php if (!empty($invoice['xml_exists'])): ?>
                                    <span class="dashicons dashicons-media-document" title="XML Available"></span>
                                <?php endif; ?>
                                <?php if (!empty($invoice['pdf_exists'])): ?>
                                    <span class="dashicons dashicons-pdf" title="PDF Available"></span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <button type="button" class="button button-small nfe-details-btn" data-id="<?php echo esc_attr((string) $invoice['id']); ?>" title="<?php esc_attr_e('View Details', 'woocommerce-cloudxm-nfe'); ?>">
                                    <span class="dashicons dashicons-visibility"></span>
                                </button>
                            </td>
                            <td>
                                <div style="display: flex; gap: 5px; flex-wrap: wrap;">
                                    <?php
                                    $allowedActions = isset($invoice['allowed_actions']) ? (array) $invoice['allowed_actions'] : [];
                                    ?>
                                    <?php if (in_array('issue', $allowedActions, true)): ?>
                                        <button type="button" class="button button-small button-primary nfe-action-issue" data-id="<?php echo esc_attr((string) $invoice['id']); ?>">
                                            <?php esc_html_e('Issue Now', 'woocommerce-cloudxm-nfe'); ?>
                                        </button>
                                    <?php endif; ?>
                                    <?php if (in_array('reschedule', $allowedActions, true)): ?>
                                        <button type="button" class="button button-small nfe-action-reschedule" data-id="<?php echo esc_attr((string) $invoice['id']); ?>">
                                            <?php esc_html_e('Reschedule', 'woocommerce-cloudxm-nfe'); ?>
                                        </button>
                                    <?php endif; ?>
                                    <?php if (in_array('cancel', $allowedActions, true)): ?>
                                        <button type="button" class="button button-small nfe-action-cancel" data-id="<?php echo esc_attr((string) $invoice['id']); ?>">
                                            <?php esc_html_e('Cancel Schedule', 'woocommerce-cloudxm-nfe'); ?>
                                        </button>
                                    <?php endif; ?>
                                    <?php if (!empty($invoice['xml_exists'])): ?>
                                        <button type="button" class="button button-small nfe-download-btn" data-id="<?php echo esc_attr((string) $invoice['id']); ?>" data-type="xml"><?php esc_html_e('XML', 'woocommerce-cloudxm-nfe'); ?></button>
                                    <?php endif; ?>
                                    <?php if (!empty($invoice['pdf_exists'])): ?>
                                        <button type="button" class="button button-small nfe-download-btn" data-id="<?php echo esc_attr((string) $invoice['id']); ?>" data-type="pdf"><?php esc_html_e('PDF', 'woocommerce-cloudxm-nfe'); ?></button>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>

        <!-- Pagination -->
        <div id="nfe-pagination" class="tablenav bottom" style="margin-top: 15px;">
            <div class="tablenav-pages">
                <?php if (!empty($initial_pagination) && (int) ($initial_pagination['total_pages'] ?? 0) > 1): ?>
                    <span class="displaying-num">
                        <?php echo esc_html((string) ($initial_pagination['total_items'] ?? 0)); ?>
                        <?php esc_html_e('items', 'woocommerce-cloudxm-nfe'); ?>
                    </span>
                <?php endif; ?>
            </div>
            <br class="clear">
        </div>

        <!-- Loading indicator -->
        <div id="nfe-loading" style="text-align: center; padding: 20px; display: none;">
            <span class="spinner is-active" style="float: none;"></span>
            <?php esc_html_e('Loading invoices...', 'woocommerce-cloudxm-nfe'); ?>
        </div>

        <!-- Empty state -->
        <div id="nfe-empty" style="text-align: center; padding: 40px; display: none;">
            <p><?php esc_html_e('No NFe invoices found matching the current filters.', 'woocommerce-cloudxm-nfe'); ?></p>
        </div>
    </div>

    <!-- NFe Details Modal -->
    <div id="nfe-details-modal" class="nfe-modal" style="display: none;">
        <div class="nfe-modal-overlay"></div>
        <div class="nfe-modal-content">
            <div class="nfe-modal-header">
                <h2><?php esc_html_e('NFe Invoice Details', 'woocommerce-cloudxm-nfe'); ?></h2>
                <button type="button" class="nfe-modal-close">&times;</button>
            </div>
            <div class="nfe-modal-body" id="nfe-details-content">
                <div class="nfe-details-loading" style="text-align: center; padding: 40px;">
                    <span class="spinner is-active" style="float: none;"></span>
                    <p><?php esc_html_e('Loading invoice details...', 'woocommerce-cloudxm-nfe'); ?></p>
                </div>
            </div>
        </div>
    </div>

    <!-- Reschedule Modal -->
    <div id="nfe-reschedule-modal" class="nfe-modal" style="display:none;">
        <div class="nfe-modal-overlay"></div>
        <div class="nfe-modal-content" style="max-width:500px;">
            <div class="nfe-modal-header">
                <h2><?php esc_html_e('Reschedule Invoice', 'woocommerce-cloudxm-nfe'); ?></h2>
                <button type="button" class="nfe-modal-close">&times;</button>
            </div>
            <div class="nfe-modal-body">
                <form id="nfe-reschedule-form">
                    <input type="hidden" id="reschedule-invoice-id" name="invoice_id">

                    <div class="form-group" style="margin-bottom:15px;">
                        <label for="reschedule-datetime" style="display:block; margin-bottom:5px; font-weight:600;">
                            <?php esc_html_e('Scheduled Date/Time', 'woocommerce-cloudxm-nfe'); ?>
                        </label>
                        <input type="datetime-local" id="reschedule-datetime" name="scheduled_at" required
                               style="width:100%; padding:8px;">
                    </div>

                    <div class="form-group" style="margin-bottom:15px;">
                        <label for="reschedule-timezone" style="display:block; margin-bottom:5px; font-weight:600;">
                            <?php esc_html_e('Timezone', 'woocommerce-cloudxm-nfe'); ?>
                        </label>
                        <select id="reschedule-timezone" name="timezone" required
                                style="width:100%; padding:8px;">
                            <option value="America/Sao_Paulo">America/Sao_Paulo (UTC-3)</option>
                        </select>
                    </div>

                    <div class="form-group" style="margin-bottom:15px;">
                        <label for="reschedule-reason" style="display:block; margin-bottom:5px; font-weight:600;">
                            <?php esc_html_e('Reason (optional)', 'woocommerce-cloudxm-nfe'); ?>
                        </label>
                        <textarea id="reschedule-reason" name="scheduling_reason" rows="3"
                                  style="width:100%; padding:8px;"></textarea>
                    </div>

                    <div class="form-buttons" style="display:flex; justify-content:flex-end; gap:10px; margin-top:20px;">
                        <button type="button" class="button modal-close">
                            <?php esc_html_e('Cancel', 'woocommerce-cloudxm-nfe'); ?>
                        </button>
                        <button type="submit" class="button button-primary">
                            <?php esc_html_e('Reschedule', 'woocommerce-cloudxm-nfe'); ?>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Cancel Modal -->
    <div id="nfe-cancel-modal" class="nfe-modal" style="display:none;">
        <div class="nfe-modal-overlay"></div>
        <div class="nfe-modal-content" style="max-width:500px;">
            <div class="nfe-modal-header">
                <h2><?php esc_html_e('Cancel Invoice', 'woocommerce-cloudxm-nfe'); ?></h2>
                <button type="button" class="nfe-modal-close">&times;</button>
            </div>
            <div class="nfe-modal-body">
                <form id="nfe-cancel-form">
                    <input type="hidden" id="cancel-invoice-id" name="invoice_id">

                    <div class="form-group" style="margin-bottom:15px;">
                        <label for="cancel-reason" style="display:block; margin-bottom:5px; font-weight:600;">
                            <?php esc_html_e('Cancellation Reason', 'woocommerce-cloudxm-nfe'); ?>
                        </label>
                        <textarea id="cancel-reason" name="reason" rows="4" required
                                  style="width:100%; padding:8px;"></textarea>
                    </div>

                    <div class="form-buttons" style="display:flex; justify-content:flex-end; gap:10px; margin-top:20px;">
                        <button type="button" class="button modal-close">
                            <?php esc_html_e('Cancel', 'woocommerce-cloudxm-nfe'); ?>
                        </button>
                        <button type="submit" class="button button-secondary">
                            <?php esc_html_e('Confirm Cancel', 'woocommerce-cloudxm-nfe'); ?>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
