<?php
/**
 * proforma_preview.php
 *
 * Staff-facing preview wrapper for a proforma invoice.
 *
 * Workflow (client requirement): the reservationist previews the proforma on
 * screen WITHOUT anything auto-downloading, then either
 *   - "Download PDF"   : saves ONE file with a clean, human filename
 *                        ("Proforma PF-PL-41565.pdf") so re-saves replace
 *                        rather than clutter the Downloads folder, or
 *   - "Open in Mail"   : opens their desktop mail client (Outlook / Apple
 *                        Mail) via a mailto: link with the subject and body
 *                        pre-filled, ready for them to attach the downloaded
 *                        PDF and type the recipient.
 *
 * The heavy PDF generation stays in proforma_invoice.php. This page just
 * embeds it inline and provides the two actions. No SendGrid, no automatic
 * send - the proforma is sent from the reservationist's own mailbox.
 *
 * Usage: proforma_preview.php?order_id=123[&bank=1]
 */

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

$orderId   = (int)($_GET['order_id'] ?? 0);
$bankParam = isset($_GET['bank']) ? (string)$_GET['bank'] : '1';

if ($orderId <= 0) {
    http_response_code(400);
    exit('Missing or invalid order_id.');
}

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

/* -----------------------------------------------------------------
   Minimal lookup for the email subject/body. The monetary figures
   are read by the agent straight from the attached PDF, so we only
   need identifying details here - no folio recomputation.
------------------------------------------------------------------ */
$stmt = $pdo->prepare("
    SELECT
        o.id,
        o.order_no,
        o.check_in,
        o.check_out,
        o.property_id,
        g.firstname,
        g.lastname,
        p.code AS property_code,
        CONCAT(COALESCE(a.firstname,''), ' ', COALESCE(a.lastname,'')) AS agent_name
    FROM orders o
    LEFT JOIN guests g       ON g.id = o.guest_id
    LEFT JOIN properties p   ON p.id = o.property_id
    LEFT JOIN agents a       ON a.id = o.agent_id
    WHERE o.id = :id
    LIMIT 1
");
$stmt->execute([':id' => $orderId]);
$order = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$order) {
    http_response_code(404);
    exit('Booking not found.');
}

/* Proforma number: mirror proforma_invoice.php's format exactly, which is
   PREFIX + "-" + UPPERCASE(property_code) + "-" + order_id. The prefix comes
   from lodge/company settings and defaults to "PF" (the near-universal case,
   e.g. "PF-PL-41565"). We read the prefix defensively and fall back to PF so
   this page never diverges from the PDF's own header number. */
$proformaPrefix = 'PF';
try {
    $prefStmt = $pdo->prepare("
        SELECT ProformaPrefix
        FROM tblmailinglist
        WHERE property_id = :pid
        ORDER BY ID DESC
        LIMIT 1
    ");
    $prefStmt->execute([':pid' => (int)($order['property_id'] ?? 0)]);
    $pref = trim((string)($prefStmt->fetchColumn() ?: ''));
    if ($pref !== '') {
        $proformaPrefix = $pref;
    }
} catch (Throwable $e) {
    // Column/table may not exist on this install - keep the PF default.
}

$propertyCode = strtoupper(trim((string)($order['property_code'] ?? '')));
$proformaNo   = $proformaPrefix
    . ($propertyCode !== '' ? '-' . $propertyCode : '')
    . '-' . $orderId;

$guestName = trim(((string)($order['firstname'] ?? '')) . ' ' . ((string)($order['lastname'] ?? '')));
if ($guestName === '') $guestName = 'Guest';

$agentName = trim((string)($order['agent_name'] ?? ''));
if ($agentName === '') $agentName = '';

$bookingRef = trim((string)($order['order_no'] ?? '')) !== '' ? (string)$order['order_no'] : (string)$orderId;

$checkIn  = trim((string)($order['check_in'] ?? ''));
$checkOut = trim((string)($order['check_out'] ?? ''));
$fmtDate = function ($d) {
    $ts = strtotime((string)$d);
    return $ts ? date('d M Y', $ts) : (string)$d;
};
$stayLine = ($checkIn !== '' && $checkOut !== '')
    ? ($fmtDate($checkIn) . ' to ' . $fmtDate($checkOut))
    : '';

/* Clean filename shown to staff, matching the download the PDF will produce. */
$cleanFileName = 'Proforma ' . $proformaNo . '.pdf';

/* -----------------------------------------------------------------
   Pre-filled email. Recipient is left blank on purpose - the
   reservationist types the agent address in their own client.
------------------------------------------------------------------ */
$mailSubject = 'Proforma Invoice ' . $proformaNo . ' - ' . $guestName;

$bodyLines = [];
$bodyLines[] = 'Good day' . ($agentName !== '' ? ' ' . $agentName : '') . ',';
$bodyLines[] = '';
$bodyLines[] = 'Please find attached proforma invoice ' . $proformaNo . ' for the booking below.';
$bodyLines[] = '';
$bodyLines[] = 'Guest: ' . $guestName;
$bodyLines[] = 'Booking Ref: ' . $bookingRef;
if ($stayLine !== '') {
    $bodyLines[] = 'Stay: ' . $stayLine;
}
$bodyLines[] = '';
$bodyLines[] = 'Kindly use the proforma number as the payment reference.';
$bodyLines[] = '';
$bodyLines[] = 'Kind regards,';
$bodyLines[] = 'Reservations';
$mailBody = implode("\r\n", $bodyLines);

/* mailto: with no recipient; subject and body encoded. */
$mailtoHref = 'mailto:?subject=' . rawurlencode($mailSubject) . '&body=' . rawurlencode($mailBody);

/* PDF source URLs (same folder). Inline for the preview, download mode for save. */
$pdfInlineUrl   = 'proforma_invoice.php?order_id=' . $orderId . '&bank=' . rawurlencode($bankParam);
$pdfDownloadUrl = $pdfInlineUrl . '&download=1';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Preview &middot; <?php echo h($proformaNo); ?></title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
<style>
    :root { --pf-navy: #16233a; --pf-line: #e6ebf1; }
    body { background: #eef1f5; margin: 0; height: 100vh; overflow: hidden; }
    .pf-shell { display: flex; flex-direction: column; height: 100vh; }
    .pf-bar {
        background: var(--pf-navy); color: #fff;
        padding: .6rem 1rem; display: flex; flex-wrap: wrap;
        align-items: center; gap: .75rem;
    }
    .pf-bar .pf-title { font-weight: 600; font-size: .98rem; line-height: 1.2; }
    .pf-bar .pf-sub { color: #a9b6c9; font-size: .78rem; }
    .pf-bar .pf-actions { margin-left: auto; display: flex; gap: .5rem; flex-wrap: wrap; }
    .pf-frame-wrap { flex: 1 1 auto; background: #55606f; }
    .pf-frame-wrap iframe { width: 100%; height: 100%; border: 0; display: block; }
    .pf-hint {
        background: #fff7e6; color: #7a5b12; border-top: 1px solid #f0e2bd;
        font-size: .8rem; padding: .5rem 1rem; display: flex; align-items: center; gap: .5rem;
    }
    @media (max-width: 575px) {
        .pf-bar .pf-actions { width: 100%; margin-left: 0; }
        .pf-bar .pf-actions .btn { flex: 1 1 auto; }
    }
</style>
</head>
<body>
<div class="pf-shell">

    <div class="pf-bar">
        <div>
            <div class="pf-title"><i class="bi bi-file-earmark-text me-1"></i><?php echo h($proformaNo); ?></div>
            <div class="pf-sub"><?php echo h($guestName); ?> &middot; Ref <?php echo h($bookingRef); ?><?php echo $stayLine !== '' ? ' &middot; ' . h($stayLine) : ''; ?></div>
        </div>

        <div class="pf-actions">
            <a class="btn btn-light btn-sm" href="<?php echo h($pdfDownloadUrl); ?>" id="pfDownloadBtn">
                <i class="bi bi-download me-1"></i>Download PDF
            </a>
            <a class="btn btn-warning btn-sm text-dark fw-semibold" href="<?php echo h($mailtoHref); ?>" id="pfMailBtn">
                <i class="bi bi-envelope me-1"></i>Open in Mail
            </a>
            <button class="btn btn-outline-light btn-sm" type="button" id="pfBothBtn" title="Download the PDF, then open your mail client">
                <i class="bi bi-lightning-charge me-1"></i>Download &amp; Compose
            </button>
        </div>
    </div>

    <div class="pf-frame-wrap">
        <iframe src="<?php echo h($pdfInlineUrl); ?>" title="Proforma preview"></iframe>
    </div>

    <div class="pf-hint">
        <i class="bi bi-info-circle"></i>
        <span>
            The proforma opens in your mail client with the message ready.
            Attach the downloaded file <strong><?php echo h($cleanFileName); ?></strong> and add the recipient before sending.
        </span>
    </div>

</div>

<script>
(function () {
    var downloadUrl = <?php echo json_encode($pdfDownloadUrl); ?>;
    var mailHref    = <?php echo json_encode($mailtoHref); ?>;

    // "Download & Compose": trigger the clean-name download, then open the
    // mail client a moment later so the browser doesn't cancel the download
    // when the mailto: handler takes focus.
    var bothBtn = document.getElementById('pfBothBtn');
    if (bothBtn) {
        bothBtn.addEventListener('click', function () {
            var a = document.createElement('a');
            a.href = downloadUrl;
            // Some browsers honour the download hint for same-origin PDFs; the
            // server also forces the clean filename via Content-Disposition.
            a.setAttribute('download', <?php echo json_encode($cleanFileName); ?>);
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);

            setTimeout(function () {
                window.location.href = mailHref;
            }, 900);
        });
    }
})();
</script>
</body>
</html>
