<?php
require_once __DIR__ . '/../../app/config/database.php';
require_once __DIR__ . '/../../app/includes/helpers.php';
require_once __DIR__ . '/render.php';

$id = (int)($_GET['id'] ?? 0);
$hash = (string)($_GET['h'] ?? '');

if ($id <= 0 || empty($hash)) {
    http_response_code(400);
    exit('Invalid link.');
}

$stmt = db()->prepare('SELECT q.*, c.customer_name, c.phone, c.email, c.address, c.location, u.name prepared_by, u.role as creator_role FROM quotations q JOIN customers c ON c.id=q.customer_id JOIN users u ON u.id=q.created_by WHERE q.id=?');
$stmt->execute([$id]);
$q = $stmt->fetch();

if (!$q) {
    http_response_code(404);
    exit('Quotation not found.');
}

// Verify hash
$expectedHash = substr(hash('sha256', $q['id'] . $q['created_at'] . 'FQS_SHARE'), 0, 16);
if (!hash_equals($expectedHash, $hash)) {
    http_response_code(403);
    exit('Invalid or expired sharing link.');
}

// Link is valid, render the PDF for download/view
require_once __DIR__ . '/../../app/services/PdfService.php';

$html = render_quotation($id, true, 'customer');
$pdfService = new PdfService();

// Stream inline so it opens in the browser directly
$pdfService->generate($html, 'Quotation_' . $q['quotation_no'] . '.pdf', true);
