<?php
// ============================================================
//  member/invoice.php — view / download a Zoho invoice
// ============================================================
//
//  Single source of truth: invoices live in Zoho Books.
//  This page does not render an invoice from local data anymore.
//  It proxies the rendered version (HTML or PDF) that Zoho gives us.
//
//  Usage:
//    /member/invoice.php?id=123        → HTML preview (in iframe)
//    /member/invoice.php?id=123&pdf=1  → PDF download
//
//  Local invoice ID is what's in the URL — never the Zoho ID, so
//  we don't leak Zoho's internal IDs to the public.
//
//  Auth: members can view their OWN invoices. Admins can view ANY
//  invoice. We don't include the member _guard.php chrome because
//  this page renders its own iframe-based chrome.
// ============================================================

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/zoho.php';

$is_admin   = function_exists('auth_admin_check') && auth_admin_check();
$is_member  = function_exists('auth_member_check') && auth_member_check();

if (!$is_admin && !$is_member) {
    // Not logged in either way — send to member login (most common case).
    // Append next= so they come back after logging in.
    $next = urlencode($_SERVER['REQUEST_URI'] ?? '');
    header('Location: ' . SITE_URL . '/login.php?next=' . $next);
    exit;
}

$id      = (int)($_GET['id'] ?? 0);
$as_pdf  = !empty($_GET['pdf']);
$invoice = db_row('SELECT * FROM invoices WHERE id=:id', ['id'=>$id]);

if (!$invoice) { http_response_code(404); exit('Invoice not found.'); }

// Authorisation: members can only see their own; admins see all.
if (!$is_admin) {
    $member = auth_member_user();
    if (!$member || (int)$invoice['member_id'] !== (int)$member['id']) {
        http_response_code(403); exit('Access denied.');
    }
}

// Must have a Zoho invoice ID — if not, we can't show anything yet
if (empty($invoice['zoho_invoice_id'])) {
    $back_url = $is_admin ? '../admin/invoices.php' : 'welcome.php';
    $back_label = $is_admin ? '← Back to admin invoices' : '← Back to dashboard';
    ?><!DOCTYPE html>
    <html lang="en"><head>
    <meta charset="utf-8">
    <title>Invoice pending — Buy Local Lowveld</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    </head><body style="background:#f1f3f5;">
    <section class="section"><div class="container" style="max-width:560px;text-align:center;padding-top:4rem;">
        <h1 style="margin-bottom:.5rem;">Invoice pending</h1>
        <p>This invoice is being generated by our accounting system. It'll be available shortly — please check back in a few minutes.</p>
        <p>If it's still not showing after a while, please <a href="../contact.php">get in touch</a> and we'll sort it out.</p>
        <p style="margin-top:2rem;"><a href="<?= htmlspecialchars($back_url) ?>" class="btn"><?= htmlspecialchars($back_label) ?></a></p>
    </div></section>
    </body></html>
    <?php
    exit;
}

// Stream HTML inside an iframe via a tiny inline route, OR proxy as PDF.
// Both happen in this same file:
//   ?id=N           → wrapper page with iframe + toolbar (HTML view)
//   ?id=N&pdf=1     → streams the PDF binary
//   ?id=N&raw=1     → streams the raw HTML (used by the iframe src)
$mode = $as_pdf ? 'pdf' : (isset($_GET['raw']) ? 'raw' : 'wrapper');

if ($mode !== 'wrapper') {
    $accept   = ($mode === 'pdf') ? 'pdf' : 'html';
    $fetched  = zoho_fetch_invoice_raw($invoice['zoho_invoice_id'], $accept);

    if (!$fetched['ok']) {
        http_response_code(502);
        echo 'Could not fetch the invoice from accounting system. Please try again in a moment.';
        exit;
    }

    if ($mode === 'pdf') {
        $filename = 'BuyLocal-Invoice-' . preg_replace('/[^a-zA-Z0-9_-]/','', (string)$invoice['number']) . '.pdf';
        header('Content-Type: application/pdf');
        header('Content-Disposition: inline; filename="' . $filename . '"');
        header('Content-Length: ' . strlen($fetched['body']));
        echo $fetched['body'];
        exit;
    }

    // Raw HTML — let the browser render Zoho's invoice template
    header('Content-Type: ' . ($fetched['content_type'] ?: 'text/html; charset=UTF-8'));
    echo $fetched['body'];
    exit;
}

// Wrapper page with toolbar + iframe
$page_title = 'Invoice ' . ($invoice['number'] ?? '');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Invoice <?= htmlspecialchars($invoice['number'] ?? '') ?> — Buy Local Lowveld</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <style>
    body{background:#f1f3f5;margin:0;}
    .noprint-bar{background:#fff;border-bottom:1px solid var(--line);padding:.75rem 0;position:sticky;top:0;z-index:10;}
    .noprint-bar .row{display:flex;align-items:center;justify-content:space-between;padding:0 1.5rem;flex-wrap:wrap;gap:.75rem;}
    .noprint-bar a, .noprint-bar button{font-size:.9rem;}
    .inv-frame{
        max-width:900px;
        margin:1.5rem auto 3rem;
        background:#fff;
        border:1px solid var(--line);
        border-radius:8px;
        overflow:hidden;
        box-shadow:0 4px 16px rgba(0,0,0,.04);
    }
    .inv-frame iframe{
        width:100%;
        min-height:1000px;
        border:0;
        display:block;
    }
    @media print { .noprint-bar { display:none; } .inv-frame { border:0; box-shadow:none; max-width:none; margin:0; } }
    </style>
</head>
<body>

<div class="noprint-bar">
    <div class="row">
        <a href="<?= $is_admin ? '../admin/invoices.php' : 'welcome.php' ?>" style="color:var(--ink-muted);text-decoration:none;"><?= $is_admin ? '← Back to admin invoices' : '← Back to dashboard' ?></a>
        <div style="display:flex;gap:.5rem;flex-wrap:wrap;">
            <a href="?id=<?= $id ?>&pdf=1" class="btn">Download PDF</a>
            <button class="btn btn-outline" onclick="document.getElementById('inv-iframe').contentWindow.print()">Print</button>
        </div>
    </div>
</div>

<div class="inv-frame">
    <iframe id="inv-iframe" src="?id=<?= $id ?>&raw=1" title="Invoice"></iframe>
</div>

</body>
</html>