<?php
require_once 'auth.php';
include 'db.php';
requireLogin($conn);

$draft_id = (int) ($_GET['id'] ?? 0);
$format = strtolower(trim((string) ($_GET['format'] ?? 'pdf')));
if ($draft_id <= 0) {
    header('Location: draft_letters.php?error=not_found');
    exit();
}

if ($format !== 'pdf') {
    header('Location: draft_letter_print.php?id=' . $draft_id . '&support_error=export_disabled');
    exit();
}

$role = $_SESSION['role'] ?? 'user';
$user_department = currentUserDepartment($conn);
$current_user_id = (int) ($_SESSION['user_id'] ?? 0);

$stmt = mysqli_prepare($conn, "SELECT ld.*, f.folder_name, f.folder_code,
        d.file_numbering,
        creator.short_name AS created_by_short_name,
        creator.fullname AS created_by_fullname,
        (SELECT COUNT(*) FROM documents d2 WHERE d2.folder_id = ld.folder_id AND d2.deleted_at IS NULL AND d2.id <= ld.document_id) AS computed_file_numbering
    FROM letter_drafts ld
    INNER JOIN folders f ON f.id = ld.folder_id
    LEFT JOIN documents d ON d.id = ld.document_id AND d.deleted_at IS NULL
    LEFT JOIN users creator ON creator.id = ld.created_by
    WHERE ld.id = ? AND ld.deleted_at IS NULL
    LIMIT 1");
mysqli_stmt_bind_param($stmt, "i", $draft_id);
mysqli_stmt_execute($stmt);
$draft = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt));

if (!$draft) {
    header('Location: draft_letters.php?error=not_found');
    exit();
}

$is_creator = (int) ($draft['created_by'] ?? 0) === $current_user_id;
$is_same_department = isSameDepartmentDb($conn, $draft['department'] ?? '', $user_department);
if (!$is_creator && $role !== 'superadmin' && !$is_same_department) {
    header('Location: draft_letters.php?error=unauthorized');
    exit();
}

$approval_recipients = getLetterApprovalRecipients($conn, $draft_id);
if (!canDraftLetterBePrinted($conn, $draft, $approval_recipients, $current_user_id)) {
    header('Location: draft_letter_print.php?id=' . $draft_id . '&support_error=export_not_ready');
    exit();
}

function exportMalayDate($date) {
    $timestamp = strtotime((string) $date);
    if (!$timestamp) return '-';
    $months = [
        1 => 'Januari', 2 => 'Februari', 3 => 'Mac', 4 => 'April',
        5 => 'Mei', 6 => 'Jun', 7 => 'Julai', 8 => 'Ogos',
        9 => 'September', 10 => 'Oktober', 11 => 'November', 12 => 'Disember',
    ];
    return date('d', $timestamp) . ' ' . $months[(int) date('n', $timestamp)] . ' ' . date('Y', $timestamp);
}

function exportSafeBody($html) {
    $allowed = '<p><br><strong><b><em><i><u><ol><ul><li><table><thead><tbody><tr><th><td><blockquote><h3><h4><div><span><img>';
    $html = strip_tags((string) $html, $allowed);
    $html = preg_replace('/\s+on[a-z]+\s*=\s*(".*?"|\'.*?\'|[^\s>]+)/i', '', $html);
    $html = preg_replace('/javascript\s*:/i', '', $html);
    return $html;
}

function exportMemoDisplayValue($value) {
    $items = preg_split('/\r\n|\r|\n/', (string) $value);
    $values = [];
    foreach ($items as $item) {
        $item = trim((string) $item);
        if ($item !== '' && !in_array($item, $values, true)) {
            $values[] = $item;
        }
    }
    if (empty($values)) {
        return '-';
    }
    return implode('<br>', array_map(static function ($position) {
        return htmlspecialchars($position) . '<br>Majlis Agama Islam Negeri Pulau Pinang';
    }, $values));
}

function exportInjectPreparerSignatureIntoGeneratedClosing($html, $draft) {
    $signature_path = trim((string) ($draft['signatory_signature_path'] ?? ''));
    if ($signature_path === '' || !is_file(__DIR__ . '/' . $signature_path)) {
        $signature_path = trim((string) ($draft['department_officer_signature_path'] ?? ''));
        if ($signature_path !== '' && is_file(__DIR__ . '/' . $signature_path)) {
            $department_officer_status = trim((string) ($draft['department_officer_status'] ?? ''));
            if ($department_officer_status !== 'lulus') {
                $signature_path = '';
            }
        } else {
            $signature_path = '';
        }
    }

    if ($signature_path === '') {
        return $html;
    }

    $signature_img = '<img src="' . htmlspecialchars($signature_path, ENT_QUOTES) . '" alt="Tandatangan Digital" style="max-width:150px;max-height:58px;object-fit:contain;">';
    $pattern = '/(<p\b[^>]*data-generated-signature\s*=\s*(["\'])1\2[^>]*>).*?(<\/p>)/is';
    if (preg_match($pattern, (string) $html)) {
        return preg_replace($pattern, '$1' . $signature_img . '$3', (string) $html, 1);
    }

    return $html;
}

function exportReplaceSuratRasmiPrintReferenceLine($html, $reference_display) {
    $reference_display = htmlspecialchars(trim((string) $reference_display), ENT_QUOTES);
    return preg_replace_callback(
        '/(<p\b(?=[^>]*data-surat-rasmi-generated-line=(?:"ref"|\'ref\'))[^>]*>)(.*?)(<\/p>)/is',
        function ($matches) use ($reference_display) {
            return $matches[1] . $reference_display . $matches[3];
        },
        (string) $html
    );
}

function exportFileUri($path) {
    $path = str_replace('\\', '/', (string) $path);
    $parts = array_map('rawurlencode', explode('/', $path));
    $uri = implode('/', $parts);
    $uri = str_replace('%3A', ':', $uri);
    return 'file:///' . ltrim($uri, '/');
}

function findHeadlessBrowserExecutable() {
    $candidates = [
        getenv('ProgramFiles') . '\\Google\\Chrome\\Application\\chrome.exe',
        getenv('ProgramFiles(x86)') . '\\Google\\Chrome\\Application\\chrome.exe',
        getenv('ProgramFiles') . '\\Microsoft\\Edge\\Application\\msedge.exe',
        getenv('ProgramFiles(x86)') . '\\Microsoft\\Edge\\Application\\msedge.exe',
    ];
    foreach ($candidates as $candidate) {
        if ($candidate && is_file($candidate)) {
            return $candidate;
        }
    }
    return '';
}

function exportDeletePath($path, $allowed_root) {
    $path = (string) $path;
    $allowed_root = rtrim(str_replace('\\', '/', (string) $allowed_root), '/') . '/';
    $normalized_path = str_replace('\\', '/', $path);

    if ($path === '' || strpos($normalized_path, $allowed_root) !== 0 || !file_exists($path)) {
        return;
    }

    if (is_file($path) || is_link($path)) {
        @unlink($path);
        return;
    }

    $items = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS),
        RecursiveIteratorIterator::CHILD_FIRST
    );
    foreach ($items as $item) {
        if ($item->isDir()) {
            @rmdir($item->getPathname());
        } else {
            @unlink($item->getPathname());
        }
    }
    @rmdir($path);
}

function exportCleanupHeadlessFiles($tmp_dir, $html_path, $pdf_path, $bridge_path, $profile_dir) {
    exportDeletePath($html_path, $tmp_dir);
    exportDeletePath($pdf_path, $tmp_dir);
    if ($bridge_path !== '') {
        exportDeletePath($bridge_path, __DIR__);
    }
    exportDeletePath($profile_dir, $tmp_dir);
}

function exportRunHeadlessCommand($command, $timeout_seconds, &$output, &$exit_code, &$timed_out) {
    $output = [];
    $exit_code = 1;
    $timed_out = false;

    $descriptors = [
        1 => ['pipe', 'w'],
        2 => ['pipe', 'w'],
    ];
    $process = @proc_open($command, $descriptors, $pipes);
    if (!is_resource($process)) {
        return false;
    }

    foreach ($pipes as $pipe) {
        stream_set_blocking($pipe, false);
    }

    $started_at = microtime(true);
    $status = proc_get_status($process);
    while (!empty($status['running'])) {
        foreach ($pipes as $pipe) {
            $chunk = stream_get_contents($pipe);
            if ($chunk !== false && $chunk !== '') {
                $output[] = trim($chunk);
            }
        }

        if ((microtime(true) - $started_at) >= $timeout_seconds) {
            $timed_out = true;
            $pid = (int) ($status['pid'] ?? 0);
            if ($pid > 0) {
                if (stripos(PHP_OS_FAMILY, 'Windows') !== false && function_exists('exec')) {
                    @exec('taskkill /PID ' . $pid . ' /T /F');
                } else {
                    @proc_terminate($process, 9);
                }
            } else {
                @proc_terminate($process);
            }
            break;
        }

        usleep(100000);
        $status = proc_get_status($process);
    }

    foreach ($pipes as $pipe) {
        $chunk = stream_get_contents($pipe);
        if ($chunk !== false && $chunk !== '') {
            $output[] = trim($chunk);
        }
        fclose($pipe);
    }

    $exit_code = proc_close($process);
    return !$timed_out;
}

function exportBuildPrintPageBridgeUrl($draft_id, &$bridge_path) {
    $bridge_path = '';
    $session_id = session_id();
    if ($session_id === '' || empty($_SERVER['HTTP_HOST'])) {
        return '';
    }

    $token = bin2hex(random_bytes(8));
    $bridge_filename = '.pdf_export_' . (int) $draft_id . '_' . $token . '.php';
    $bridge_path = __DIR__ . DIRECTORY_SEPARATOR . $bridge_filename;
    $bridge_code = "<?php\n"
        . "session_id(" . var_export($session_id, true) . ");\n"
        . "\$_GET['id'] = " . (int) $draft_id . ";\n"
        . "\$_GET['pdf_export'] = '1';\n"
        . "require __DIR__ . '/draft_letter_print.php';\n";

    if (file_put_contents($bridge_path, $bridge_code) === false) {
        $bridge_path = '';
        return '';
    }

    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $script_dir = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '/sistem_fail/export_draft_letter.php'));
    $script_dir = rtrim($script_dir, '/');

    return $scheme . '://' . $_SERVER['HTTP_HOST'] . $script_dir . '/' . rawurlencode($bridge_filename);
}

function streamPdfWithHeadlessBrowser($html, $title, $conn, $current_user_id, $draft, $draft_id) {
    $browser = findHeadlessBrowserExecutable();
    if ($browser === '' || !function_exists('proc_open')) {
        return false;
    }

    $tmp_dir = rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'sistem_fail_pdf';
    if (!is_dir($tmp_dir)) {
        @mkdir($tmp_dir, 0775, true);
    }
    if (!is_dir($tmp_dir) || !is_writable($tmp_dir)) {
        return false;
    }

    $token = bin2hex(random_bytes(8));
    $html_path = $tmp_dir . DIRECTORY_SEPARATOR . 'draft_' . $draft_id . '_' . $token . '.html';
    $pdf_path = $tmp_dir . DIRECTORY_SEPARATOR . 'draft_' . $draft_id . '_' . $token . '.pdf';
    $profile_dir = $tmp_dir . DIRECTORY_SEPARATOR . 'chrome_profile_' . $draft_id . '_' . $token;
    @mkdir($profile_dir, 0775, true);
    $base_href = exportFileUri(__DIR__ . DIRECTORY_SEPARATOR);
    $html = preg_replace('/<head>/i', '<head><base href="' . htmlspecialchars($base_href, ENT_QUOTES) . '">', (string) $html, 1);
    file_put_contents($html_path, $html);

    $html_uri = exportFileUri($html_path);
    $bridge_path = '';
    $print_source = exportBuildPrintPageBridgeUrl($draft_id, $bridge_path);
    if ($print_source !== '' && session_status() === PHP_SESSION_ACTIVE) {
        session_write_close();
    }
    if ($print_source === '') {
        $print_source = $html_uri;
    }

    $command = escapeshellarg($browser)
        . ' --headless=new --disable-gpu --no-sandbox --disable-extensions --allow-file-access-from-files --print-to-pdf-no-header --virtual-time-budget=3000'
        . ' --user-data-dir=' . escapeshellarg($profile_dir)
        . ' --print-to-pdf=' . escapeshellarg($pdf_path)
        . ' ' . escapeshellarg($print_source);
    $output = [];
    $exit_code = 1;
    $timed_out = false;
    $completed = exportRunHeadlessCommand($command, 45, $output, $exit_code, $timed_out);

    if (!$completed || $exit_code !== 0 || !is_file($pdf_path) || filesize($pdf_path) <= 0) {
        $reason = $timed_out ? 'Timeout selepas 45 saat' : 'Exit: ' . $exit_code;
        error_log('Export PDF gagal untuk draf ID ' . $draft_id . '. ' . $reason . '. Output: ' . implode(' | ', array_filter($output)));
        exportCleanupHeadlessFiles($tmp_dir, $html_path, $pdf_path, $bridge_path, $profile_dir);
        return false;
    }

    logActivity(
        $conn,
        $current_user_id,
        'export_draft_letter_pdf',
        'Export PDF surat: ' . ($draft['ref_no'] ?? '') . ' - ' . ($draft['subject'] ?? '') . ' (Draf ID: ' . $draft_id . ')'
    );

    $filename = $title . '.pdf';
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Content-Length: ' . filesize($pdf_path));
    header('Cache-Control: private, max-age=0, must-revalidate');
    readfile($pdf_path);
    exportCleanupHeadlessFiles($tmp_dir, $html_path, $pdf_path, $bridge_path, $profile_dir);
    exit();
}

$letter_pages = decodeDraftLetterPages($draft['letter_pages'] ?? '', $draft['letter_body'] ?? '');
$file_numbering = (($draft['file_numbering'] ?? '') !== '' && ($draft['file_numbering'] ?? '') !== ($draft['ref_no'] ?? ''))
    ? ($draft['file_numbering'] ?? '')
    : ($draft['computed_file_numbering'] ?? '');
$reference = formatDraftLetterReferenceDisplay($draft['department'] ?? '', $draft['ref_no'] ?? '', $file_numbering);
$title = preg_replace('/[^A-Za-z0-9_\-]+/', '_', $draft['subject'] ?: 'surat');
$prepared_by_short_name = trim((string) (($draft['created_by_short_name'] ?? '') ?: ($draft['created_by_fullname'] ?? '')));
$letter_html = '';
foreach ($letter_pages as $page) {
    $page = exportInjectPreparerSignatureIntoGeneratedClosing($page, $draft);
    if (strcasecmp($draft['doc_type'] ?? '', 'Surat Rasmi') === 0) {
        $page = exportReplaceSuratRasmiPrintReferenceLine($page, $reference);
    }
    $letter_html .= exportSafeBody($page);
}
$is_memo_document = strcasecmp(trim((string) ($draft['doc_type'] ?? '')), 'Memo') === 0;
$through_row_html = $is_memo_document ? '' : '<tr><td class="label">Melalui</td><td>:</td><td>' . exportMemoDisplayValue($draft['attention_to'] ?: '') . '</td></tr>';

$html = '<!DOCTYPE html><html><head><meta charset="UTF-8"><style>
@page { size: A4; margin: 25.4mm; }
body { font-family: Arial, Helvetica, sans-serif; font-size: 12pt; line-height: 1.15; color: #000; }
.prepared-by { font-family: Arial, Helvetica, sans-serif; font-size: 8pt; line-height: 1.15; margin-top: 2mm; }
.logo { text-align:center; margin-bottom: 8mm; }
.logo img { width: 24mm; height:auto; }
.title { text-align:center; font-weight:bold; margin-bottom: 7mm; }
.ref { width:100%; border-collapse:collapse; margin-bottom:10mm; }
.ref td { border:1px solid #111; padding:5px 8px; vertical-align:top; }
.ref-line { display:grid; grid-template-columns:17mm 4mm minmax(0, 1fr); white-space:nowrap; }
.ref-colon { text-align:center; }
.label { width:28mm; text-transform:uppercase; }
.meta { width:100%; border-collapse:collapse; margin-bottom:8mm; }
.meta td { padding:5px 0; vertical-align:top; }
table { border-collapse: collapse; }
th, td { padding: 5px 7px; }
</style></head><body>
<div class="logo"><img src="mainpp.png" alt="MAINPP"></div>
<div class="title">' . htmlspecialchars(strtoupper($draft['doc_type'] ?? 'Memo Kelulusan')) . '</div>
<table class="ref"><tr><td rowspan="2"><strong>MAJLIS AGAMA ISLAM NEGERI PULAU PINANG<br>TINGKAT 7, 8 &amp; 9, MENARA JKP<br>NO. 128, JALAN MACALISTER<br>10400 PULAU PINANG</strong></td><td><div class="ref-line"><span>Ruj Kami</span><span class="ref-colon">:</span><span>' . htmlspecialchars($reference) . '</span></div></td></tr><tr><td><div class="ref-line"><span>Tarikh</span><span class="ref-colon">:</span><span>' . htmlspecialchars(exportMalayDate($draft['letter_date'] ?? '')) . '</span></div></td></tr></table>
<table class="meta">
<tr><td class="label">Daripada</td><td>:</td><td>' . htmlspecialchars($draft['signatory_position'] ?: '-') . '<br>Majlis Agama Islam Negeri Pulau Pinang</td></tr>
' . $through_row_html . '
<tr><td class="label">Kepada</td><td>:</td><td>' . exportMemoDisplayValue($draft['recipient_organization'] ?: '') . '</td></tr>
</table>
' . $letter_html . '
<p><strong>"MALAYSIA MADANI"<br>"BERKHIDMAT UNTUK NEGARA"<br>"CEKAP, AKAUNTABILITI, TELUS"</strong></p>
<p>Saya yang menjalankan amanah,</p>
<p style="margin-top:24mm;"><strong>(' . htmlspecialchars(strtoupper($draft['signatory_name'] ?: '')) . ')</strong><br><span class="prepared-by">Disediakan Oleh: ' . htmlspecialchars($prepared_by_short_name) . '</span><br>' . htmlspecialchars($draft['signatory_position'] ?: '') . '</p>
</body></html>';

$autoload = __DIR__ . '/vendor/autoload.php';
if (file_exists($autoload)) {
    require_once $autoload;
}

if (streamPdfWithHeadlessBrowser($html, $title, $conn, $current_user_id, $draft, $draft_id)) {
    exit();
}

if (class_exists('\\Dompdf\\Dompdf')) {
    $dompdf = new \Dompdf\Dompdf(['isRemoteEnabled' => true]);
    $dompdf->loadHtml($html);
    $dompdf->setPaper('A4', 'portrait');
    $dompdf->render();
    logActivity(
        $conn,
        $current_user_id,
        'export_draft_letter_pdf',
        'Export PDF surat: ' . ($draft['ref_no'] ?? '') . ' - ' . ($draft['subject'] ?? '') . ' (Draf ID: ' . $draft_id . ')'
    );
    $dompdf->stream($title . '.pdf', ['Attachment' => true]);
    exit();
}

header('Location: draft_letter_print.php?id=' . $draft_id . '&support_error=pdf_export_failed');
exit();
