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

/**
 * PDF generator utilities.
 *
 * IMPORTANT (WP.org review compliance):
 * - DO NOT enqueue PDF CSS/JS in wp-admin globally.
 * - PDF styling must be used ONLY inside the generated PDF HTML (Dompdf context),
 *   not applied to the WordPress administration dashboard.
 *
 * Therefore:
 * - We load assets/pdf.css from disk and inject into the PDF HTML for Dompdf.
 * - We do NOT call wp_enqueue_style() / admin_enqueue_scripts() here.
 */

/**
 * Ensure the upload directory exists and includes basic protection files.
 */
function cf7_pdf_gen_ensure_upload_protection(string $base_dir): void
{
  if ($base_dir === '') return;

  if (!is_dir($base_dir)) {
    if (!wp_mkdir_p($base_dir)) return;
  }

  $index = rtrim($base_dir, "/\\") . '/index.php';
  if (!file_exists($index)) {
    // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_file_put_contents -- Writing small protection files in uploads folder.
    file_put_contents($index, "<?php\nhttp_response_code(404);\nexit;\n");
  }

  $ht = rtrim($base_dir, "/\\") . '/.htaccess';
  if (!file_exists($ht)) {
    $rules  = "Options -Indexes\n\n";
    $rules .= "<IfModule mod_headers.c>\n";
    $rules .= "  Header set X-Robots-Tag \"noindex, nofollow, nosnippet, noarchive\"\n";
    $rules .= "</IfModule>\n";
    // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_read_file_put_contents -- Writing small protection files in uploads folder.
    file_put_contents($ht, $rules);
  }
}

/**
 * Create a human-friendly label from field keys.
 * Example: "your-name" => "Your Name"
 */
function cf7_pdf_gen_pretty_label(string $key): string
{
  $key = trim($key);
  if ($key === '') return '';
  $key = preg_replace('/[_\-]+/', ' ', $key);
  $key = preg_replace('/\s+/', ' ', $key);
  $key = strtolower($key);
  $key = ucwords($key);
  return $key;
}

/**
 * Convert URLs and emails into clickable links.
 * Input must be HTML-escaped already.
 */
function cf7_pdf_gen_linkify_escaped(string $escaped): string
{
  if ($escaped === '') return '';

  // URLs
  $escaped = preg_replace_callback(
    '~(https?://[^\s<]+)~i',
    function ($m) {
      $display = (string) $m[1];

      $raw = html_entity_decode($display, ENT_QUOTES, 'UTF-8');
      $raw = trim($raw);

      // Trim trailing punctuation that often sticks to URLs in text
      $trail = '';
      while ($raw !== '' && preg_match('/[)\].,!?:;]+$/', $raw)) {
        $trail = substr($raw, -1) . $trail;
        $raw = substr($raw, 0, -1);
      }

      $raw_href = esc_url_raw($raw);
      if ($raw_href === '') {
        return $display;
      }

      $href = esc_url($raw_href);
      $safe_display = esc_html($raw);
      $safe_trail   = esc_html($trail);

      return '<a href="' . $href . '">' . $safe_display . '</a>' . $safe_trail;
    },
    $escaped
  );

  // Emails
  $escaped = preg_replace_callback(
    '/([A-Z0-9._%+\-]+@[A-Z0-9.\-]+\.[A-Z]{2,})/i',
    function ($m) {
      $display = (string) $m[1];

      $raw = html_entity_decode($display, ENT_QUOTES, 'UTF-8');
      $raw = trim($raw);

      $email = sanitize_email($raw);
      if ($email === '') {
        return $display;
      }

      return '<a href="mailto:' . esc_attr($email) . '">' . esc_html($email) . '</a>';
    },
    $escaped
  );

  return $escaped;
}

/**
 * Read the local PDF CSS file (assets/pdf.css) for injecting into Dompdf HTML.
 * Remote loading is disabled, so CSS must be local.
 */
function cf7_pdf_gen_get_pdf_css(): string
{
  $css_path = realpath(dirname(__DIR__) . '/assets/pdf.css');
  if (!$css_path || !is_file($css_path)) {
    return '';
  }

  $css_raw = @file_get_contents($css_path);
  return is_string($css_raw) ? $css_raw : '';
}

/**
 * Generate a PDF from the current Contact Form 7 submission.
 * Returns an absolute file path on success, or an empty string on failure.
 */
function cf7_pdf_gen_create_pdf($contact_form)
{
  // Respect admin toggle if available.
  if (function_exists('cf7_pdf_gen_is_enabled') && !cf7_pdf_gen_is_enabled()) {
    return '';
  }

  static $dompdf_loaded = false;
  if (!$dompdf_loaded) {
    $autoload = CF7_PDF_GEN_PATH . 'vendor/autoload.php';
    if (!file_exists($autoload)) {
      return '';
    }
    require_once $autoload;
    $dompdf_loaded = true;
  }

  if (!class_exists('WPCF7_Submission')) {
    return '';
  }

  $submission = WPCF7_Submission::get_instance();
  if (!$submission) {
    return '';
  }

  $posted_data = $submission->get_posted_data();
  if (!is_array($posted_data) || empty($posted_data)) {
    return '';
  }

  // Remove internal CF7 keys
  foreach (array_keys($posted_data) as $k) {
    if (strncmp((string)$k, '_wpcf7', 5) === 0) {
      unset($posted_data[$k]);
    }
  }

  $form_title = (is_object($contact_form) && method_exists($contact_form, 'title'))
    ? (string) $contact_form->title()
    : 'Contact Form 7';

  $form_id = (is_object($contact_form) && method_exists($contact_form, 'id'))
    ? (string) $contact_form->id()
    : '';

  $dt = current_time('Y-m-d H:i:s');

  $html = cf7_pdf_gen_build_pdf_html($form_title, $form_id, $dt, $posted_data);

  $upload = wp_upload_dir();
  if (empty($upload['basedir'])) {
    return '';
  }

  $base_dir = trailingslashit($upload['basedir']) . CF7_PDF_GEN_SLUG;
  cf7_pdf_gen_ensure_upload_protection($base_dir);

  $form_dir = $base_dir;
  if ($form_id !== '') {
    $safe_form_id = preg_replace('/[^a-zA-Z0-9_-]/', '', $form_id);
    $form_dir = trailingslashit($base_dir) . 'form-' . $safe_form_id;
    cf7_pdf_gen_ensure_upload_protection($form_dir);
  }

  if (!is_dir($form_dir) || !wp_is_writable($form_dir)) {
    return '';
  }

  $safe_id_part = ($form_id !== '') ? preg_replace('/[^a-zA-Z0-9_-]/', '', $form_id) : 'unknown';
  $filename = 'cf7-form-' . $safe_id_part . '-' . gmdate('Ymd-His') . '.pdf';

  if (function_exists('wp_unique_filename')) {
    $filename = wp_unique_filename($form_dir, $filename);
  }

  $filepath = trailingslashit($form_dir) . $filename;

  if (!class_exists('\Dompdf\Dompdf')) {
    return '';
  }

  $brand_name = defined('CF7_PDF_GEN_BRAND_NAME') ? (string) CF7_PDF_GEN_BRAND_NAME : 'EPE Formetto - PDF Attachments for Contact Forms';

  try {
    $dompdf = new \Dompdf\Dompdf();

    if (method_exists($dompdf, 'set_option')) {
      $dompdf->set_option('isRemoteEnabled', false);
      $dompdf->set_option('isHtml5ParserEnabled', true);
      $dompdf->set_option('defaultFont', 'DejaVu Sans');
    }

    $dompdf->loadHtml($html);
    $dompdf->setPaper('A4', 'portrait');
    $dompdf->render();

    // Set document metadata title (helps in PDF viewers)
    if (method_exists($dompdf, 'add_info')) {
      $dompdf->add_info('Title', $brand_name . ' - Submission');
    } elseif (method_exists($dompdf, 'addInfo')) {
      $dompdf->addInfo('Title', $brand_name . ' - Submission');
    }

    $bytes = @file_put_contents($filepath, $dompdf->output());
    if ($bytes === false || (int)$bytes <= 0) {
      return '';
    }
  } catch (\Throwable $e) {
    return '';
  }

  if (!file_exists($filepath)) {
    return '';
  }

  return $filepath;
}

/**
 * Build the HTML that will be rendered into the PDF.
 */
function cf7_pdf_gen_build_pdf_html($form_title, $form_id, $dt, $posted_data)
{
  $css = cf7_pdf_gen_get_pdf_css();

  $plugin_name = defined('CF7_PDF_GEN_BRAND_NAME') ? (string) CF7_PDF_GEN_BRAND_NAME : 'EPE Formetto - PDF Attachments for Contact Forms';

  $safe_plugin = esc_html($plugin_name);
  $safe_form   = esc_html((string)$form_title);
  $safe_dt     = esc_html((string)$dt);
  $safe_id     = esc_html((string)$form_id);

  $watermark_text = function_exists('cf7_pdf_gen_watermark_text')
    ? (string) cf7_pdf_gen_watermark_text()
    : ('Generated with ' . $plugin_name);

  $wm = esc_html($watermark_text);

  $watermark_html = '
    <div class="wm">
      <div>' . $wm . '</div>
      <div>' . $wm . '</div>
      <div>' . $wm . '</div>
      <div>' . $wm . '</div>
    </div>
  ';

  $rows = '';
  foreach ($posted_data as $key => $value) {

    if (is_array($value)) $value = implode(', ', $value);

    $raw_val = trim((string)$value);

    $label = cf7_pdf_gen_pretty_label((string)$key);
    $label = $label !== '' ? $label : (string)$key;

    $escaped = esc_html($raw_val);
    $escaped = cf7_pdf_gen_linkify_escaped($escaped);
    $escaped = nl2br($escaped);

    $rows .= '
      <tr>
        <td class="k">' . esc_html($label) . '</td>
        <td class="v">' . $escaped . '</td>
      </tr>
    ';
  }

  if ($rows === '') {
    $rows = '
      <tr>
        <td class="k">Info</td>
        <td class="v">No fields were provided.</td>
      </tr>
    ';
  }

  $mode_pill = '<span class="pill free">PDF</span>';

  $footer_html = '
    <div class="footer">
      <div>' . esc_html('Generated by ' . $plugin_name) . '</div>
      <div>' . $safe_plugin . '</div>
    </div>
  ';

  // Inject CSS into Dompdf HTML only (no wp-admin enqueues)
  $style_open  = '<' . 'style>';
  $style_close = '<' . '/style>';

  $html = '
  <!doctype html>
  <html>
  <head>
    <meta charset="utf-8">
    <title>' . $safe_plugin . ' - Submission</title>
    ' . $style_open . "\n" . $css . "\n" . $style_close . '
  </head>
  <body>
    ' . $watermark_html . '

    <div class="header">
      <div class="header-inner">
        <div class="topline">
          <div class="brand">' . $safe_plugin . '</div>
          <div>' . $mode_pill . '</div>
        </div>

        <h1>Contact Form Submission</h1>

        <div class="meta">
          <div><strong>Form:</strong> ' . $safe_form . '</div>
          <div><strong>Form ID:</strong> ' . ($safe_id !== '' ? $safe_id : '-') . '</div>
          <div><strong>Date:</strong> ' . $safe_dt . '</div>
        </div>
      </div>
    </div>

    <table>
      ' . $rows . '
    </table>

    ' . $footer_html . '
  </body>
  </html>';

  return $html;
}
