<?php
require_once __DIR__.'/includes/functions.php';
require_once __DIR__.'/includes/v291_payment_helpers.php';
require_once __DIR__.'/includes/v292_admin_portal_helpers.php';
mj292_ensure_schema();
$admin=current_admin(); $user=current_user();
if (!$admin && !$user) { redirect('login.php'); }
$invoiceId=(int)($_GET['invoice_id'] ?? $_GET['id'] ?? 0); $batchId=(int)($_GET['batch_id'] ?? 0); $receiptId=(int)($_GET['receipt_id'] ?? 0);
$data=mj292_invoice_data($invoiceId,$batchId,$receiptId); $invoice=$data['invoice']; $batch=$data['batch']; $receipt=$data['receipt']; $items=$data['items']; $billUser=$data['user'];
if (!$invoice && !$batch && !$receipt) { http_response_code(404); exit('Invoice not found.'); }
if (!$admin && $user && (int)$data['user_id'] !== (int)$user['id']) { http_response_code(403); exit('You cannot view this invoice.'); }
$invoiceNo=(string)($invoice['invoice_no'] ?? ($batch['batch_no'] ?? ('INV-'.($invoice['id'] ?? $batch['id'] ?? ''))));
$currency=(string)($invoice['currency_code'] ?? $batch['currency_code'] ?? $receipt['currency_code'] ?? setting('wallet_default_currency','SGD'));
$total=(float)($invoice['total_amount'] ?? $batch['total_amount'] ?? $receipt['amount'] ?? 0);
$paidStatus=(string)($invoice['status'] ?? $batch['status'] ?? $receipt['status'] ?? 'draft');
$receiptNo=(string)($receipt['receipt_no'] ?? '');
?><!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Invoice <?=e($invoiceNo)?></title><link rel="stylesheet" href="<?=e(asset_versioned('css/admin.css'))?>"><style>body{font-family:Arial,sans-serif;background:#f5f7fb;color:#111827}.wrap{max-width:900px;margin:24px auto;background:#fff;border-radius:18px;padding:36px;box-shadow:0 15px 40px rgba(15,23,42,.1)}.top{display:flex;justify-content:space-between;gap:20px;border-bottom:2px solid #e5e7eb;padding-bottom:20px}.brand h2,.title h1{margin:0}.muted{color:#6b7280}.box{border:1px solid #e5e7eb;border-radius:14px;padding:16px;margin:20px 0}.grid{display:grid;grid-template-columns:1fr 1fr;gap:18px}.table{width:100%;border-collapse:collapse}.table th,.table td{padding:12px;border-bottom:1px solid #e5e7eb;text-align:left}.table th{background:#f9fafb}.right{text-align:right!important}.badge{display:inline-block;padding:6px 12px;border-radius:999px;background:#eef2ff}.paid{background:#dcfce7}.pending{background:#fef3c7}.danger{background:#fee2e2}.actions{max-width:900px;margin:20px auto;text-align:right}.btn{display:inline-block;padding:10px 16px;border-radius:999px;background:#2563eb;color:#fff;text-decoration:none}.btn.secondary{background:#6b7280}@media print{body{background:#fff}.actions{display:none}.wrap{box-shadow:none;margin:0;max-width:none;border-radius:0}.badge{border:1px solid #ddd}.grid{grid-template-columns:1fr 1fr}}</style></head><body>
<div class="actions"><a href="javascript:history.back()" class="btn secondary">Back</a> <a href="javascript:window.print()" class="btn">Print Invoice</a></div>
<div class="wrap">
  <div class="top"><div class="brand"><h2><?=e(setting('invoice_seller_name', setting('site_name','MJ Marketplace')))?></h2><div class="muted"><?=nl2br(e(setting('invoice_seller_address','')))?><br><?=e(setting('invoice_seller_email',''))?></div></div><div class="title right"><h1>INVOICE</h1><h3><?=e($invoiceNo)?></h3><?=mj292_status_badge($paidStatus)?></div></div>
  <div class="grid"><div class="box"><b>Bill To</b><br><?=e($billUser['name'] ?? ('User #'.$data['user_id']))?><br><span class="muted"><?=e($billUser['email'] ?? '')?><br><?=e($billUser['mobile'] ?? '')?></span></div><div class="box"><b>Invoice Details</b><br>Date: <?=e(!empty($invoice['created_at']) ? date('d M Y',strtotime($invoice['created_at'])) : date('d M Y'))?><br>Status: <?=e(ucwords(str_replace('_',' ',$paidStatus)))?><br><?php if($receiptNo): ?>Receipt: <?=e($receiptNo)?><br><?php endif; ?>Payment Method: <?=e($receipt['payment_method'] ?? $batch['payment_method'] ?? $invoice['payment_method'] ?? '')?></div></div>
  <table class="table"><thead><tr><th>Description</th><th class="right">Qty</th><th class="right">Unit</th><th class="right">Total</th></tr></thead><tbody><?php if($items): foreach($items as $it): $qty=(int)($it['quantity']??1); $unit=(float)($it['unit_amount']??(($it['total_amount']??0)/max(1,$qty))); ?><tr><td><b><?=e($it['description'] ?? $it['item_label'] ?? ucwords(str_replace('_',' ',(string)($it['item_type']??'Item'))))?></b><br><span class="muted"><?=e(ucwords(str_replace('_',' ',(string)($it['item_type']??''))))?></span></td><td class="right"><?=e($qty)?></td><td class="right"><?=mj292_money0($unit,$currency)?></td><td class="right"><?=mj292_money0((float)($it['total_amount']??0),$currency)?></td></tr><?php endforeach; else: ?><tr><td>Marketplace invoice</td><td class="right">1</td><td class="right"><?=mj292_money0($total,$currency)?></td><td class="right"><?=mj292_money0($total,$currency)?></td></tr><?php endif; ?></tbody><tfoot><tr><th colspan="3" class="right">Subtotal</th><th class="right"><?=mj292_money0((float)($invoice['amount']??$batch['subtotal_amount']??$total),$currency)?></th></tr><?php if((float)($invoice['tax_amount']??$batch['tax_amount']??0)>0): ?><tr><th colspan="3" class="right"><?=e(setting('payment_cart_tax_label','GST/VAT'))?></th><th class="right"><?=mj292_money0((float)($invoice['tax_amount']??$batch['tax_amount']),$currency)?></th></tr><?php endif; ?><tr><th colspan="3" class="right">Total</th><th class="right"><?=mj292_money0($total,$currency)?></th></tr></tfoot></table>
  <div class="box"><b>Payment Note</b><br><span class="muted"><?php if(in_array(strtolower($paidStatus),['paid','approved','payment_verified'],true)): ?>Payment received. Receipt is generated automatically.<?php else: ?>Please follow admin-enabled payment instructions. Manual payment proof requires admin approval before services activate.<?php endif; ?></span></div>
  <p class="muted"><?=nl2br(e(setting('invoice_footer_note','Thank you for using MJ Marketplace.')))?></p>
</div></body></html>
