<?php
// ============================================================
// CertificateDocxGenerator
// Calls the Node.js generate_certificate.js script to produce
// a .docx matching the official GSA certificate template.
// Falls back to HTML if Node.js is unavailable.
// ============================================================
class CertificateDocxGenerator {

    /**
     * Generate a .docx certificate file.
     *
     * @param array  $request     Full request row (joined company/equipment/lab)
     * @param array  $formData    Lab-specific form row
     * @param array  $officer     ['officer_name'=>..., 'signature'=>...]
     * @param string $certNum     e.g. GSA/THL/2025/0001
     * @param string $issueDate   Y-m-d
     * @param string $labType     'humidity' | 'balance' | 'generic'
     * @param array  $results     Pre-processed results array (for certificate table)
     * @return string|null        Path to the generated .docx file, or null on failure
     */
    public static function generate(
        array $request,
        array $formData,
        array $officer,
        string $certNum,
        string $issueDate,
        string $labType,
        array $results = []
    ): ?string {
        // Build data payload for Node.js
        $sigPath = '';
        if (!empty($officer['signature'])) {
            $p = SIGNATURE_PATH . $officer['signature'];
            if (file_exists($p)) $sigPath = $p;
        }

        $slug     = str_replace(['/', ' '], '-', $certNum);
        $outPath  = CERT_PATH . 'CERT_' . $slug . '.docx';
        $dataFile = sys_get_temp_dir() . '/metlab_cert_' . $slug . '_' . time() . '.json';

        $payload = [
            'lab_type'       => $labType,
            'cert_number'    => $certNum,
            'issue_date'     => $issueDate,
            'issue_ym'       => date('Y-m', strtotime($issueDate)),
            'lab_code'       => $request['lab_code']   ?? '',
            'lab_name'       => $request['lab_name']   ?? '',
            // From request (equipment/company tables — no duplication)
            'equipment_name' => $request['equipment_name'] ?? '',
            'manufacturer'   => $request['manufacturer']   ?? '',
            'model'          => $request['model']           ?? '',
            'serial_number'  => $request['serial_number']  ?? '',
            'company_name'   => $request['company_name']   ?? '',
            'request_number' => $request['request_number'] ?? '',
            // Form data (lab-specific fields only)
            'form'           => $formData,
            // Pre-computed results
            'results'        => $results,
            // Officer
            'officer_name'   => $officer['officer_name'] ?? '',
            'signature_path' => $sigPath,
            // Output
            'output_path'    => $outPath,
        ];

        file_put_contents($dataFile, json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));

        // Find Node.js
        $node = trim((string)shell_exec('which node nodejs 2>/dev/null | head -1'));
        if (!$node) $node = 'node';

        $scriptPath = BASE_PATH . '/generate_certificate.js';
        $cmd        = escapeshellcmd($node) . ' ' . escapeshellarg($scriptPath) . ' ' . escapeshellarg($dataFile) . ' 2>&1';
        $output     = shell_exec($cmd);

        @unlink($dataFile);

        if ($output && str_starts_with(trim($output), 'OK:')) {
            return $outPath;
        }

        // Log failure for debugging
        error_log("CertificateDocxGenerator failed: $output");
        return null;
    }
}
