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

use BLR\Backline\Core\Access;
use BLR\Backline\Core\Views;
use BLR\Backline\Modules\Outreach\Module as OutreachModule;

$base = rtrim((string) ($ctx['base_url'] ?? ''), '/') . '/';
$id = (int) ($ctx['id'] ?? 0);
$campaign = $id ? get_post($id) : null;

if (!$campaign || $campaign->post_type !== 'blr_outreach') {
    echo '<div class="container-fluid p-0"><div class="alert alert-danger">' . esc_html__('Campaign not found.', 'blr-backline') . '</div></div>';
    return;
}

if (!Access::can_edit_post($id, 'blr_outreach')) {
    echo '<div class="container-fluid p-0"><div class="alert alert-danger">' . esc_html__('You do not have permission to view or update this campaign.', 'blr-backline') . '</div></div>';
    return;
}

$subject = (string) get_post_meta($id, 'blr_outreach_subject', true);
$from_name = (string) get_post_meta($id, 'blr_outreach_from_name', true);
$from_email = (string) get_post_meta($id, 'blr_outreach_from_email', true);
$reply_to = (string) get_post_meta($id, 'blr_outreach_reply_to', true);
$last_sent = (string) get_post_meta($id, 'blr_outreach_last_sent_at', true);
$stats = OutreachModule::get_campaign_stats($id);
$status = OutreachModule::resolved_campaign_status($id, $stats);
$delivery_status = OutreachModule::derive_campaign_delivery_status($id, $stats);
$workflow_status = (string) get_post_meta($id, 'blr_outreach_workflow_status', true);
$pending_count = (int) ($stats['queued'] ?? 0) + (int) ($stats['sending'] ?? 0);
$queue_diagnostics = OutreachModule::queue_diagnostics($id);

$page_num = Views::current_page_from_query_arg('pg');
$logs = new WP_Query([
    'post_type' => 'blr_outreach_log',
    'post_status' => ['publish', 'draft'],
    'posts_per_page' => 50,
    'paged' => $page_num,
    'post_parent' => $id,
    'orderby' => 'date',
    'order' => 'DESC',
]);
$logs_summary = Views::pagination_summary_data($logs, 'pg');

$edit_url = $base . 'outreach/edit/' . $id . '/';
$delete_url = $base . 'outreach/delete/' . $id . '/';
?>
<div class="container-fluid p-0">
  <div class="d-flex align-items-center justify-content-between mb-3">
    <div>
      <h1 class="h3 mb-1"><?php echo esc_html(get_the_title($campaign)); ?></h1>
      <div class="text-muted"><?php echo esc_html($subject ?: __('No subject', 'blr-backline')); ?></div>
    </div>
    <div class="d-flex gap-2">
      <a class="btn btn-outline-secondary" href="<?php echo esc_url($base . 'outreach/'); ?>"><?php echo esc_html__('Back', 'blr-backline'); ?></a>
      <?php if ($pending_count > 0 || $delivery_status === 'Failed') : ?>
        <form method="post" class="d-inline">
          <?php wp_nonce_field('blr_ba_resume_outreach_' . $id); ?>
          <button type="submit" class="btn btn-outline-primary" name="resume_queue" value="1"><?php echo esc_html__('Resume Queue', 'blr-backline'); ?></button>
        </form>
      <?php endif; ?>
      <?php if ($pending_count > 0) : ?>
        <form method="post" class="d-inline">
          <?php wp_nonce_field('blr_ba_run_outreach_queue_' . $id); ?>
          <button type="submit" class="btn btn-outline-secondary" name="run_queue_now" value="1"><?php echo esc_html__('Run Queue Now', 'blr-backline'); ?></button>
        </form>
      <?php endif; ?>
      <a class="btn btn-primary" href="<?php echo esc_url($edit_url); ?>"><?php echo esc_html__('Edit', 'blr-backline'); ?></a>
      <?php /* translators: %s: campaign title. */ ?>
      <form method="post" action="<?php echo esc_url($delete_url); ?>" class="blr-ba-delete-form d-inline" data-item-label="<?php echo esc_attr(sprintf(__('campaign “%s”', 'blr-backline'), get_the_title($campaign))); ?>">
        <?php wp_nonce_field('blr_ba_delete_blr_outreach_' . $id); ?>
        <button type="submit" class="btn btn-outline-danger"><?php echo esc_html__('Delete', 'blr-backline'); ?></button>
      </form>
    </div>
  </div>

<?php
// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only notice counts from the URL.
$queued_notice = isset($_GET['queued']) ? absint((string) wp_unslash($_GET['queued'])) : 0;
$updated_notice = isset($_GET['updated']) ? absint((string) wp_unslash($_GET['updated'])) : 0;
$queued_count = isset($_GET['queued_count']) ? absint((string) wp_unslash($_GET['queued_count'])) : 0;
$invalid_count = isset($_GET['invalid_count']) ? absint((string) wp_unslash($_GET['invalid_count'])) : 0;
$skipped_count = isset($_GET['skipped_count']) ? absint((string) wp_unslash($_GET['skipped_count'])) : 0;
$suppressed_count = isset($_GET['suppressed_count']) ? absint((string) wp_unslash($_GET['suppressed_count'])) : 0;
$limited_count = isset($_GET['limited_count']) ? absint((string) wp_unslash($_GET['limited_count'])) : 0;
$resumed_notice = isset($_GET['resumed']) ? absint((string) wp_unslash($_GET['resumed'])) : 0;
$queue_run_notice = isset($_GET['queue_run']) ? absint((string) wp_unslash($_GET['queue_run'])) : 0;
$processed_count = isset($_GET['processed_count']) ? absint((string) wp_unslash($_GET['processed_count'])) : 0;
$sent_count = isset($_GET['sent_count']) ? absint((string) wp_unslash($_GET['sent_count'])) : 0;
$failed_count = isset($_GET['failed_count']) ? absint((string) wp_unslash($_GET['failed_count'])) : 0;
$remaining_count = isset($_GET['remaining_count']) ? absint((string) wp_unslash($_GET['remaining_count'])) : 0;
$queue_locked_notice = isset($_GET['queue_locked']) ? absint((string) wp_unslash($_GET['queue_locked'])) : 0;
$log_update_error = isset($_GET['log_update_error']) ? absint((string) wp_unslash($_GET['log_update_error'])) : 0;
// phpcs:enable WordPress.Security.NonceVerification.Recommended
?>

  <?php if ($queued_notice) : ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
      <?php if ($resumed_notice) : ?>
        <?php
          printf(
              /* translators: %d: pending recipient count. */
              esc_html__('Queue processing was kicked again. %d recipient(s) are still pending.', 'blr-backline'),
              (int) $queued_count
          );
        ?>
      <?php else : ?>
        <?php
        /* translators: 1: queued recipient count, 2: skipped recipient count, 3: invalid recipient count, 4: suppressed recipient count, 5: recipient limit count. */
        printf(esc_html__('Campaign queued. %1$d recipient(s) are queued for delivery, %2$d already-sent recipient(s) were skipped, %3$d invalid recipient(s) were ignored, %4$d unsubscribed recipient(s) were suppressed, and %5$d recipient(s) exceeded the campaign limit.', 'blr-backline'), (int) $queued_count, (int) $skipped_count, (int) $invalid_count, (int) $suppressed_count, (int) $limited_count);
        ?>
      <?php endif; ?>
      <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="<?php echo esc_attr__('Close', 'blr-backline'); ?>"></button>
    </div>
  <?php endif; ?>
  <?php if ($updated_notice) : ?><div class="alert alert-success alert-dismissible fade show" role="alert"><?php echo esc_html__('Updated.', 'blr-backline'); ?><button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="<?php echo esc_attr__('Close', 'blr-backline'); ?>"></button></div><?php endif; ?>

  <?php if ($log_update_error) : ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
      <?php echo esc_html__('The recipient log could not be updated because the linked contact is no longer valid or you do not have permission to edit it.', 'blr-backline'); ?>
      <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="<?php echo esc_attr__('Close', 'blr-backline'); ?>"></button>
    </div>
  <?php endif; ?>

  <?php if ($queue_run_notice) : ?>
    <div class="alert <?php echo $queue_locked_notice ? 'alert-warning' : 'alert-info'; ?> alert-dismissible fade show" role="alert">
      <?php if ($queue_locked_notice) : ?>
        <?php echo esc_html__('The queue is already running in another request. No extra batch was started.', 'blr-backline'); ?>
      <?php else : ?>
        <?php
        printf(
            /* translators: 1: processed recipients, 2: sent recipients, 3: failed recipients, 4: remaining recipients. */
            esc_html__('Queue run finished. Processed %1$d recipient(s), sent %2$d, failed %3$d, and %4$d remain pending.', 'blr-backline'),
            (int) $processed_count,
            (int) $sent_count,
            (int) $failed_count,
            (int) $remaining_count
        );
        ?>
      <?php endif; ?>
      <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="<?php echo esc_attr__('Close', 'blr-backline'); ?>"></button>
    </div>
  <?php endif; ?>

  <div class="row g-3 mb-3">
    <div class="col-12 col-md-6 col-xl-3"><div class="card"><div class="card-body"><div class="text-muted small"><?php echo esc_html__('Status', 'blr-backline'); ?></div><div class="mt-1"><?php echo wp_kses_post(OutreachModule::badge($status)); ?></div></div></div></div>
    <div class="col-12 col-md-6 col-xl-3"><div class="card"><div class="card-body"><div class="text-muted small"><?php echo esc_html__('Pending', 'blr-backline'); ?></div><div class="mt-1"><?php echo (int) $pending_count; ?></div></div></div></div>
    <div class="col-12 col-md-6 col-xl-3"><div class="card"><div class="card-body"><div class="text-muted small"><?php echo esc_html__('Sent', 'blr-backline'); ?></div><div class="mt-1"><?php echo (int) $stats['sent']; ?></div></div></div></div>
    <div class="col-12 col-md-6 col-xl-3"><div class="card"><div class="card-body"><div class="text-muted small"><?php echo esc_html__('Failed', 'blr-backline'); ?></div><div class="mt-1"><?php echo (int) $stats['failed']; ?></div></div></div></div>
  </div>

  <div class="row g-3">
    <div class="col-12 col-xl-4">
      <div class="card">
        <div class="card-header"><h5 class="card-title mb-0"><?php echo esc_html__('Campaign Details', 'blr-backline'); ?></h5></div>
        <div class="card-body">
          <div class="mb-3"><div class="text-muted small"><?php echo esc_html__('From', 'blr-backline'); ?></div><div><?php echo esc_html(trim($from_name . ' <' . $from_email . '>')); ?></div></div>
          <div class="mb-3"><div class="text-muted small"><?php echo esc_html__('Reply-To', 'blr-backline'); ?></div><div><?php echo esc_html($reply_to ?: __('—', 'blr-backline')); ?></div></div>
          <div class="mb-3"><div class="text-muted small"><?php echo esc_html__('Delivery Status', 'blr-backline'); ?></div><div><?php echo wp_kses_post(OutreachModule::badge($delivery_status)); ?></div></div>
          <div class="mb-3"><div class="text-muted small"><?php echo esc_html__('Workflow Status', 'blr-backline'); ?></div><div><?php echo wp_kses_post(OutreachModule::badge($workflow_status !== '' ? $workflow_status : $delivery_status)); ?></div></div>
          <div class="mb-3"><div class="text-muted small"><?php echo esc_html__('Last Sent', 'blr-backline'); ?></div><div><?php echo esc_html($last_sent ?: __('—', 'blr-backline')); ?></div></div>

          <form method="post" class="border-top pt-3">
            <?php wp_nonce_field('blr_ba_update_campaign_status_' . $id); ?>
            <div class="mb-2"><label class="form-label"><?php echo esc_html__('Workflow Status', 'blr-backline'); ?></label></div>
            <div class="d-flex gap-2">
              <select class="form-select" name="campaign_status">
                <option value="" <?php selected($workflow_status, ''); ?>><?php echo esc_html__('Auto', 'blr-backline'); ?></option>
                <?php foreach (OutreachModule::campaign_editable_statuses() as $opt) : ?>
                  <option value="<?php echo esc_attr($opt); ?>" <?php selected($workflow_status, $opt); ?>><?php echo esc_html(OutreachModule::status_label($opt)); ?></option>
                <?php endforeach; ?>
              </select>
              <button class="btn btn-outline-secondary" type="submit" name="update_campaign_status" value="1"><?php echo esc_html__('Save', 'blr-backline'); ?></button>
            </div>
            <div class="form-text"><?php echo esc_html__('Delivery status is tracked automatically from the recipient log. Workflow status is your manual follow-up label for the campaign.', 'blr-backline'); ?></div>
          </form>
        </div>
      </div>

      <div class="card mt-3">
        <div class="card-header"><h5 class="card-title mb-0"><?php echo esc_html__('Queue Diagnostics', 'blr-backline'); ?></h5></div>
        <div class="card-body">
          <div class="mb-3"><div class="text-muted small"><?php echo esc_html__('Pending breakdown', 'blr-backline'); ?></div><div><?php
            /* translators: 1: queued recipient count, 2: currently sending recipient count, 3: failed recipient count. */
            printf(esc_html__('%1$d queued / %2$d sending / %3$d failed', 'blr-backline'), (int) ($queue_diagnostics['queued'] ?? 0), (int) ($queue_diagnostics['sending'] ?? 0), (int) ($queue_diagnostics['failed'] ?? 0));
          ?></div></div>
          <div class="mb-3"><div class="text-muted small"><?php echo esc_html__('Queue healthcheck scheduled', 'blr-backline'); ?></div><div><?php echo !empty($queue_diagnostics['cron_ready']) ? esc_html__('Yes', 'blr-backline') : esc_html__('No', 'blr-backline'); ?></div></div>
          <div class="mb-3"><div class="text-muted small"><?php echo esc_html__('WP-Cron disabled', 'blr-backline'); ?></div><div><?php echo !empty($queue_diagnostics['disable_wp_cron']) ? esc_html__('Yes', 'blr-backline') : esc_html__('No', 'blr-backline'); ?></div></div>
          <div class="mb-3"><div class="text-muted small"><?php echo esc_html__('Next healthcheck', 'blr-backline'); ?></div><div><?php echo !empty($queue_diagnostics['next_healthcheck']) ? esc_html(wp_date(get_option('date_format') . ' ' . get_option('time_format'), (int) $queue_diagnostics['next_healthcheck'])) : esc_html__('Not scheduled', 'blr-backline'); ?></div></div>
          <div><div class="text-muted small"><?php echo esc_html__('Campaign lock', 'blr-backline'); ?></div><div><?php echo !empty($queue_diagnostics['campaign_locked']) ? esc_html__('Active', 'blr-backline') : esc_html__('Idle', 'blr-backline'); ?></div></div>
          <?php if (!empty($queue_diagnostics['disable_wp_cron'])) : ?>
            <div class="alert alert-warning mt-3 mb-0"><?php echo esc_html__('WP-Cron is disabled on this site. Use a real cron job or run the queue manually when needed.', 'blr-backline'); ?></div>
          <?php elseif (empty($queue_diagnostics['cron_ready'])) : ?>
            <div class="alert alert-warning mt-3 mb-0"><?php echo esc_html__('The outreach healthcheck is not currently scheduled. Saving or running the queue should recreate it.', 'blr-backline'); ?></div>
          <?php endif; ?>
        </div>
      </div>

      <div class="card mt-3">
        <div class="card-header"><h5 class="card-title mb-0"><?php echo esc_html__('Body', 'blr-backline'); ?></h5></div>
        <div class="card-body">
          <?php if (trim((string) $campaign->post_content) !== '') : ?>
            <div class="small"><?php echo wp_kses_post(wpautop($campaign->post_content)); ?></div>
          <?php else : ?>
            <div class="text-muted"><?php echo esc_html__('No body content.', 'blr-backline'); ?></div>
          <?php endif; ?>
        </div>
      </div>
    </div>

    <div class="col-12 col-xl-8">
      <div class="card">
        <div class="card-header"><h5 class="card-title mb-0"><?php echo esc_html__('Recipient Log', 'blr-backline'); ?></h5></div>
        <div class="card-body p-0">
          <?php if (!$logs->have_posts()) : ?>
            <div class="p-3 text-muted"><?php echo esc_html__('No recipient logs yet.', 'blr-backline'); ?></div>
          <?php else : ?>
            <div class="table-responsive">
              <table class="table table-hover my-0 align-middle">
                <thead>
                  <tr>
                    <th><?php echo esc_html__('Contact', 'blr-backline'); ?></th>
                    <th class="d-none d-lg-table-cell"><?php echo esc_html__('Sent', 'blr-backline'); ?></th>
                    <th><?php echo esc_html__('Status', 'blr-backline'); ?></th>
                    <th class="d-none d-xl-table-cell"><?php echo esc_html__('Error / Notes', 'blr-backline'); ?></th>
                    <th class="text-end"><?php echo esc_html__('Update', 'blr-backline'); ?></th>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach ($logs->posts as $log) :
                    $contact_id = (int) get_post_meta($log->ID, 'blr_outreach_log_contact_id', true);
                    $email = (string) get_post_meta($log->ID, 'blr_outreach_log_email', true);
                    $log_status = (string) get_post_meta($log->ID, 'blr_outreach_log_status', true);
                    $error = (string) get_post_meta($log->ID, 'blr_outreach_log_error', true);
                    $sent_at = (string) get_post_meta($log->ID, 'blr_outreach_log_sent_at', true);
                    $note = (string) get_post_meta($log->ID, 'blr_outreach_log_note', true);
                    $contact_view = $contact_id ? $base . 'contacts/view/' . $contact_id . '/' : '';
                  ?>
                    <tr>
                      <td>
                        <strong><?php echo esc_html(get_the_title($log)); ?></strong>
                        <?php if ($contact_view) : ?><div class="small"><a href="<?php echo esc_url($contact_view); ?>"><?php echo esc_html__('View contact', 'blr-backline'); ?></a></div><?php endif; ?>
                      </td>
                      <td class="d-none d-lg-table-cell"><?php echo esc_html($sent_at ?: __('—', 'blr-backline')); ?><div class="text-muted small"><?php echo esc_html($email); ?></div></td>
                      <td><?php echo wp_kses_post(OutreachModule::badge($log_status ?: 'Draft')); ?></td>
                      <td class="d-none d-xl-table-cell">
                        <?php if ($error) : ?><div class="text-danger small mb-1"><?php echo esc_html($error); ?></div><?php endif; ?>
                        <?php if ($note) : ?><div class="small"><?php echo wp_kses_post(wpautop($note)); ?></div><?php endif; ?>
                        <?php if (!$error && !$note) : ?><span class="text-muted"><?php echo esc_html__('—', 'blr-backline'); ?></span><?php endif; ?>
                      </td>
                      <td class="text-end">
                        <form method="post" class="d-inline-block text-start blr-ba-log-update-form">
                          <?php wp_nonce_field('blr_ba_update_outreach_log_' . (int) $log->ID); ?>
                          <input type="hidden" name="log_id" value="<?php echo (int) $log->ID; ?>">
                          <div class="d-flex gap-2 mb-2">
                            <select class="form-select form-select-sm" name="log_status">
                              <?php foreach (OutreachModule::recipient_statuses() as $opt) : ?>
                                <option value="<?php echo esc_attr($opt); ?>" <?php selected($log_status, $opt); ?>><?php echo esc_html(OutreachModule::status_label($opt)); ?></option>
                              <?php endforeach; ?>
                            </select>
                            <button class="btn btn-sm btn-outline-secondary" type="submit" name="update_log_status" value="1"><?php echo esc_html__('Save', 'blr-backline'); ?></button>
                          </div>
                          <textarea class="form-control form-control-sm" name="log_note" rows="2" placeholder="<?php echo esc_attr__('Manual note', 'blr-backline'); ?>"><?php echo esc_textarea($note); ?></textarea>
                        </form>
                      </td>
                    </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
          <?php endif; ?>
        </div>
      </div>
      <?php if ($logs->max_num_pages > 1) : ?>
        <div class="d-flex flex-column flex-lg-row align-items-lg-center justify-content-between gap-3 mt-3">
          <div class="text-muted small"><?php echo esc_html(Views::render_pagination_summary($logs, 'recipient logs', 'pg')); ?></div>
          <div><?php echo wp_kses_post(Views::render_pagination($logs, $base . 'outreach/view/' . $id . '/')); ?></div>
        </div>
      <?php endif; ?>
    </div>
  </div>
</div>
<?php
$campaign_modified = get_the_modified_date(get_option('date_format') . ' ' . get_option('time_format'), $id);
$campaign_revisions = wp_get_post_revisions($id, ['numberposts' => 1]);
$last_revision = is_array($campaign_revisions) ? reset($campaign_revisions) : false;
$last_editor_id = $last_revision instanceof WP_Post
    ? (int) $last_revision->post_author
    : (int) get_post_field('post_author', $id);
$last_editor_name = get_the_author_meta('display_name', $last_editor_id);
?>
<p class="small text-muted mb-0">
  <?php
  printf(
      /* translators: 1: modified date, 2: last editor display name. */
      esc_html__('Last edited %1$s by %2$s', 'blr-backline'),
      esc_html($campaign_modified),
      esc_html($last_editor_name)
  );
  ?>
</p>
