<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();

/*
 * SendGrid configuration.
 *
 * IMPORTANT:
 * Replace SG_PASTE_NEW_KEY_HERE with a NEW SendGrid API key.
 * The keys previously pasted into source/chat should be revoked.
 */
if (!defined('SENDGRID_API_KEY')) {
    define('SENDGRID_API_KEY', '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');
}

if (!defined('SENDGRID_FROM_EMAIL')) {
    define('SENDGRID_FROM_EMAIL', 'info@batonkaguestlodge.com');
}
if (!defined('SENDGRID_FROM_NAME')) {
    define('SENDGRID_FROM_NAME', 'Batonka Reservations');
}
 

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!function_exists('h')) {
    function h($value): string
    {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('ep_table_exists')) {
    function ep_table_exists(PDO $pdo, string $table): bool
    {
        static $cache = [];
        if (isset($cache[$table])) return $cache[$table];

        try {
            $stmt = $pdo->prepare(
                'SELECT COUNT(*) FROM information_schema.tables
                 WHERE table_schema = DATABASE() AND table_name = :table_name'
            );
            $stmt->execute([':table_name' => $table]);
            return $cache[$table] = ((int)$stmt->fetchColumn() > 0);
        } catch (Throwable $e) {
            return $cache[$table] = false;
        }
    }
}

if (!function_exists('ep_column_exists')) {
    function ep_column_exists(PDO $pdo, string $table, string $column): bool
    {
        static $cache = [];
        $key = $table . '.' . $column;
        if (isset($cache[$key])) return $cache[$key];

        try {
            $stmt = $pdo->prepare(
                'SELECT COUNT(*) FROM information_schema.columns
                 WHERE table_schema = DATABASE()
                   AND table_name = :table_name
                   AND column_name = :column_name'
            );
            $stmt->execute([
                ':table_name' => $table,
                ':column_name' => $column,
            ]);
            return $cache[$key] = ((int)$stmt->fetchColumn() > 0);
        } catch (Throwable $e) {
            return $cache[$key] = false;
        }
    }
}

function ep_config_value(string $constantName, string $environmentName, string $default = ''): string
{
    if (defined($constantName)) {
        return trim((string)constant($constantName));
    }

    $value = getenv($environmentName);
    return $value !== false ? trim((string)$value) : $default;
}

function ep_absolute_url(string $relativeUrl): string
{
    if (preg_match('~^https?://~i', $relativeUrl)) {
        return $relativeUrl;
    }

    $https = !empty($_SERVER['HTTPS']) && strtolower((string)$_SERVER['HTTPS']) !== 'off';
    $scheme = $https ? 'https' : 'http';
    $host = (string)($_SERVER['HTTP_HOST'] ?? '');
    $scriptDir = rtrim(str_replace('\\', '/', dirname((string)($_SERVER['SCRIPT_NAME'] ?? '/'))), '/');

    if ($host === '') return $relativeUrl;
    return $scheme . '://' . $host . $scriptDir . '/' . ltrim($relativeUrl, '/');
}

function ep_fetch_pdf(string $url): string
{
    if (!function_exists('curl_init')) {
        throw new RuntimeException('PHP cURL is required to retrieve the PDF attachment.');
    }

    $ch = curl_init($url);
    if ($ch === false) {
        throw new RuntimeException('Could not initialise the PDF request.');
    }

    $cookieHeader = '';
    foreach ($_COOKIE as $name => $value) {
        $cookieHeader .= ($cookieHeader === '' ? '' : '; ') . rawurlencode((string)$name) . '=' . rawurlencode((string)$value);
    }

    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS => 5,
        CURLOPT_CONNECTTIMEOUT => 15,
        CURLOPT_TIMEOUT => 90,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_HTTPHEADER => [
            'Accept: application/pdf',
            'User-Agent: PMS-SendGrid-PDF/1.0',
            $cookieHeader !== '' ? 'Cookie: ' . $cookieHeader : 'Cookie:',
        ],
    ]);

    $body = curl_exec($ch);
    $status = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $contentType = strtolower((string)curl_getinfo($ch, CURLINFO_CONTENT_TYPE));
    $curlError = curl_error($ch);
    curl_close($ch);

    if ($body === false || $curlError !== '') {
        throw new RuntimeException('Could not generate the PDF: ' . $curlError);
    }

    if ($status < 200 || $status >= 300) {
        throw new RuntimeException('The PDF generator returned HTTP ' . $status . '.');
    }

    if (strncmp($body, '%PDF-', 5) !== 0 && strpos($contentType, 'application/pdf') === false) {
        $preview = trim(strip_tags(substr($body, 0, 300)));
        throw new RuntimeException(
            'The selected document did not return a valid PDF.' . ($preview !== '' ? ' Response: ' . $preview : '')
        );
    }

    return $body;
}

function ep_release_session_for_internal_request(): bool
{
    if (session_status() === PHP_SESSION_ACTIVE) {
        session_write_close();
        return true;
    }
    return false;
}

function ep_restore_session_after_internal_request(bool $wasReleased): void
{
    if ($wasReleased && session_status() === PHP_SESSION_NONE) {
        session_start();
    }
}

function ep_send_sendgrid(array $payload, string $apiKey): array
{
    if (!function_exists('curl_init')) {
        throw new RuntimeException('PHP cURL is required to send through SendGrid.');
    }

    $ch = curl_init('https://api.sendgrid.com/v3/mail/send');
    if ($ch === false) {
        throw new RuntimeException('Could not initialise the SendGrid request.');
    }

    $json = json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    if ($json === false) {
        throw new RuntimeException('Could not prepare the SendGrid message.');
    }

    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CONNECTTIMEOUT => 15,
        CURLOPT_TIMEOUT => 90,
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . $apiKey,
            'Content-Type: application/json',
        ],
        CURLOPT_POSTFIELDS => $json,
    ]);

    $response = curl_exec($ch);
    $status = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);

    if ($response === false || $curlError !== '') {
        throw new RuntimeException('SendGrid connection failed: ' . $curlError);
    }

    if ($status < 200 || $status >= 300) {
        $message = 'SendGrid rejected the email (HTTP ' . $status . ').';
        $decoded = json_decode((string)$response, true);
        if (is_array($decoded) && !empty($decoded['errors'][0]['message'])) {
            $message .= ' ' . $decoded['errors'][0]['message'];
        }
        throw new RuntimeException($message);
    }

    return ['status' => $status, 'response' => (string)$response];
}

$orderId = (int)($_GET['order_id'] ?? $_POST['order_id'] ?? 0);
$type = strtolower(trim((string)($_GET['type'] ?? $_POST['type'] ?? 'standard')));

$allowedTypes = [
    'standard' => ['label' => 'Proforma', 'file' => 'proforma_invoice.php'],
    'master'   => ['label' => 'Main Folio Proforma', 'file' => 'proforma_master_folio.php'],
    'room'     => ['label' => 'Room Proforma', 'file' => 'proforma_room_account.php'],
    'guest'    => ['label' => 'Guest Folio Proforma', 'file' => 'guest_folios.php'],
];
if (!isset($allowedTypes[$type])) $type = 'standard';

$errors = [];
$success = '';
$order = null;
$guestName = '';
$emailTo = '';

if ($orderId <= 0) {
    $errors[] = 'No booking was selected.';
} else {
    try {
        $guestJoin = '';
        $agentJoin = '';
        $guestSelect = "'' AS guest_name, '' AS guest_email";
        $agentSelect = "'' AS agent_email";

        if (ep_table_exists($pdo, 'guests') && ep_column_exists($pdo, 'orders', 'guest_id')) {
            $firstName = ep_column_exists($pdo, 'guests', 'firstname') ? "COALESCE(g.firstname,'')" : "''";
            $lastName = ep_column_exists($pdo, 'guests', 'lastname') ? "COALESCE(g.lastname,'')" : "''";
            $guestNameExpr = "TRIM(CONCAT($firstName,' ',$lastName))";
            $guestEmailExpr = ep_column_exists($pdo, 'guests', 'email') ? "COALESCE(g.email,'')" : "''";
            $guestJoin = 'LEFT JOIN guests g ON g.id = o.guest_id';
            $guestSelect = "$guestNameExpr AS guest_name, $guestEmailExpr AS guest_email";
        }

        if (ep_table_exists($pdo, 'agents') && ep_column_exists($pdo, 'orders', 'agent_id')) {
            $agentEmailExpr = ep_column_exists($pdo, 'agents', 'email') ? "COALESCE(a.email,'')" : "''";
            $agentJoin = 'LEFT JOIN agents a ON a.id = o.agent_id';
            $agentSelect = "$agentEmailExpr AS agent_email";
        }

        $orderNoExpr = ep_column_exists($pdo, 'orders', 'order_no') ? 'o.order_no' : 'o.id';
        $checkInExpr = ep_column_exists($pdo, 'orders', 'check_in') ? 'o.check_in' : 'NULL';
        $checkOutExpr = ep_column_exists($pdo, 'orders', 'check_out') ? 'o.check_out' : 'NULL';

        $stmt = $pdo->prepare("SELECT
                o.id,
                {$orderNoExpr} AS order_no,
                {$checkInExpr} AS check_in,
                {$checkOutExpr} AS check_out,
                {$guestSelect},
                {$agentSelect}
            FROM orders o
            {$guestJoin}
            {$agentJoin}
            WHERE o.id = :id
            LIMIT 1");
        $stmt->execute([':id' => $orderId]);
        $order = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$order) throw new RuntimeException('Booking was not found.');

        $guestName = trim((string)($order['guest_name'] ?? '')) ?: 'Guest';
        $guestEmail = trim((string)($order['guest_email'] ?? ''));
        $agentEmail = trim((string)($order['agent_email'] ?? ''));

        if (filter_var($guestEmail, FILTER_VALIDATE_EMAIL)) {
            $emailTo = $guestEmail;
        } elseif (filter_var($agentEmail, FILTER_VALIDATE_EMAIL)) {
            $emailTo = $agentEmail;
        }
    } catch (Throwable $e) {
        $errors[] = $e->getMessage();
    }
}

$proformaFile = $allowedTypes[$type]['file'];
$proformaLabel = $allowedTypes[$type]['label'];
$pdfUrl = $proformaFile . '?order_id=' . urlencode((string)$orderId);
$absolutePdfUrl = ep_absolute_url($pdfUrl);
$orderNo = $order ? (string)($order['order_no'] ?? ('#' . $orderId)) : ('#' . $orderId);
$defaultSubject = $proformaLabel . ' - ' . $orderNo;

$bodyLines = [
    'Dear ' . $guestName . ',',
    '',
    'Please find attached the ' . strtolower($proformaLabel) . ' for booking ' . $orderNo . '.',
];
if (!empty($order['check_in']) || !empty($order['check_out'])) {
    $bodyLines[] = '';
    $bodyLines[] = 'Stay: ' . trim((string)($order['check_in'] ?? '')) . ' to ' . trim((string)($order['check_out'] ?? ''));
}
$bodyLines[] = '';
$bodyLines[] = 'Kind regards,';
$defaultBody = implode("\n", $bodyLines);

$formTo = trim((string)($_POST['email_to'] ?? $emailTo));
$formSubject = trim((string)($_POST['email_subject'] ?? $defaultSubject));
$formBody = trim((string)($_POST['email_body'] ?? $defaultBody));

if (empty($_SESSION['email_proforma_csrf'])) {
    $_SESSION['email_proforma_csrf'] = bin2hex(random_bytes(24));
}
$csrfToken = (string)$_SESSION['email_proforma_csrf'];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_sendgrid'])) {
    error_log('email_proforma.php: SendGrid POST received for order_id=' . $orderId);
    try {
        if (!hash_equals($csrfToken, (string)($_POST['csrf_token'] ?? ''))) {
            throw new RuntimeException('Your session expired. Reload the page and try again.');
        }
        if ($orderId <= 0 || !$order) throw new RuntimeException('Invalid booking.');
        if (!filter_var($formTo, FILTER_VALIDATE_EMAIL)) throw new RuntimeException('Enter a valid recipient email address.');
        if ($formSubject === '') throw new RuntimeException('Enter an email subject.');
        if ($formBody === '') throw new RuntimeException('Enter an email message.');

        $apiKey = ep_config_value('SENDGRID_API_KEY', 'SENDGRID_API_KEY');
        $fromEmail = ep_config_value('SENDGRID_FROM_EMAIL', 'SENDGRID_FROM_EMAIL');
        $fromName = ep_config_value('SENDGRID_FROM_NAME', 'SENDGRID_FROM_NAME', 'Reservations');

        if ($apiKey === '' || $apiKey === 'SG_PASTE_NEW_KEY_HERE') {
            throw new RuntimeException('SENDGRID_API_KEY has not been configured with a new API key.');
        }
        if (!filter_var($fromEmail, FILTER_VALIDATE_EMAIL)) {
            throw new RuntimeException('SENDGRID_FROM_EMAIL has not been configured with a valid verified sender address.');
        }

        /*
         * The PDF URL points back to this same authenticated application.
         * Release the session lock before cURL requests the PDF; otherwise the
         * PDF request can block waiting for the session held by this request.
         */
        $sessionWasReleased = ep_release_session_for_internal_request();

        try {
            $pdfBytes = ep_fetch_pdf($absolutePdfUrl);

            $safeOrderNo = preg_replace('/[^A-Za-z0-9_-]+/', '_', $orderNo);
            $attachmentName = ($type === 'standard' ? 'Proforma' : preg_replace('/\s+/', '_', $proformaLabel))
                . '_' . $safeOrderNo . '.pdf';

            $htmlBody = nl2br(h($formBody));
            $payload = [
                'personalizations' => [[
                    'to' => [['email' => $formTo]],
                    'subject' => $formSubject,
                ]],
                'from' => [
                    'email' => $fromEmail,
                    'name' => $fromName,
                ],
                'content' => [
                    ['type' => 'text/plain', 'value' => $formBody],
                    ['type' => 'text/html', 'value' => $htmlBody],
                ],
                'attachments' => [[
                    'content' => base64_encode($pdfBytes),
                    'type' => 'application/pdf',
                    'filename' => $attachmentName,
                    'disposition' => 'attachment',
                ]],
            ];

            $sendResult = ep_send_sendgrid($payload, $apiKey);
        } finally {
            ep_restore_session_after_internal_request($sessionWasReleased);
        }

        $success = 'Email accepted by SendGrid (HTTP '
            . (int)$sendResult['status']
            . ') and queued for '
            . $formTo
            . ' with '
            . $attachmentName
            . ' attached.';

        $_SESSION['email_proforma_csrf'] = bin2hex(random_bytes(24));
        $csrfToken = (string)$_SESSION['email_proforma_csrf'];
    } catch (Throwable $e) {
        $errors[] = $e->getMessage();
    }
}

$pageTitle = 'Email Proforma';
require_once __DIR__ . '/../../includes/header.php';
?>

<div class="card panel-card mx-auto email-proforma-card">
    <div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">
        <div>
            <h5 class="mb-0"><i class="bi bi-envelope-paper me-2"></i>Email <?php echo h($proformaLabel); ?></h5>
            <div class="small text-muted">Booking <?php echo h($orderNo); ?></div>
        </div>
        <a href="../calendar/calendar.php" class="btn btn-sm btn-outline-secondary">Back to Calendar</a>
    </div>

    <div class="card-body">
        <?php if ($success !== ''): ?>
            <div class="alert alert-success"><i class="bi bi-check-circle me-2"></i><?php echo h($success); ?></div>
        <?php endif; ?>

        <?php if ($errors): ?>
            <div class="alert alert-danger">
                <strong>Could not send:</strong>
                <ul class="mb-0">
                    <?php foreach ($errors as $error): ?>
                        <li><?php echo h($error); ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        <?php endif; ?>

        <?php if ($order): ?>
            <div class="alert alert-info">
                Review or edit the recipient, subject and message below. When you click
                <strong>Send with SendGrid</strong>, the PDF shown on the right is generated and attached automatically.
            </div>

            <form method="post" id="sendgridForm">
                <input type="hidden" name="send_sendgrid" value="1">
                <input type="hidden" name="order_id" value="<?php echo (int)$orderId; ?>">
                <input type="hidden" name="type" value="<?php echo h($type); ?>">
                <input type="hidden" name="csrf_token" value="<?php echo h($csrfToken); ?>">

                <div class="row g-3">
                    <div class="col-lg-6">
                        <div class="mb-3">
                            <label class="form-label fw-bold">To</label>
                            <input type="email" name="email_to" id="emailTo" class="form-control"
                                   value="<?php echo h($formTo); ?>" placeholder="customer@example.com" required>
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-bold">Subject</label>
                            <input type="text" name="email_subject" id="emailSubject" class="form-control"
                                   value="<?php echo h($formSubject); ?>" required>
                        </div>

                        <div class="mb-3">
                            <label class="form-label fw-bold">Message</label>
                            <textarea name="email_body" id="emailBody" class="form-control" rows="10" required><?php echo h($formBody); ?></textarea>
                        </div>

                        <div class="attachment-box mb-3">
                            <div class="d-flex align-items-center gap-2">
                                <i class="bi bi-paperclip fs-4"></i>
                                <div>
                                    <div class="fw-bold"><?php echo h($proformaLabel); ?> PDF</div>
                                    <div class="small text-muted">Generated and attached automatically when sent.</div>
                                </div>
                            </div>
                        </div>

                        <div class="d-flex flex-wrap gap-2 align-items-center">
                            <div class="dropdown">
                                <button
                                    class="btn btn-success dropdown-toggle"
                                    type="button"
                                    id="emailActionsDropdown"
                                    data-bs-toggle="dropdown"
                                    aria-expanded="false">
                                    <i class="bi bi-envelope-paper me-2"></i>Email...
                                </button>

                                <ul class="dropdown-menu shadow email-actions-menu" aria-labelledby="emailActionsDropdown">
                                    <li>
                                        <button type="submit" class="dropdown-item" id="sendButton">
                                            <i class="bi bi-send-fill me-2 text-success"></i>
                                            <span>
                                                <strong>Send Immediately</strong>
                                                <small>SendGrid sends the PDF attachment now</small>
                                            </span>
                                        </button>
                                    </li>

                                    <li><hr class="dropdown-divider"></li>

                                    <li>
                                        <a class="dropdown-item"
                                           href="/rooms/modules/communications/index.php?order_id=<?php echo (int)$orderId; ?>"
                                           target="_blank"
                                           rel="noopener">
                                            <i class="bi bi-microsoft me-2 text-primary"></i>
                                            <span>
                                                <strong>Draft in Outlook</strong>
                                                <small>Prepare a code for the Outlook reply add-in</small>
                                            </span>
                                        </a>
                                    </li>

                                    <li>
                                        <button type="button" class="dropdown-item" onclick="openGmailDraft()">
                                            <i class="bi bi-google me-2 text-danger"></i>
                                            <span>
                                                <strong>Draft in Gmail</strong>
                                                <small>Open Gmail with recipient, subject and message</small>
                                            </span>
                                        </button>
                                    </li>

                                    <li>
                                        <button type="button" class="dropdown-item" onclick="copyEmailText(this)">
                                            <i class="bi bi-clipboard-check me-2 text-secondary"></i>
                                            <span>
                                                <strong>Copy Email Text</strong>
                                                <small>Copy recipient, subject and message</small>
                                            </span>
                                        </button>
                                    </li>

                                    <li><hr class="dropdown-divider"></li>

                                    <li>
                                        <a class="dropdown-item"
                                           href="<?php echo h($pdfUrl); ?>"
                                           target="_blank"
                                           rel="noopener">
                                            <i class="bi bi-file-earmark-pdf me-2 text-danger"></i>
                                            <span>
                                                <strong>Open PDF</strong>
                                                <small>View the generated proforma</small>
                                            </span>
                                        </a>
                                    </li>

                                    <li>
                                        <a class="dropdown-item"
                                           href="<?php echo h($pdfUrl); ?>"
                                           download="<?php echo h('Proforma_' . preg_replace('/[^A-Za-z0-9_-]+/', '_', $orderNo) . '.pdf'); ?>">
                                            <i class="bi bi-download me-2 text-dark"></i>
                                            <span>
                                                <strong>Download PDF</strong>
                                                <small>Save the PDF for manual attachment</small>
                                            </span>
                                        </a>
                                    </li>
                                </ul>
                            </div>

                            <span id="emailActionMessage" class="small text-muted"></span>
                        </div>
                    </div>

                    <div class="col-lg-6">
                        <div class="pdf-preview-wrap">
                            <div class="pdf-preview-title">
                                <i class="bi bi-file-earmark-pdf me-2"></i>Attachment Preview
                            </div>
                            <iframe src="<?php echo h($pdfUrl); ?>" title="PDF preview" loading="lazy"></iframe>
                        </div>
                    </div>
                </div>
            </form>

            <script>
            function emailFormValues() {
                return {
                    to: document.getElementById('emailTo').value.trim(),
                    subject: document.getElementById('emailSubject').value.trim(),
                    body: document.getElementById('emailBody').value.trim()
                };
            }

            function showEmailActionMessage(message, isError) {
                const box = document.getElementById('emailActionMessage');
                box.textContent = message;
                box.className = 'small ' + (isError ? 'text-danger' : 'text-success');

                window.clearTimeout(showEmailActionMessage.timer);
                showEmailActionMessage.timer = window.setTimeout(function () {
                    box.textContent = '';
                    box.className = 'small text-muted';
                }, 5000);
            }

            function openGmailDraft() {
                const values = emailFormValues();

                if (!values.to || !values.subject || !values.body) {
                    showEmailActionMessage('Complete To, Subject and Message first.', true);
                    return;
                }

                const gmailUrl = 'https://mail.google.com/mail/?view=cm&fs=1'
                    + '&to=' + encodeURIComponent(values.to)
                    + '&su=' + encodeURIComponent(values.subject)
                    + '&body=' + encodeURIComponent(values.body);

                window.open(gmailUrl, '_blank', 'noopener');
                showEmailActionMessage('Gmail draft opened. Attach the PDF manually if required.', false);
            }

            async function copyEmailText(button) {
                const values = emailFormValues();
                const text = 'To: ' + values.to
                    + '\nSubject: ' + values.subject
                    + '\n\n' + values.body;

                try {
                    await navigator.clipboard.writeText(text);
                    showEmailActionMessage('Email text copied.', false);
                } catch (error) {
                    const textarea = document.createElement('textarea');
                    textarea.value = text;
                    textarea.style.position = 'fixed';
                    textarea.style.opacity = '0';
                    document.body.appendChild(textarea);
                    textarea.focus();
                    textarea.select();

                    const copied = document.execCommand('copy');
                    document.body.removeChild(textarea);

                    showEmailActionMessage(
                        copied ? 'Email text copied.' : 'Could not copy the email text.',
                        !copied
                    );
                }
            }

            document.getElementById('sendgridForm').addEventListener('submit', function (event) {
                const to = document.getElementById('emailTo').value.trim();
                const subject = document.getElementById('emailSubject').value.trim();
                if (!confirm('Send "' + subject + '" to ' + to + ' with the PDF attached?')) {
                    event.preventDefault();
                    return;
                }

                const button = document.getElementById('sendButton');
                button.disabled = true;
                button.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Sending...';
            });
            </script>
        <?php endif; ?>
    </div>
</div>

<style>
.email-proforma-card{max-width:1200px}.email-proforma-card .card-header{padding:12px 14px}.email-proforma-card .card-body{padding:14px}.email-proforma-card textarea{min-height:220px}.attachment-box{background:#f8f9fa;border:1px solid #dfe3e7;border-radius:8px;padding:12px}.pdf-preview-wrap{border:1px solid #dfe3e7;border-radius:8px;overflow:hidden;background:#f8f9fa}.pdf-preview-title{padding:10px 12px;background:#eef1f4;border-bottom:1px solid #dfe3e7;font-weight:700}.pdf-preview-wrap iframe{display:block;width:100%;height:650px;border:0;background:#fff}.email-actions-menu{min-width:310px;padding:7px}.email-actions-menu .dropdown-item{display:flex;align-items:flex-start;gap:4px;border-radius:8px;padding:9px 10px;white-space:normal}.email-actions-menu .dropdown-item:hover{background:#f4f7fa}.email-actions-menu .dropdown-item>i{width:22px;margin-top:2px}.email-actions-menu .dropdown-item span{display:flex;flex-direction:column}.email-actions-menu .dropdown-item strong{font-size:13px;line-height:1.25}.email-actions-menu .dropdown-item small{font-size:11px;color:#6c757d;line-height:1.35;margin-top:2px}@media(max-width:991px){.pdf-preview-wrap iframe{height:500px}}
</style>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
