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

/**
 * Admin settings and utilities for EPE Formetto - PDF Attachments for Contact Forms.
 *
 * WP.org compliance:
 * - Do not alter wp-admin globally
 * - Load CSS ONLY on this plugin settings page
 * - Keep WP default admin styling everywhere else
 */

define('CF7_PDF_GEN_OPT_ALLOWED_FORM_ID', 'cf7_pdf_gen_allowed_form_id');

/**
 * Enqueue admin CSS ONLY on our settings page.
 *
 * IMPORTANT:
 * - We do NOT rely on $hook.
 * - We do NOT use get_current_screen() (can be null depending on load order).
 * - We hard-guard via $pagenow + $_GET['page'] (read-only) and ONLY then enqueue.
 */
add_action('admin_enqueue_scripts', 'cf7_pdf_gen_admin_assets');
function cf7_pdf_gen_admin_assets(): void
{
  if (!is_admin()) return;

  global $pagenow;
  if (!isset($pagenow) || $pagenow !== 'options-general.php') return;

  // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only check for current admin page.
  $page = isset($_GET['page']) ? sanitize_key(wp_unslash($_GET['page'])) : '';
  if ($page !== CF7_PDF_GEN_SLUG) return;

  wp_enqueue_style(
    'cf7-pdf-gen-admin',
    CF7_PDF_GEN_URL . 'assets/admin.css',
    array(),
    defined('CF7_PDF_GEN_VERSION') ? (string) CF7_PDF_GEN_VERSION : '1.0.0'
  );
}

add_action('admin_menu', 'cf7_pdf_gen_admin_menu');
function cf7_pdf_gen_admin_menu()
{
  $page_title = defined('CF7_PDF_GEN_BRAND_NAME') ? (string) CF7_PDF_GEN_BRAND_NAME : 'EPE Formetto';
  $menu_title = defined('CF7_PDF_GEN_BRAND_NAME') ? (string) CF7_PDF_GEN_BRAND_NAME : 'EPE Formetto';

  add_options_page(
    $page_title,
    $menu_title,
    'manage_options',
    defined('CF7_PDF_GEN_SLUG') ? (string) CF7_PDF_GEN_SLUG : 'epe-formetto-pdf-attachments',
    'cf7_pdf_gen_settings_page'
  );
}

add_action('admin_init', 'cf7_pdf_gen_register_settings');
function cf7_pdf_gen_register_settings()
{
  register_setting(
    'cf7_pdf_gen_settings',
    CF7_PDF_GEN_OPT_ALLOWED_FORM_ID,
    array(
      'type' => 'string',
      'sanitize_callback' => 'sanitize_text_field',
      'default' => '',
    )
  );

  // Ensure a "Settings saved." notice WITHOUT reading $_GET['settings-updated'] (avoids nonce warnings).
  add_settings_error(
    'cf7_pdf_gen_settings',
    'cf7_pdf_gen_settings_saved',
    __('Settings saved.', 'epe-formetto-pdf-attachments-for-contact-forms'),
    'updated'
  );
}

function cf7_pdf_gen_settings_page()
{
  if (!current_user_can('manage_options')) return;

  $brand_name = defined('CF7_PDF_GEN_BRAND_NAME') ? (string) CF7_PDF_GEN_BRAND_NAME : 'EPE Formetto';
  $allowed_form_id = (string) get_option(CF7_PDF_GEN_OPT_ALLOWED_FORM_ID, '');

  // CF7 availability.
  $cf7_ok = (defined('WPCF7_VERSION') && class_exists('WPCF7_ContactForm'));
  $forms = array();
  if ($cf7_ok) {
    $forms = WPCF7_ContactForm::find();
  }

  /**
   * Secure "PDF deleted" notice:
   * - We ONLY show it if both query args exist AND nonce validates.
   * - This removes Plugin Check NonceVerification warnings.
   */
  $show_deleted_notice = false;
  if (isset($_GET['cf7_pdf_gen_notice'], $_GET['cf7_pdf_gen_notice_nonce'])) {
    $notice = sanitize_text_field(wp_unslash($_GET['cf7_pdf_gen_notice']));
    $nonce  = sanitize_text_field(wp_unslash($_GET['cf7_pdf_gen_notice_nonce']));

    if ($notice === 'deleted' && wp_verify_nonce($nonce, 'cf7_pdf_gen_notice_deleted')) {
      $show_deleted_notice = true;
    }
  }

  ?>
  <div class="wrap cf7-pdf-admin">
    <h1><?php echo esc_html($brand_name); ?></h1>

    <?php
    // WP-native settings notices (no $_GET reads, no nonce warnings)
    settings_errors('cf7_pdf_gen_settings');
    ?>

    <?php if ($show_deleted_notice) : ?>
      <div class="notice notice-success is-dismissible">
        <p><strong><?php echo esc_html__('PDF deleted.', 'epe-formetto-pdf-attachments-for-contact-forms'); ?></strong></p>
      </div>
    <?php endif; ?>

    <?php if (!$cf7_ok) : ?>
      <div class="notice notice-error">
        <p><strong><?php echo esc_html__('Contact Form 7 is not active.', 'epe-formetto-pdf-attachments-for-contact-forms'); ?></strong></p>
        <p><?php echo esc_html__('Activate Contact Form 7 and create at least one form to start generating PDFs.', 'epe-formetto-pdf-attachments-for-contact-forms'); ?></p>
      </div>
    <?php endif; ?>

    <div id="poststuff">
      <div id="post-body" class="metabox-holder columns-1">
        <div id="post-body-content">

          <div class="postbox cf7-pdf-card">
            <h2 class="hndle"><span><?php echo esc_html__('Overview', 'epe-formetto-pdf-attachments-for-contact-forms'); ?></span></h2>
            <div class="inside">
              <p>
                <strong><?php echo esc_html__('Status:', 'epe-formetto-pdf-attachments-for-contact-forms'); ?></strong>
                <?php echo ($allowed_form_id !== '') ? esc_html__('Configured', 'epe-formetto-pdf-attachments-for-contact-forms') : esc_html__('Not configured', 'epe-formetto-pdf-attachments-for-contact-forms'); ?>
              </p>

              <p><?php echo esc_html__('How it works:', 'epe-formetto-pdf-attachments-for-contact-forms'); ?></p>
              <ul style="list-style: disc; padding-left: 20px; margin-left: 0;">
                <li><?php echo esc_html__('When the selected Contact Form 7 form is submitted, a PDF is generated.', 'epe-formetto-pdf-attachments-for-contact-forms'); ?></li>
                <li><?php echo esc_html__('The PDF is attached to the Contact Form 7 email.', 'epe-formetto-pdf-attachments-for-contact-forms'); ?></li>
                <li><?php echo esc_html__('Administrators can open and delete recent PDFs from this page.', 'epe-formetto-pdf-attachments-for-contact-forms'); ?></li>
              </ul>
            </div>
          </div>

          <form method="post" action="options.php">
            <?php settings_fields('cf7_pdf_gen_settings'); ?>

            <div class="postbox cf7-pdf-card">
              <h2 class="hndle"><span><?php echo esc_html__('Form selection', 'epe-formetto-pdf-attachments-for-contact-forms'); ?></span></h2>
              <div class="inside">
                <p><?php echo esc_html__('Choose which Contact Form 7 form should generate PDFs.', 'epe-formetto-pdf-attachments-for-contact-forms'); ?></p>

                <table class="form-table" role="presentation">
                  <tr>
                    <th scope="row">
                      <label for="cf7_pdf_gen_allowed_form_id"><?php echo esc_html__('Contact Form 7 form', 'epe-formetto-pdf-attachments-for-contact-forms'); ?></label>
                    </th>
                    <td>
                      <?php if (!$cf7_ok || empty($forms)) : ?>
                        <p><?php echo esc_html__('Contact Form 7 is not active or no forms were found.', 'epe-formetto-pdf-attachments-for-contact-forms'); ?></p>
                      <?php else : ?>
                        <select id="cf7_pdf_gen_allowed_form_id" name="<?php echo esc_attr(CF7_PDF_GEN_OPT_ALLOWED_FORM_ID); ?>">
                          <option value=""><?php echo esc_html__('— Select a form —', 'epe-formetto-pdf-attachments-for-contact-forms'); ?></option>
                          <?php foreach ($forms as $f) :
                            $id = (string) $f->id();
                            $title = (string) $f->title();
                          ?>
                            <option value="<?php echo esc_attr($id); ?>" <?php selected($allowed_form_id, $id); ?>>
                              <?php echo esc_html($title . ' (ID: ' . $id . ')'); ?>
                            </option>
                          <?php endforeach; ?>
                        </select>
                        <p class="description"><?php echo esc_html__('Only the selected form will generate PDFs.', 'epe-formetto-pdf-attachments-for-contact-forms'); ?></p>
                      <?php endif; ?>
                    </td>
                  </tr>
                </table>

                <?php submit_button(__('Save selection', 'epe-formetto-pdf-attachments-for-contact-forms')); ?>
              </div>
            </div>
          </form>

          <div class="postbox cf7-pdf-card">
            <h2 class="hndle"><span><?php echo esc_html__('Recent PDFs', 'epe-formetto-pdf-attachments-for-contact-forms'); ?></span></h2>
            <div class="inside">
              <p><?php echo esc_html__('These links are available to administrators and use protected URLs.', 'epe-formetto-pdf-attachments-for-contact-forms'); ?></p>
              <?php echo wp_kses_post(cf7_pdf_gen_render_recent_pdfs()); ?>
            </div>
          </div>

        </div>
      </div>
    </div>

  </div>
  <?php
}

/**
 * Determines whether a form is eligible for PDF generation based on the saved setting.
 */
function cf7_pdf_gen_is_form_allowed($form_id)
{
  $form_id = (string) $form_id;
  if ($form_id === '') return false;

  $allowed = (string) get_option(CF7_PDF_GEN_OPT_ALLOWED_FORM_ID, '');
  return ($allowed !== '' && $allowed === $form_id);
}

/**
 * Renders a list of recent generated PDFs with protected open/delete actions.
 */
function cf7_pdf_gen_render_recent_pdfs()
{
  $upload = wp_upload_dir();
  $base_dir = trailingslashit($upload['basedir']) . CF7_PDF_GEN_SLUG;

  if (!file_exists($base_dir)) {
    return '<p>' . esc_html__('No PDFs yet. Submit the selected form to generate the first PDF.', 'epe-formetto-pdf-attachments-for-contact-forms') . '</p>';
  }

  $files = array();

  $it = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($base_dir, FilesystemIterator::SKIP_DOTS)
  );

  foreach ($it as $fileinfo) {
    if (!$fileinfo->isFile()) continue;
    $name = $fileinfo->getFilename();
    if (strtolower(substr($name, -4)) !== '.pdf') continue;

    $files[] = array(
      'path' => $fileinfo->getPathname(),
      'mtime' => $fileinfo->getMTime(),
    );
  }

  if (empty($files)) {
    return '<p>' . esc_html__('No PDFs yet. Submit the selected form to generate the first PDF.', 'epe-formetto-pdf-attachments-for-contact-forms') . '</p>';
  }

  usort($files, function ($a, $b) {
    return $b['mtime'] <=> $a['mtime'];
  });

  $files = array_slice($files, 0, 20);

  $html  = '<table class="widefat striped">';
  $html .= '<thead><tr><th>' . esc_html__('File', 'epe-formetto-pdf-attachments-for-contact-forms') . '</th><th>' . esc_html__('Created', 'epe-formetto-pdf-attachments-for-contact-forms') . '</th><th>' . esc_html__('Action', 'epe-formetto-pdf-attachments-for-contact-forms') . '</th></tr></thead><tbody>';

  foreach ($files as $f) {
    $path = $f['path'];

    $rel = str_replace($base_dir, '', $path);
    $rel = ltrim(str_replace('\\', '/', $rel), '/');

    if (!function_exists('cf7_pdf_gen_admin_pdf_url')) {
      $html .= '<tr><td colspan="3">' . esc_html__('Secure download handler is not available.', 'epe-formetto-pdf-attachments-for-contact-forms') . '</td></tr>';
      break;
    }

    $secure_url = cf7_pdf_gen_admin_pdf_url($rel);

    $delete_url = '';
    if (function_exists('cf7_pdf_gen_admin_pdf_delete_url')) {
      $delete_url = cf7_pdf_gen_admin_pdf_delete_url($rel);
    }

    $html .= '<tr>';
    $html .= '<td><code>' . esc_html($rel) . '</code></td>';
    $html .= '<td>' . esc_html(wp_date('Y-m-d H:i:s', (int) $f['mtime'])) . '</td>';

    $html .= '<td>';
    $html .= '<a class="button button-primary" href="' . esc_url($secure_url) . '" target="_blank" rel="noopener">' . esc_html__('Open PDF', 'epe-formetto-pdf-attachments-for-contact-forms') . '</a> ';

    if ($delete_url !== '') {
      $html .= '<a class="button button-secondary" href="' . esc_url($delete_url) . '" onclick="return confirm(\'' . esc_js(__('Delete this PDF? This cannot be undone.', 'epe-formetto-pdf-attachments-for-contact-forms')) . '\');">' . esc_html__('Delete', 'epe-formetto-pdf-attachments-for-contact-forms') . '</a>';
    } else {
      $html .= '<span>' . esc_html__('Delete unavailable', 'epe-formetto-pdf-attachments-for-contact-forms') . '</span>';
    }

    $html .= '</td>';
    $html .= '</tr>';
  }

  $html .= '</tbody></table>';

  return $html;
}
