<?php
// includes/finance/quotes/finance_quotes_preview.php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (isset($_REQUEST['tenant']) && file_exists('../' . $_REQUEST['tenant'] . '/config.php')) { 
    require_once('../' . $_REQUEST['tenant'] . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

if (!isset($GLOBALS['con']) || !$GLOBALS['con'] instanceof mysqli) {
    echo '<div class="alert alert-danger m-3">Database connection not available.</div>';
    exit;
}

$con = $GLOBALS['con'];

// Quote id
$quoteId = isset($_GET['quote_id']) ? (int)$_GET['quote_id'] : 0;
if ($quoteId <= 0) {
    echo '<div class="alert alert-danger m-3">Invalid quotation reference.</div>';
    exit;
}

// Fetch quote header
$stmt = $con->prepare("
    SELECT
        id,
        quote_ref,
        client_mode,
        clientnumber,
        contact_company,
        contact_name,
        status
    FROM finance_quotes
    WHERE id = ? AND is_deleted = 0
");
$stmt->bind_param('i', $quoteId);
$stmt->execute();
$res   = $stmt->get_result();
$quote = $res->fetch_assoc();
$stmt->close();

if (!$quote) {
    echo '<div class="alert alert-warning m-3">Quotation not found or has been deleted.</div>';
    exit;
}

$quoteRef   = $quote['quote_ref'];
$status     = ucfirst((string)$quote['status']);
$clientName = $quote['contact_company'] ?: $quote['contact_name'] ?: 'Quotation';

// ---------------------------------------------------------------------
// PDF + preview image paths
// ---------------------------------------------------------------------
// Same PDF path as used by includes/engines/quote.php:
// ../../../TENANT_URL/quotes/REF_quote.pdf (from engines)
// Here we are one level deeper (includes/finance/quotes) so it's ../../../../
$pdfPath       = '../' . TENANT_URL . '/quotes/' . $quoteRef . '_quote.pdf';
$pdfExists     = file_exists($pdfPath);

// Preview image store – keep this the SAME folder as invoice preview uses.
// If your invoice preview uses a different folder/name, mirror it here.
$previewImagePath = null;
$previewAvailable = false;
$previewError     = null;

if ($pdfExists && class_exists('Imagick')) {
    // Example: shared preview folder under tenant root
    // Adjust this if your invoice preview uses a different location
    $previewDir = 'preview';

    if (!is_dir($previewDir)) {
        // Try to create the preview directory if it doesn't exist
        @mkdir($previewDir, 0775, true);
    }

    if (is_dir($previewDir) && is_writable($previewDir)) {
        // File name pattern – mirror whatever invoice preview uses, but without type
        $previewImagePath = $previewDir . '/' . $quoteRef . '_quote.png';

        $needsRender = true;
        if (file_exists($previewImagePath)) {
            // Regenerate if PDF is newer than the existing PNG
            $needsRender = (filemtime($previewImagePath) < filemtime($pdfPath));
        }

        if ($needsRender) {
            try {
                $imagick = new Imagick();
                // First page only
                $imagick->setResolution(150, 150);
                $imagick->readImage($pdfPath . '[0]');
                $imagick->setImageFormat('png');
                $imagick->setImageCompressionQuality(90);
                $imagick->writeImage($previewImagePath);
                $imagick->clear();
                $imagick->destroy();
            } catch (Exception $e) {
                $previewError = $e->getMessage();
                $previewImagePath = null;
            }
        }

        if ($previewImagePath && file_exists($previewImagePath)) {
            $previewAvailable = true;
        }
    } else {
        $previewError = 'Preview directory is not writable.';
    }
}

// Web paths (for <img> / <a> src/href) – use the same relative paths
// we used for file_exists above, as per the existing invoice preview pattern.
$pdfWebPath     = $pdfPath;
$previewWebPath = $previewAvailable ? $previewImagePath : null;
?>
<div class="container-fluid">
    <div class="row align-items-center mb-3">
        <div class="col-12 col-md-8">
            <h5 class="mb-1">
                <i class="fad fa-file-pdf me-2"></i>
                Quotation preview: <?php echo htmlspecialchars($quoteRef); ?>
            </h5>
            <p class="mb-0 text-muted">
                <?php echo htmlspecialchars($clientName); ?>
                &middot;
                Status: <?php echo htmlspecialchars($status); ?>
            </p>
        </div>
        <div class="col-12 col-md-4 text-md-end mt-2 mt-md-0">
            <?php if ($pdfExists): ?>
            <a href="<?php echo htmlspecialchars($pdfWebPath); ?>" target="_blank"
               class="btn btn-sm btn-info me-2"
               data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
               title="Open PDF in a new tab">
                <i class="fad fa-external-link-alt me-1"></i>Open PDF
            </a>
            <a href="<?php echo htmlspecialchars($pdfWebPath); ?>" download
               class="btn btn-sm btn-light"
               data-mdb-tooltip-init data-mdb-placement="top" data-mdb-trigger="hover"
               title="Download PDF">
                <i class="fad fa-download me-1"></i>Download
            </a>
            <?php else: ?>
            <span class="badge bg-warning text-dark">
                <i class="fad fa-exclamation-triangle me-1"></i>PDF not found
            </span>
            <?php endif; ?>
        </div>
    </div>

    <div class="row">
        <div class="col-12">
            <?php if (!$pdfExists): ?>
            <div class="alert alert-warning">
                The quotation PDF could not be found.
                Try re-saving the quotation to regenerate the document and then preview again.
            </div>
            <?php elseif ($previewAvailable && $previewWebPath): ?>
            <!-- Image-based preview (matches invoice preview behaviour) -->
            <div class="text-center">
                <img src="<?php echo htmlspecialchars($previewWebPath); ?>"
                     alt="Quotation preview image"
                     style="max-width:100%; height:auto; border:1px solid #ddd; border-radius:4px;">
            </div>
            <?php else: ?>
            <div class="alert alert-warning">
                The quotation preview image could not be generated.
                <?php if ($previewError): ?>
                <br><small class="text-muted"><?php echo htmlspecialchars($previewError); ?></small>
                <?php endif; ?>
                <?php if (!class_exists('Imagick')): ?>
                <br><small class="text-muted">
                    Imagick is not available on the server; only direct PDF viewing is possible.
                </small>
                <?php endif; ?>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>