<?php

ob_start();

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

require_once __DIR__ . '/../../../includes/auth.php';
requireLogin();

require_once __DIR__ . '/../../../config/database.php';
require_once __DIR__ . '/../../../libs/dompdf/vendor/autoload.php';

use Dompdf\Dompdf;

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if(!$id){
    die("Invalid quotation ID.");
}

/* ===============================
FETCH QUOTATION
================================ */

$stmt = $pdo->prepare("
SELECT q.*, c.company_name, c.email, c.phone, c.address, c.city, c.province
FROM quotations q
LEFT JOIN companies c ON q.customer_id = c.id
WHERE q.id = ?
");

$stmt->execute([$id]);

$quote = $stmt->fetch(PDO::FETCH_ASSOC);

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

/* ===============================
FETCH ITEMS
================================ */

$stmt = $pdo->prepare("
SELECT *
FROM quotation_items
WHERE quotation_id = ?
ORDER BY id ASC
");

$stmt->execute([$id]);

$rawItems = $stmt->fetchAll(PDO::FETCH_ASSOC);

/* ===============================
DOCUMENT VARIABLES
================================ */

$document_title  = "QUOTATION";

$document_number = !empty($quote['quote_number'])
    ? $quote['quote_number']
    : "QT-" . date("Y") . "-" . str_pad($quote['id'],5,"0",STR_PAD_LEFT);

$document_date = !empty($quote['quote_date'])
    ? date("d M Y",strtotime($quote['quote_date']))
    : '';

$document_status = $quote['status'] ?? '';

$customer_label = "Customer";
$details_label  = "Quote Details";

$customer_name    = $quote['company_name'] ?? '';
$customer_email   = $quote['email'] ?? '';
$customer_phone   = $quote['phone'] ?? '';
$customer_address = $quote['address'] ?? '';

$customer_city     = $quote['city'] ?? '';
$customer_province = $quote['province'] ?? '';

$details_content = "
Quote #: ".$document_number."<br>
Date: ".$document_date."<br>
Status: ".$document_status;

if(!empty($quote['valid_until'])){
    $details_content .= "<br>Valid Until: ".date("d M Y",strtotime($quote['valid_until']));
}

/* ===============================
TOTALS
================================ */

$subtotal  = (float)($quote['subtotal'] ?? 0);
$vat_total = (float)($quote['vat_total'] ?? 0);
$total     = (float)($quote['total'] ?? 0);

$vat_display = '';

if(!empty($quote['vat_enabled']) && $vat_total > 0){
    $vat_display = "R ".number_format($vat_total,2);
}

/* ===============================
NOTES + TERMS
================================ */

$note_text = "Thank you for considering EDM Solutions for your smart metering requirements.";

$terms_text = "
<ul>
<li>This quotation is valid for 30 days.</li>
<li>Payment may be required prior to installation.</li>
<li>Any work outside the quoted scope will be charged separately.</li>
</ul>
";

/* ===============================
NORMALIZE ITEMS
================================ */

$items = [];

foreach($rawItems as $item){

    $items[] = [

        'product_name' => $item['product_name'] ?? '',
        'sku'          => $item['sku'] ?? '',
        'quantity'     => (float)($item['quantity'] ?? 0),
        'unit_price'   => (float)($item['unit_price'] ?? 0),
        'total'        => (float)($item['total'] ?? 0),
        'description'  => $item['description'] ?? '',
        'item_comment' => $item['item_comment'] ?? ''

    ];
}

/* ===============================
LOGO
================================ */

$logoPath = __DIR__.'/../../../assets/logo.png';

$logo = '';

if(file_exists($logoPath)){

$type = pathinfo($logoPath,PATHINFO_EXTENSION);
$data = file_get_contents($logoPath);

$logo = 'data:image/'.$type.';base64,'.base64_encode($data);

}

/* ===============================
LOAD TEMPLATE
================================ */

require __DIR__ . '/../../../templates/document.php';

/* ===============================
RENDER PDF
================================ */

$html = ob_get_clean();

$dompdf = new Dompdf();

$dompdf->loadHtml($html);
$dompdf->setPaper('A4','portrait');
$dompdf->render();

$dompdf->stream(
    "Quotation-" . $quote['quote_number'] . ".pdf",
    ["Attachment" => false]
);