<?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();
requirePermission('finance.manage');

require_once __DIR__ . '/../../../config/database.php';

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

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

/* ===============================
FETCH INVOICE
================================ */

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

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

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

if(!$invoice){
    die("Invoice not found.");
}

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

$stmt = $pdo->prepare("
SELECT ii.*, p.product_name, p.sku, p.description
FROM invoice_items ii
LEFT JOIN inventory_products p ON ii.product_id = p.id
WHERE ii.invoice_id = ?
ORDER BY ii.line_order ASC
");

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

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

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

$document_title = "INVOICE";

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

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

$document_status = $invoice['payment_status'] ?? 'UNPAID';

$customer_label = "Bill To";
$details_label  = "Invoice Details";

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

$customer_city = '';
$customer_province = '';

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

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

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

$vat_display = '';

if($vat_total > 0){
    $vat_display = "R ".number_format($vat_total,2);
}

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

$note_text = "Thank you for doing business with EDM Solutions.";

$terms_text = "
<ul>
<li>Payment due within 7 days.</li>
<li>Installation scheduled after payment confirmation.</li>
<li>All equipment remains property of EDM Solutions until fully paid.</li>
</ul>
";

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

$items = [];

foreach($rawItems as $item){

    $items[] = [

        'product_name' => $item['product_name'] ?? $item['label'],
        'sku'          => $item['sku'] ?? '',
        'quantity'     => (float)($item['units'] ?? 0),
        'unit_price'   => (float)($item['rate'] ?? 0),
        'total'        => (float)($item['amount'] ?? 0),
        'description'  => $item['description'] ?? '',
        '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 HTML
================================ */

$html = ob_get_clean();

echo $html;