<?php
defined('BASEPATH') or exit('No direct script access allowed');

/**
 * Word download helpers.
 * Uses MHTML (.doc) so logos are embedded (CID) — Word rejects remote/data-URI images in plain HTML.
 */
class Word_export
{
    public function stream_html($html, $filename, $embedded_images = array())
    {
        if (stripos($filename, '.doc') === false) {
            $filename .= '.doc';
        }

        $CI =& get_instance();
        $CI->load->helper('report');

        // Already a full MHTML document
        if (stripos($html, 'MIME-Version:') === 0) {
            $this->send_headers($filename);
            echo $html;
            exit;
        }

        // Strip outer html wrapper if present — keep inner body for MHTML rebuild
        if (stripos($html, '<html') !== false) {
            if (preg_match('/<body[^>]*>(.*)<\/body>/is', $html, $bm)) {
                $html = $bm[1];
            }
        }

        // Convert any local/remote img URLs (SO/CRV PDF HTML) to CID embeds
        $embedded = report_export_html_embed_local_images($html, $embedded_images);
        $html = $embedded['html'];
        $images = $embedded['images'];

        $html = report_export_build_mhtml($html, $images);

        $this->send_headers($filename);
        echo $html;
        exit;
    }

    protected function send_headers($filename)
    {
        $this->send_download_cookie();

        header('Content-Type: application/msword; charset=UTF-8');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
    }

    protected function send_download_cookie()
    {
        $CI =& get_instance();
        $token = (string) $CI->input->post('download_token');
        if ($token === '') {
            return;
        }
        $token = preg_replace('/[^a-zA-Z0-9_\-]/', '', $token);
        if ($token === '') {
            return;
        }
        setcookie('kohaDownloadToken', $token, time() + 120, '/');
    }

    /**
     * @param string $title
     * @param array  $columns label => key
     * @param array  $rows
     * @param string $filename
     */
    public function stream_table($title, $columns, $rows, $filename)
    {
        $CI =& get_instance();
        $CI->load->helper('report');

        $brand = report_export_brand_header_word();
        $html = $brand['html'];
        $images = $brand['images'];

        $col_count = max(1, count($columns));
        $table_class = 'report-table' . ($col_count >= 10 ? ' cols-many' : '');

        $html .= '<h2 style="text-align:center;margin:8px 0 12px;font-size:14pt;color:#111;">' . htmlspecialchars($title) . '</h2>';
        $html .= '<table class="' . $table_class . '" border="1" cellpadding="3" cellspacing="0" width="100%">';
        $html .= '<thead><tr>';
        foreach ($columns as $label => $key) {
            if (is_int($label)) {
                $label = $key;
            }
            $html .= '<th>' . htmlspecialchars($label) . '</th>';
        }
        $html .= '</tr></thead><tbody>';
        if (!empty($rows)) {
            foreach ($rows as $row) {
                $html .= '<tr>';
                foreach ($columns as $label => $key) {
                    if (is_int($label)) {
                        $label = $key;
                    }
                    $val = (string) report_cell($row, $key);
                    $align = report_export_cell_align($val, is_string($label) ? $label : '');
                    $html .= '<td style="text-align:' . $align . ';">' . htmlspecialchars($val) . '</td>';
                }
                $html .= '</tr>';
            }
        } else {
            $html .= '<tr><td colspan="' . $col_count . '" style="text-align:center;">No records</td></tr>';
        }
        $html .= '</tbody></table>';

        $this->stream_html($html, $filename, $images);
    }
}
