<?php
require('session-master.php');
require('functions.php');

if (!isset($_GET['id']) || empty($_GET['id'])) {
    die("Invalid invoice ID");
}

$getID = $_GET['id'];

// Connect DB
$mysqli = new mysqli(DATABASE_HOST, DATABASE_USER, DATABASE_PASS, DATABASE_NAME);
if ($mysqli->connect_error) {
    die('Error : (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}

/* --------------------------------------------
   FETCH INVOICE + CUSTOMER
-------------------------------------------- */
$query = "
    SELECT 
        i.*, 
        c.*, 
        (SELECT SUM(subtotal) FROM invoice_items WHERE invoice = i.invoice) AS real_subtotal,
        (SELECT COUNT(*) FROM invoice_items WHERE invoice = i.invoice) AS item_count
    FROM invoices i
    JOIN customers c ON c.invoice = i.invoice
    WHERE i.invoice = '" . $mysqli->real_escape_string($getID) . "'
    LIMIT 1
";

$result = $mysqli->query($query);
$invoice = $result->fetch_assoc();

if (!$invoice) {
    	echo "
        <script>
            alert('Invoice not found');
            window.location.href = 'invoice-list.php';
        </script>
        ";
        exit;
}

/* --------------------------------------------
   FETCH COMPANY INFO
-------------------------------------------- */
$company = getCompanyDetails($mysqli, $_SESSION['company_id']);
    $company_name    = $company['company_name'] ?? '';
    $currency        = $company['currency'] ?? '';
    $vat_rate        = $company['vat_rate'] ?? '';
    $invoice_prefix  = $company['invoice_prefix'] ?? '';
    $company_logo    = $company['company_logo'] ?? '';
    $target          = $company['year_target'] ?? '';
    $enable_vat      = $company['enable_vat'] ?? '';

/* --------------------------------------------
   LOAD LOGO
-------------------------------------------- */
$base64_logo = "";
$logo_path = "images/" . $company['company_logo'];

if (!empty($company['company_logo']) && file_exists($logo_path)) {
    $type = pathinfo($logo_path, PATHINFO_EXTENSION);
    $data = file_get_contents($logo_path);
    $base64_logo = 'data:image/' . $type . ';base64,' . base64_encode($data);
}

/* --------------------------------------------
   FETCH ITEMS
-------------------------------------------- */
$items = [];
$itemQuery = "
    SELECT * FROM invoice_items
    WHERE invoice = '" . $mysqli->real_escape_string($getID) . "'
    ORDER BY item_order ASC
";

$resItems = $mysqli->query($itemQuery);
while ($row = $resItems->fetch_assoc()) {
    $items[] = $row;
}

$mysqli->close();

/* --------------------------------------------
   OUTPUT HTML
-------------------------------------------- */
header('Content-Type: text/html; charset=UTF-8');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="icon" type="image/png" sizes="32x32" href="app-assets/favicon/inv.png">
<link rel="icon" type="image/png" sizes="16x16" href="app-assets/favicon/inv.png">

<title>Invoice - <?= htmlspecialchars($invoice['invoice']) ?></title>

<style>
body {
    font-family: DejaVu Sans, sans-serif;
    font-size: 13px;
    margin: 20px;
}

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

.table-clean td {
    padding: 6px 4px;
}

.table-summary {
    width: 100%;
    border-collapse: collapse;
    margin-top: 15px;
}

.table-summary th {
    background: #f0f0f0;
    padding: 8px;
    border-bottom: 2px solid #ccc;
}

.table-summary td {
    padding: 8px;
    border-bottom: 1px solid #eee;
}

.section-title {
    font-weight: bold;
    font-size: 14px;
    margin-bottom: 5px;
}

.total-box td {
    background: #000;
    color: #fff;
    font-weight: bold;
}

@media print {
    body { margin: 0; }
}


body {
    background: #f4f6f8;
    margin: 0;
    padding: 30px 0;
    font-family: DejaVu Sans, sans-serif;
}

/* Centered invoice card */
.invoice-wrapper {
    max-width: 850px;        /* A4-ish width */
    margin: auto;
    background: #fff;
    padding: 30px 35px;
    box-shadow: 0 8px 30px rgba(0,0,0,0.08);
    border-radius: 6px;
}

/* Print clean */
@media print {
    body {
        background: #fff;
        padding: 0;
    }

    .invoice-wrapper {
        box-shadow: none;
        border-radius: 0;
        padding: 0;
        max-width: 100%;
    }
}

/* =======================
   ACTION BUTTON BAR
======================= */
.action-bar {
    max-width: 850px;
    margin: 0 auto 15px auto;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 10px;
}

.action-left,
.action-right {
    display: flex;
    gap: 10px;
}

.action-btn {
    padding: 8px 14px;
    font-size: 13px;
    border-radius: 4px;
    border: none;
    cursor: pointer;
    text-decoration: none;
    font-weight: 500;
    display: inline-flex;
    align-items: center;
    gap: 6px;
}

.btn-back {
    background: #e5e7eb;
    color: #111;
}

.btn-download {
    background: #0d6efd;
    color: #fff;
}

.btn-share {
    background: #198754;
    color: #fff;
}

.action-btn:hover {
    opacity: 0.9;
}

/* Hide buttons when printing */
@media print {
    .action-bar {
        display: none;
    }
}

</style>
</head>

<body>
<div class="invoice-wrapper">
    <!-- ACTION BUTTONS -->
<div class="action-bar">
    <div class="action-left">
        <a href="javascript:history.back()" class="action-btn btn-back">
            ← Back
        </a>
    </div>

    <div class="action-right">
        <!-- Download PDF -->
        <a href="invoice-download.php?id=<?= urlencode($invoice['invoice']) ?>" 
           class="action-btn btn-download">
            ⬇ Download
        </a>

        <!-- Share -->
         <a href="invoice-share.php?id=<?= urlencode($invoice['invoice']) ?>" 
           class="action-btn btn-share">
            🔗 Share
        </a>
       
    </div>
</div>

<script>
function shareInvoice() {
    window.location.href = "invoice-share.php?id=<?= urlencode($invoice['invoice']) ?>";
}
</script>


<!-- WATERMARK -->
<?php if (!empty($invoice['status'])): ?>
<div style="
    position: fixed;
    top: 35%;
    left: 0;
    width: 100%;
    font-size: 120px;
    font-weight: bold;
    color: rgba(0,0,0,0.05);
    text-align: center;
    transform: rotate(-30deg);
    z-index: -1;
">
    <?= strtoupper(htmlspecialchars($invoice['status'])) ?>
</div>
<?php endif; ?>

<!-- HEADER -->
<table width="100%" style="margin-bottom: 20px;">
<tr>
    <td width="50%">
        <img src="images/<?php echo $company_logo?>" float="left" alt="" width="150px">
    </td>
    <td width="50%" align="right">
        <h1><?= strtoupper(htmlspecialchars($invoice['invoice_type'])) ?></h1>
    </td>
</tr>
</table>

<!-- SUMMARY -->
<table class="table-clean">
<tr>
    <td width="60%"></td>
    <td align="right"><b>Invoice No:</b></td>
    <td align="right"><?= htmlspecialchars($invoice['invoice']) ?></td>
</tr>
<tr>
    <td></td>
    <td align="right"><b>Billing Date:</b></td>
    <td align="right"><?= date("d M Y", strtotime($invoice['invoice_date'])) ?></td>
</tr>
<tr>
    <td></td>
    <td align="right"><b>Due Date:</b></td>
    <td align="right"><?= date("d M Y", strtotime($invoice['invoice_due_date'])) ?></td>
</tr>
<tr>
    <td></td>
    <td align="right"><b>Total Amount:</b></td>
    <td align="right">₦<?= number_format($invoice['total'], 2) ?></td>
</tr>
</table>

<br>

<!-- COMPANY + CUSTOMER -->
<table class="table-clean">
<tr>
    <td width="33%" valign="top">
        <div class="section-title">OUR DETAILS</div>
        <b><?= htmlspecialchars($company['company_name']) ?></b><br>
        <?= nl2br(htmlspecialchars($company['company_address'])) ?><br>
        <?= htmlspecialchars($company['company_town']) ?>, <?= htmlspecialchars($company['company_state']) ?><br>
        <?= htmlspecialchars($company['company_email']) ?><br>
        <?= htmlspecialchars($company['company_phone']) ?>
    </td>

    <td width="33%" valign="top">
        <div class="section-title">BILLING TO</div>
        <b><?= htmlspecialchars($invoice['name']) ?></b><br>
        <?= nl2br(htmlspecialchars($invoice['address_1'])) ?><br>
        <?= htmlspecialchars($invoice['town']) ?>, <?= htmlspecialchars($invoice['county']) ?><br>
        <?= htmlspecialchars($invoice['postcode']) ?>
    </td>

    <td width="33%" valign="top">
        <div class="section-title">PAY TO</div>
        Bank: <?= htmlspecialchars($company['bank_name']) ?><br>
        Account No: <?= htmlspecialchars($company['account_no']) ?><br>
        Account Name: <?= htmlspecialchars($company['account_name']) ?>
    </td>
</tr>
</table>

<br>

<!-- ITEMS -->
<table class="table-summary">
<thead>
<tr>
    <th>Description</th>
    <th width="10%">Qty</th>
    <th width="15%">Unit Price</th>
    <th width="15%">Total</th>
</tr>
</thead>

<tbody>
<?php foreach ($items as $item): ?>
<tr>
    <td>
        <b><?= htmlspecialchars($item['product']) ?></b><br>
        <span style="font-size:11px;">
            <?= htmlspecialchars($item['product_description']) ?>
        </span>
    </td>
    <td align="right"><?= (int)$item['qty'] ?></td>
    <td align="right"><?= number_format($item['price'], 2) ?></td>
    <td align="right"><?= number_format($item['subtotal'], 2) ?></td>
</tr>
<?php endforeach; ?>
</tbody>

<tfoot>
<tr>
    <td colspan="2"></td>
    <td align="right"><b>Subtotal</b></td>
    <td align="right"><?= number_format($invoice['subtotal'], 2) ?></td>
</tr>
<tr>
    <td colspan="2"></td>
    <td align="right"><b>Discount</b></td>
    <td align="right"><?= number_format($invoice['discount'], 2) ?></td>
</tr>
<tr>
    <td colspan="2"></td>
    <td align="right"><b>Tax</b></td>
    <td align="right"><?= number_format($invoice['vat'], 2) ?></td>
</tr>
<tr class="total-box">
    <td colspan="2"></td>
    <td align="right">TOTAL</td>
    <td align="right">₦<?= number_format($invoice['total'], 2) ?></td>
</tr>
</tfoot>
</table>

<br><br>

<b>NOTES</b>
<div style="font-size:12px;">
    <?= nl2br(htmlspecialchars($company['terms'])) ?>
</div>
</div>

<script>
function shareInvoice() {
    const url = window.location.href;

    if (navigator.share) {
        navigator.share({
            title: 'Invoice <?= addslashes($invoice['invoice']) ?>',
            url: url
        });
    } else {
        navigator.clipboard.writeText(url).then(() => {
            alert('Invoice link copied to clipboard');
        });
    }
}
</script>

</body>
</html>
