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

//asana-form-builder/includes/helpers.php

/**
 * Minimal Word-compatible HTML wrapper for .doc export.
 */
function afb_wrap_html_as_word_document($body_html, $title = 'Submitted Copy') {
    $css = 'body{font-family:Arial,Helvetica,sans-serif;font-size:12pt}
            p{margin:.5em 0} ul,ol{margin:.5em 1.25em} li{margin:.25em 0}
            a{color:#1155cc} strong{font-weight:bold}';
    return "<!DOCTYPE html>
<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' xmlns='http://www.w3.org/TR/REC-html40'>
<head><meta charset='utf-8'><title>" . esc_html($title) . "</title><style>{$css}</style></head>
<body>{$body_html}</body></html>";
}

/**
 * Create temp .doc from HTML and attach to Asana.
 * NOTE: relies on afb_normalize_html_for_asana() from triagesummary.php if available.
 */
function afb_attach_word_doc_from_html($task_gid, $html, $filename_base, $pat) {
    if (!trim($html)) return;

    // Normalize/sanitize via triagesummary helpers (loaded by init.php)
    if (function_exists('afb_normalize_html_for_asana')) {
        $safe_html = afb_normalize_html_for_asana($html);
    } else {
        // Defensive fallback: allow basic post HTML
        $safe_html = wp_kses_post($html);
    }

    $doc_html = afb_wrap_html_as_word_document($safe_html, $filename_base);

    $uploads = wp_upload_dir();
    $tmp_dir = trailingslashit($uploads['basedir']) . 'asana-temp';
    if (!file_exists($tmp_dir)) {
        wp_mkdir_p($tmp_dir);
    }

    $filename = sanitize_file_name($filename_base) . '.doc';
    $tmp_path = trailingslashit($tmp_dir) . $filename;
    file_put_contents($tmp_path, $doc_html);

    $ch = curl_init("https://app.asana.com/api/1.0/tasks/{$task_gid}/attachments");
    curl_setopt_array($ch, [
        CURLOPT_HTTPHEADER     => ["Authorization: Bearer {$pat}"],
        CURLOPT_POST           => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POSTFIELDS     => ['file' => new CURLFile($tmp_path, 'application/msword', $filename)],
    ]);
    $resp = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    @unlink($tmp_path);

    if (!in_array($code, [200, 201], true)) {
        afb_log("⚠️ Attach .doc failed ({$code}) {$filename}", 'asana_update_notes');
    } else {
        afb_log("✅ Attached {$filename} to {$task_gid}", 'asana_update_notes');
    }
}

/**
 * Prevent duplicate .doc attachments within a single request.
 */
function afb_attach_word_doc_from_html_once($task_gid, $html, $filename_base, $pat) {
    static $attached = [];
    $key = $task_gid . '|' . sanitize_file_name($filename_base) . '.doc';
    if (isset($attached[$key])) {
        afb_log("ℹ️ Skipped duplicate attach for {$key}", 'asana_update_notes');
        return;
    }
    $attached[$key] = true;
    afb_attach_word_doc_from_html($task_gid, $html, $filename_base, $pat);
}

/**
 * Generate a unique Job Number (SCB) per task.
 * Format: {PREFIX}-{YYYYMMDDHHMMSS}-{BASE36}
 * PREFIX comes from WP option 'afb_prefix_map' keyed by project_id, else 'SCB'.
 */
function afb_generate_job_number($project_id) {
    $prefix_map = get_option('afb_prefix_map', []); // mirror of JS afb_ajax.prefix_map
    $prefix = isset($prefix_map[$project_id]) && $prefix_map[$project_id] ? $prefix_map[$project_id] : 'SCB';

    // Timestamp in WP timezone
    $ts = current_time('timestamp');
    $stamp = date('YmdHis', $ts);

    // Add 4-char base36 entropy for uniqueness
    $rand = substr(strtoupper(base_convert(random_int(2176782336, 78364164095), 10, 36)), 0, 4);

    return sprintf('%s-%s-%s', $prefix, $stamp, $rand);
}

/**
 * Lightweight logger that defaults to /wp-content/afb-debug.log
 *
 * afb_log($message, $channel = 'afb-debug.log')
 * - Writes to WP_CONTENT_DIR/$channel (defaults to afb-debug.log).
 * - If $channel doesn't end with ".log", we still write to "afb-debug.log".
 * - Falls back to PHP error_log if file write fails.
 */
if (!function_exists('afb_log')) {
    function afb_log($message, $channel = 'afb-debug.log') {
        // Normalize message
        if (is_array($message) || is_object($message)) {
            $message = print_r($message, true);
        }

        // Timestamp like your examples
        $line = '[' . date('Y-m-d H:i:s') . '] ' . $message . PHP_EOL;

        // Build target path in wp-content
        $base = defined('WP_CONTENT_DIR')
            ? rtrim(WP_CONTENT_DIR, '/\\')
            : (defined('ABSPATH') ? rtrim(ABSPATH, '/\\') . '/wp-content' : __DIR__);

        // Only filenames ending with ".log" are respected; otherwise default
        $filename = (is_string($channel) && substr($channel, -4) === '.log')
            ? $channel
            : 'afb-debug.log';

        $path = $base . DIRECTORY_SEPARATOR . $filename;

        // Ensure directory exists
        $dir = dirname($path);
        if (!is_dir($dir)) {
            @mkdir($dir, 0755, true);
        }

        // Try to append to the file; if it fails, log to PHP error_log
        if (@error_log($line, 3, $path) === false) {
            @error_log($line);
        }
    }
}
