<?php
// includes/engines/quote.php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Tenant + config (mirror invoice.php)
if (isset($_POST['tenant']) && file_exists('../../../' . $_POST['tenant'] . '/config.php')) {
    require_once('../../../' . $_POST['tenant'] . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

if (!isset($GLOBALS['con']) || !$GLOBALS['con'] instanceof mysqli) {
    die('Database connection not available.');
}

$con      = $GLOBALS['con'];
$quoteId  = isset($_POST['quote_id']) ? (int)$_POST['quote_id'] : 0;

if ($quoteId <= 0) {
    die('Invalid quotation id.');
}

// ---------------------------------------------------------------------
// Fetch quote header + client details
// ---------------------------------------------------------------------
$stmt = $con->prepare("
    SELECT 
        q.*,
        c.clientname,
        c.billing_name,
        c.billing1,
        c.billing2,
        c.billing_town,
        c.billing_county,
        c.billing_postcode,
        c.billing_email,
        c.billing_phone
    FROM finance_quotes q
    LEFT JOIN clientdetails c ON q.clientnumber = c.clientnumber
    WHERE q.id = ? AND q.is_deleted = 0
");
$stmt->bind_param('i', $quoteId);
$stmt->execute();
$res   = $stmt->get_result();
$quote = $res->fetch_assoc();
$stmt->close();

if (!$quote) {
    die('Quotation not found.');
}

// ---------------------------------------------------------------------
// Fetch items
// ---------------------------------------------------------------------
$stmt = $con->prepare("
    SELECT line_no, item_type, description, qty, unit_price, net, vat, gross, meta
    FROM finance_quote_items
    WHERE quote_id = ?
    ORDER BY line_no ASC
");
$stmt->bind_param('i', $quoteId);
$stmt->execute();
$itemsRes = $stmt->get_result();

$items = [];
while ($row = $itemsRes->fetch_assoc()) {
    $row['qty']        = (float)$row['qty'];
    $row['unit_price'] = (float)$row['unit_price'];
    $row['net']        = (float)$row['net'];
    $row['vat']        = (float)$row['vat'];
    $row['gross']      = (float)$row['gross'];
    $row['meta']       = $row['meta'] ? json_decode($row['meta'], true) : null;
    $items[] = $row;
}
$stmt->close();

// ---------------------------------------------------------------------
// IU summary (same logic as UI rows in JS)
// ---------------------------------------------------------------------
$iuMinutesPerUnit = (int)($quote['iu_minutes_per_unit'] ?? 15);
$iuRatePerUnit    = (float)($quote['iu_rate_per_unit'] ?? 0.0);
$totalIU          = 0.0;

foreach ($items as $it) {
    if ($it['item_type'] === 'ui_item') {
        $totalIU += $it['qty'];
        if ($iuRatePerUnit === null && $it['unit_price'] > 0) {
            $iuRatePerUnit = $it['unit_price'];
        }
    }
}
if ($iuRatePerUnit === null) {
    $iuRatePerUnit = 0.0;
}

$iuTotalMinutes = $totalIU * $iuMinutesPerUnit;
$iuTotalHours   = $iuTotalMinutes / 60.0;
$iuEstFee       = $totalIU * $iuRatePerUnit;

// ---------------------------------------------------------------------
// Basic labels / dates
// ---------------------------------------------------------------------
$scopeMap = [
    'single'       => 'Single inspection',
    'renewal'      => 'Contract renewal',
    'new_contract' => 'New contract',
    'adhoc'        => 'Ad-hoc inspection',
];
$scopeLabel = $scopeMap[$quote['scope_type']] ?? ucfirst($quote['scope_type']);

$sourceMap = [
    'manual'     => 'Manual entry',
    'item_based' => 'Item-based (from assets)',
];
$sourceLabel = $sourceMap[$quote['source_type']] ?? ucfirst($quote['source_type']);

$statusLabel = ucfirst($quote['status']);

$createdDate = !empty($quote['date_created'])
    ? date('d-m-Y', (int)$quote['date_created'])
    : '';

$validUntilDate = !empty($quote['valid_until'])
    ? date('d-m-Y', (int)$quote['valid_until'])
    : '';

// ---------------------------------------------------------------------
// Client / billing block
// ---------------------------------------------------------------------
$company = $quote['contact_company'] ?: $quote['clientname'];
$contact = $quote['contact_name'];
$email   = $quote['contact_email'];
$phone   = $quote['contact_phone'];

$billingAddress = trim((string)$quote['billing_address']);
if ($billingAddress === '') {
    $parts = [];
    if (!empty($quote['billing_name']))      $parts[] = $quote['billing_name'];
    if (!empty($quote['billing1']))          $parts[] = $quote['billing1'];
    if (!empty($quote['billing2']))          $parts[] = $quote['billing2'];
    if (!empty($quote['billing_town']))      $parts[] = $quote['billing_town'];
    if (!empty($quote['billing_county']))    $parts[] = $quote['billing_county'];
    if (!empty($quote['billing_postcode']))  $parts[] = $quote['billing_postcode'];
    $billingAddress = implode('<br>', array_filter($parts, fn($v) => $v !== ''));
}

$billingEmail = $quote['billing_email'] ?: $email;
$billingPhone = $quote['billing_phone'] ?: $phone;

// Totals
$netTotal   = (float)$quote['net_total'];
$vatTotal   = (float)$quote['vat_total'];
$grossTotal = (float)$quote['gross_total'];
$vatrate    = (float)$quote['vatrate'];
$currency   = '£';

$notesClient = $quote['notes_client'] ?? '';

// ---------------------------------------------------------------------
// HEADER / FOOTER (mirror invoice.php pattern)
// ---------------------------------------------------------------------
$header = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta name="viewport" content="width=device-width" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
$header .= '</head>
<body bgcolor="#FFFFFF" topmargin="0" leftmargin="0" marginheight="0" marginwidth="0" style="font-size:10px!important">';
$header .= file_get_contents('../../../' . TENANT_URL . '/engines/invoice_structure/header_view.php');

$quote_body  = '';
$quote_body .= '<link href="../../packages/bootstrap/bootstrap.gen.css" rel="stylesheet">';
$quote_body .= file_get_contents('../../../' . TENANT_URL . '/engines/invoice_structure/style.php');

// Main heading
$quote_body .= '<h2 style="text-align:right; color:#2a3f54">QUOTATION</h2>';

// Top meta tables (similar to invoice but quote-focused)
$quote_body .= '
<div style="clear:both"></div>
<hr style="color:#2a3f54">
<div style="width:30%; float:left">
    <table class="invtable table table-borderless">
        <tr><th>QUOTE REFERENCE</th><td>' . htmlspecialchars($quote['quote_ref']) . '</td></tr>
       
    </table>
</div>
<div style="width:40%; float:right">
    <table class="invtable table table-borderless" style="text-align:right">
        <tr><th>QUOTE DATE</th><td>' . htmlspecialchars($createdDate) . '</td></tr>';
if ($validUntilDate) {
    $quote_body .= '<tr><th>VALID UNTIL</th><td>' . htmlspecialchars($validUntilDate) . '</td></tr>';
}
$quote_body .= '
    </table>
</div>
<div style="clear:both"></div>
<hr style="color:#2a3f54">';

// Address / scope block
$quote_body .= '
<div style="width:50%; float:left">
    <h4>Quoted to:</h4>
    <table class="invtable table table-borderless">
        <tr><td><strong>' . htmlspecialchars($company) . '</strong></td></tr>';
if ($contact) {
    $quote_body .= '<tr><td>' . htmlspecialchars($contact) . '</td></tr>';
}
if ($billingAddress) {
    $quote_body .= '<tr><td>' . $billingAddress . '</td></tr>';
}
if ($billingEmail) {
    $quote_body .= '<tr><td>Email: ' . htmlspecialchars($billingEmail) . '</td></tr>';
}
if ($billingPhone) {
    $quote_body .= '<tr><td>Tel: ' . htmlspecialchars($billingPhone) . '</td></tr>';
}
$quote_body .= '
    </table>
</div>
<div style="width:40%; float:right; text-align:right">
    <h4>Scope &amp; basis</h4>
    <table class="invtable table table-borderless" style="text-align:right">
        <tr><th>Scope</th><td>' . htmlspecialchars($scopeLabel) . '</td></tr>
        <tr><th>Basis</th><td>' . htmlspecialchars($sourceLabel) . '</td></tr>
    </table>
</div>
<div style="clear:both"></div>
<hr style="color:#2a3f54">';

// Items table
$quote_body .= '
<table class="invtable table">
    <thead>
        <tr>
            <th style="width:40%;">Description</th>
            <th style="width:10%;">Type</th>
            <th style="width:10%; text-align:right;">Qty</th>
            <th style="width:15%; text-align:right;">Unit price</th>
            <th style="width:10%; text-align:right;">Net</th>
            <th style="width:7%;  text-align:right;">VAT</th>
            <th style="width:8%;  text-align:right;">Gross</th>
        </tr>
    </thead>
    <tbody>';

if (empty($items)) {
    $quote_body .= '<tr><td colspan="7" style="text-align:center; font-size:9px;">No items defined.</td></tr>';
} else {
    foreach ($items as $it) {
        $quote_body .= '
        <tr>
            <td>' . htmlspecialchars($it['description']) . '</td>
            <td>' . htmlspecialchars($it['item_type']) . '</td>
            <td style="text-align:right;">' . htmlspecialchars($currency) . '' . number_format($it['qty'], 2) . '</td>
            <td style="text-align:right;">' . htmlspecialchars($currency) . '' . number_format($it['unit_price'], 2) . '</td>
            <td style="text-align:right;">' . htmlspecialchars($currency) . '' . number_format($it['net'], 2) . '</td>
            <td style="text-align:right;">' . htmlspecialchars($currency) . '' . number_format($it['vat'], 2) . '</td>
            <td style="text-align:right;">' . htmlspecialchars($currency) . '' . number_format($it['gross'], 2) . '</td>
        </tr>';
    }
}

$quote_body .= '
    </tbody>
</table>';

// Totals
$quote_body .= '
<div style="width:40%; float:right; margin-top:10px;">
    <table class="invtable table table-borderless" style="text-align:right">
        <tr>
            <th>Net total:</th>
            <td>' . htmlspecialchars($currency) . '' . number_format($netTotal, 2) . '</td>
        </tr>
        <tr>
            <th>VAT (' . number_format($vatrate, 1) . '%):</th>
            <td>' . htmlspecialchars($currency) . '' . number_format($vatTotal, 2) . '</td>
        </tr>
        <tr>
            <th>Gross total:</th>
            <td><strong>' . htmlspecialchars($currency) . '' . number_format($grossTotal, 2) . '</strong></td>
        </tr>
    </table>
</div>
<div style="clear:both"></div>';

// IU summary
$quote_body .= '
<h4 style="margin-top:20px;">Inspection Units summary</h4>
<table class="invtable table table-borderless" style="width:60%;">
    <tr><td>Minutes per IU</td><td style="text-align:right;">' . htmlspecialchars($currency) . '' . number_format($iuMinutesPerUnit, 0) . '</td></tr>
    <tr><td>Fee per IU</td><td style="text-align:right;">' . htmlspecialchars($currency) . '' . number_format($iuRatePerUnit, 2) . '</td></tr>
    <tr><td>Total IU</td><td style="text-align:right;">' . htmlspecialchars($currency) . '' . number_format($totalIU, 2) . '</td></tr>
    <tr><td>Total hours (IU × minutes / 60)</td><td style="text-align:right;">' . htmlspecialchars($currency) . '' . number_format($iuTotalHours, 2) . '</td></tr>
    <tr><td>Estimated IU fee</td><td style="text-align:right;">' . htmlspecialchars($currency) . '' . number_format($iuEstFee, 2) . '</td></tr>
</table>';

// Client-facing notes
if ($notesClient) {
    $quote_body .= '
    <h4 style="margin-top:20px;">Notes</h4>
    <div style="font-size:9px;">' . nl2br(htmlspecialchars($notesClient)) . '</div>';
}

$quote_body .= '
<div style="clear:both"></div>
</body>
</html>';

// Footer based on invoice footer template
$footer = file_get_contents('../../../' . TENANT_URL . '/engines/invoice_structure/footer_view.php');

// Content replacement (mirror invoice, but no QR for quotes)
if (file_exists('../../../' . TENANT_URL . '/images/company/logo.jpg')) {
    $header = str_replace('[LGO]', '<img src="../../../' . TENANT_URL . '/images/company/logo.jpg" height="50px" />', $header);
}
for ($i = 1; $i <= 6; $i++) {
    $tag = '[AF' . $i . ']';
    $img = '../../../' . TENANT_URL . '/images/company/afl_' . $i . '.jpg';
    if (file_exists($img)) {
        $header = str_replace($tag, '<td><img src="' . $img . '" width="50px" /></td>', $header);
    } else {
        $header = str_replace($tag, '', $header);
    }
}

// No QR image for quotes; strip placeholder
$footer = str_replace('[QCODE]', '', $footer);

// These helpers are already available in your system (same as invoice.php)
if (function_exists('getCompanyDetails')) {
    $footer = str_replace('[CNAME]', getCompanyDetails('name'), $footer);
    $footer = str_replace('[CBANK]', getCompanyDetails('bankName'), $footer);
    $footer = str_replace('[CACNO]', getCompanyDetails('accountNo'), $footer);
    $footer = str_replace('[CSCODE]', getCompanyDetails('sortCode'), $footer);
    $footer = str_replace('[WEB]', getCompanyDetails('web'), $footer);
}

// ---------------------------------------------------------------------
// mPDF output – mirror invoice.php (file output, no browser stream)
// ---------------------------------------------------------------------
require_once '../../packages/mpd/vendor/autoload.php';

// Save to tenant quotes folder
$path = "../../../" . TENANT_URL . "/quotes/";
if (!is_dir($path)) {
    @mkdir($path, 0775, true);
}

$filestore = $path . $quote['quote_ref'] . "_quote.pdf";

$mpdf = new \Mpdf\Mpdf([
    'setAutoTopMargin'    => 'stretch',
    'setAutoBottomMargin' => 'stretch',
    'mode'                => 'utf-8',
    'format'              => 'A4',
    'orientation'         => 'P'
]);

$mpdf->SetHTMLHeader($header);
$mpdf->WriteHTML($quote_body);
$mpdf->SetHTMLFooter($footer);
$mpdf->Output($filestore);

// Silent endpoint – no JSON needed; caller just regenerates the file