<?php

/* ===============================
ERROR DISPLAY
================================ */

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';

$company_id = $_SESSION['company_id'] ?? 0;
$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 = ?
AND i.company_id = ?
");

$stmt->execute([$id,$company_id]);
$invoice = $stmt->fetch(PDO::FETCH_ASSOC);

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

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

$stmt = $pdo->prepare("
SELECT *
FROM invoice_items
WHERE invoice_id = ?
ORDER BY line_order ASC
");

$stmt->execute([$id]);
$items = $stmt->fetchAll(PDO::FETCH_ASSOC);


/* ===============================
FETCH PAYMENTS (NEW)
================================ */

$stmt = $pdo->prepare("
SELECT *
FROM invoice_payments
WHERE invoice_id = ?
AND company_id = ?
ORDER BY created_at DESC
");

$stmt->execute([$id,$company_id]);
$payments = $stmt->fetchAll(PDO::FETCH_ASSOC);


/* ===============================
PAYMENT STATUS HELPER
================================ */

$paymentStatus = strtoupper($invoice['payment_status'] ?? 'UNPAID');

/* ===============================
LAYOUT
================================ */

$breadcrumb = "Invoice View";
require_once __DIR__ . '/../../../includes/layout.php';

?>

<style>

.invoice-header{
display:flex;
justify-content:space-between;
margin-bottom:30px;
flex-wrap:wrap;
gap:20px;
}

.invoice-company{
font-size:14px;
line-height:1.6;
}

.invoice-title{
font-size:26px;
font-weight:600;
color:#f2531e;
}

.invoice-meta{
text-align:right;
font-size:14px;
}

.invoice-actions{
margin-bottom:20px;
display:flex;
flex-wrap:wrap;
gap:10px;
}

.customer-box{
border:1px solid #e5e7eb;
padding:15px;
margin-bottom:25px;
border-radius:6px;
background:#fafafa;
}

.table-wrap table{
width:100%;
border-collapse:collapse;
}

.table-wrap th{
background:#111827;
color:#fff;
padding:12px;
text-align:left;
}

.table-wrap td{
padding:10px;
border-bottom:1px solid #e5e7eb;
vertical-align:top;
}

.totals-box{
margin-top:30px;
width:320px;
margin-left:auto;
border:1px solid #e5e7eb;
padding:15px;
border-radius:6px;
background:#fafafa;
}

.totals-box div{
display:flex;
justify-content:space-between;
margin-bottom:8px;
}

.totals-box .grand{
font-weight:700;
font-size:18px;
border-top:1px solid #ddd;
padding-top:10px;
}

.status-badge{
padding:4px 10px;
border-radius:4px;
font-size:12px;
font-weight:600;
background:#e5e7eb;
display:inline-block;
}

.payment-table{
margin-top:40px;
}

</style>

<div class="container">

<!-- ===============================
INVOICE HEADER
================================ -->

<div class="invoice-header">

<div class="invoice-company">

<strong>EDM Solutions</strong><br>
Smart Metering. Simplified.<br>
info@edmsolutions.co.za<br>
www.edmsolutions.co.za

</div>

<div class="invoice-meta">

<div class="invoice-title">
Invoice <?= htmlspecialchars($invoice['invoice_number'] ?: ('INV-' . str_pad($invoice['id'],5,"0",STR_PAD_LEFT))) ?>
</div>

Created <?= date("d M Y",strtotime($invoice['created_at'])) ?>

<?php if(!empty($invoice['quote_id'])): ?>

<br>
Quote Ref: Q-<?= str_pad($invoice['quote_id'],5,"0",STR_PAD_LEFT) ?>

<?php endif; ?>

<br><br>

<span class="status-badge">
<?= htmlspecialchars($paymentStatus) ?>
</span>

</div>

</div>

<!-- ===============================
CUSTOMER
================================ -->

<div class="customer-box">

<strong>Customer</strong><br><br>

<?= htmlspecialchars($invoice['company_name'] ?? '') ?><br>
<?= htmlspecialchars($invoice['email'] ?? '') ?><br>
<?= htmlspecialchars($invoice['phone'] ?? '') ?><br>
<?= nl2br(htmlspecialchars($invoice['address'] ?? '')) ?>

</div>

<!-- ===============================
ACTIONS
================================ -->

<div class="invoice-actions">

<a class="btn" href="index.php">← Back</a>

<?php if(!empty($invoice['quote_id'])): ?>
<a class="btn" href="../quotations/view.php?id=<?= (int)$invoice['quote_id'] ?>">
View Quote
</a>
<?php endif; ?>

<a class="btn" href="preview.php?id=<?= (int)$invoice['id'] ?>">
Preview
</a>

<a class="btn" href="pdf.php?id=<?= (int)$invoice['id'] ?>" target="_blank">
Download PDF
</a>

<button onclick="window.print()" class="btn">
Print
</button>

<?php if($invoice['balance'] <= 0): ?>

<div style="margin-top:10px;padding:10px;background:#e8f7ee;border:1px solid #b6e3c6;border-radius:6px;">
Invoice fully paid. Any corrections must be done via Credit Note.
</div>

<?php endif; ?>

</div>

<!-- ===============================
ITEM TABLE
================================ -->

<div class="table-wrap">

<table>

<thead>
<tr>
<th style="width:60px">#</th>
<th>Description</th>
<th style="width:120px">Units</th>
<th style="width:140px">Rate</th>
<th style="width:160px">Amount</th>
</tr>
</thead>

<tbody>

<?php if(!$items): ?>

<tr>
<td colspan="5">No invoice items found.</td>
</tr>

<?php else: ?>

<?php foreach($items as $i => $item): ?>

<tr>

<td><?= $i+1 ?></td>

<td><?= htmlspecialchars($item['label'] ?? '') ?></td>

<td><?= number_format((float)($item['units'] ?? 0),2) ?></td>

<td>R <?= number_format((float)($item['rate'] ?? 0),2) ?></td>

<td>R <?= number_format((float)($item['amount'] ?? 0),2) ?></td>

</tr>

<?php endforeach; ?>

<?php endif; ?>

</tbody>

</table>

</div>

<!-- ===============================
TOTALS
================================ -->

<div class="totals-box">

<div>
<span>Subtotal</span>
<span>R <?= number_format((float)($invoice['subtotal'] ?? 0),2) ?></span>
</div>

<div>
<span>VAT</span>
<span>
<?php if(!empty($invoice['vat_enabled'])): ?>
R <?= number_format((float)($invoice['vat_total'] ?? 0),2) ?>
<?php else: ?>
Not Applied
<?php endif; ?>
</span>
</div>

<div>
<span>Total</span>
<span>R <?= number_format((float)($invoice['total'] ?? 0),2) ?></span>
</div>

<div>
<span>Paid</span>
<span>R <?= number_format((float)($invoice['paid_total'] ?? 0),2) ?></span>
</div>

<div>
<span>Balance</span>
<span>R <?= number_format((float)($invoice['balance'] ?? 0),2) ?></span>
</div>

<div class="grand">
<span>Status</span>
<span><?= htmlspecialchars($paymentStatus) ?></span>
</div>

</div>


<!-- ===============================
PAYMENT HISTORY (NEW)
================================ -->

<?php if(!empty($payments)): ?>

<div class="payment-table table-wrap">

<h3 style="margin-top:40px;">Payment History</h3>

<table>

<thead>
<tr>
<th style="width:160px;">Date</th>
<th style="width:140px;">Method</th>
<th>Reference</th>
<th style="width:160px;">Amount</th>
</tr>
</thead>

<tbody>

<?php foreach($payments as $pay): ?>

<tr>

<td>
<?= date("d M Y",strtotime($pay['created_at'])) ?>
</td>

<td>
<?= htmlspecialchars($pay['payment_method']) ?>
</td>

<td>
<?= htmlspecialchars($pay['reference'] ?? '-') ?>
</td>

<td>
R <?= number_format((float)$pay['amount'],2) ?>
</td>

</tr>

<?php endforeach; ?>

</tbody>

</table>

</div>

<?php endif; ?>

</div>

<?php require_once __DIR__ . '/../../../includes/layout_footer.php'; ?>