<?php
// ============================================================
//  member/view-statement.php — customer statement
// ============================================================
//
//  Pulls invoices + customer payments + credit notes from Zoho
//  Books for the logged-in member's contact, computes a running
//  balance, and renders a print-ready statement.
//
//  Auth: members see their OWN. Admins can use ?member_id=N.
//  Print: browser's native print works directly (no iframe).
// ============================================================

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) {
    $next = urlencode($_SERVER['REQUEST_URI'] ?? '');
    header('Location: ' . SITE_URL . '/login.php?next=' . $next);
    exit;
}

// Resolve which member's statement to show
$member = null;
if ($is_admin && !empty($_GET['member_id'])) {
    $member = db_row('SELECT * FROM members WHERE id=:id', ['id' => (int)$_GET['member_id']]);
} elseif ($is_member) {
    $member = auth_member_user();
}
if (!$member) {
    http_response_code(404);
    exit('Member not found.');
}

// Date range — default to current calendar month (first of month → today's last day of month)
$from_date = $_GET['from'] ?? date('Y-m-01');
$to_date   = $_GET['to']   ?? date('Y-m-t');
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $from_date)) $from_date = date('Y-m-01');
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $to_date))   $to_date   = date('Y-m-t');

$back_url   = $is_admin ? '../admin/member-edit.php?id=' . (int)$member['id'] : 'welcome.php';
$back_label = $is_admin ? '← Back to member' : '← Back to dashboard';

// If the member isn't linked to a Zoho contact, show a friendly empty state
if (empty($member['zoho_contact_id'])) {
    ?><!DOCTYPE html>
    <html lang="en"><head>
    <meta charset="utf-8">
    <title>Statement 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;">No statement yet</h1>
        <p>Your statement will be available here once your first payment has been processed.</p>
        <p style="margin-top:2rem;"><a href="<?= htmlspecialchars($back_url) ?>" class="btn"><?= htmlspecialchars($back_label) ?></a></p>
    </div></section>
    </body></html>
    <?php
    exit;
}

// Pull data from Zoho
$data = zoho_get_statement_data((string)$member['zoho_contact_id'], $from_date, $to_date);

// Build an in-memory map of zoho invoice ID → local invoice ID so the View
// link points at our /member/invoice.php proxy (which respects auth)
$z_ids = [];
foreach (($data['rows'] ?? []) as $r) {
    if ($r['type'] === 'invoice' && !empty($r['zoho_id'])) $z_ids[] = $r['zoho_id'];
}
$local_map = [];
if ($z_ids) {
    $placeholders = implode(',', array_fill(0, count($z_ids), '?'));
    $rows = db_all(
        "SELECT id, zoho_invoice_id FROM invoices
          WHERE member_id = ? AND zoho_invoice_id IN ($placeholders)",
        array_merge([(int)$member['id']], array_values($z_ids))
    );
    foreach ($rows as $r) $local_map[$r['zoho_invoice_id']] = (int)$r['id'];
}

function fmt_money($v): string {
    return 'R&nbsp;' . number_format((float)$v, 2, '.', ',');
}
function fmt_date(string $iso): string {
    if (!$iso) return '';
    $t = strtotime($iso);
    return $t ? date('j M Y', $t) : $iso;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Statement — Buy Local Lowveld</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <style>
    body{background:#f1f3f5;margin:0;color:#1a1a1a;}
    .noprint-bar{background:#fff;border-bottom:1px solid var(--line);padding:.4rem 0;position:sticky;top:0;z-index:10;}
    .noprint-bar .row{display:flex;align-items:center;justify-content:space-between;padding:0 1rem;flex-wrap:wrap;gap:.5rem;}
    .noprint-bar a{font-size:.82rem;}
    .noprint-bar .btn{padding:.35rem .75rem;font-size:.78rem;}
    .date-form{
        display:flex;
        gap:2.35rem;
        align-items:stretch;
        font-size:.78rem;
        flex-wrap:nowrap;
        flex-direction:row;
        justify-content:space-evenly;
        align-content:space-around;
    }
    .date-form label{color:var(--ink-muted);}
    .date-form input[type=date]{padding:.25rem .45rem;border:1px solid var(--line);border-radius:5px;font-size:.78rem;background:#fff;}
    .date-form .btn{padding:.3rem .65rem;font-size:.75rem;}

    .stmt-paper{
        max-width:1000px;
        margin:1.5rem auto 3rem;
        background:#fff;
        border:1px solid var(--line);
        border-radius:8px;
        box-shadow:0 4px 16px rgba(0,0,0,.04);
        padding:2.5rem;
    }
    .stmt-head{
        display:flex;
        justify-content:space-between;
        align-items:flex-start;
        flex-wrap:wrap;
        gap:1.5rem;
        margin-bottom:2rem;
        padding-bottom:1.5rem;
        border-bottom:2px solid #1a1a1a;
    }
    .stmt-head .org h1{margin:0 0 .35rem;font-family:Georgia, serif;font-size:1.8rem;}
    .stmt-head .org p{margin:0;font-size:.85rem;color:#555;}
    .stmt-head .meta{text-align:right;font-size:.85rem;}
    .stmt-head .meta .lbl{color:#888;text-transform:uppercase;letter-spacing:.05em;font-size:.7rem;}
    .stmt-head .meta .val{font-weight:600;font-size:.95rem;margin-bottom:.5rem;}

    .bill-to{margin-bottom:1.75rem;}
    .bill-to .lbl{color:#888;text-transform:uppercase;letter-spacing:.05em;font-size:.7rem;}
    .bill-to .val{font-weight:600;font-size:1rem;margin-top:.15rem;}
    .bill-to .sub{color:#555;font-size:.85rem;}

    .stmt-summary{
        display:flex;
        gap:1rem;
        margin-bottom:1.5rem;
        flex-wrap:wrap;
    }
    .stmt-summary .stat{
        flex:1;min-width:140px;
        background:#fafaf8;
        border:1px solid var(--line);
        border-radius:6px;
        padding:.75rem 1rem;
    }
    .stmt-summary .stat .lbl{font-size:.7rem;color:#888;text-transform:uppercase;letter-spacing:.05em;}
    .stmt-summary .stat .val{font-size:1.15rem;font-weight:700;margin-top:.1rem;}

    .stmt-tbl{width:100%;border-collapse:collapse;font-size:.85rem;}
    .stmt-tbl th{padding:.55rem .65rem;background:#fafaf8;font-size:.7rem;text-transform:uppercase;letter-spacing:.05em;color:#666;border-bottom:2px solid var(--line);text-align:left;white-space:nowrap;}
    .stmt-tbl th.r{text-align:right;}
    .stmt-tbl td{padding:.65rem;border-bottom:1px solid #eee;vertical-align:top;}
    .stmt-tbl td.r{text-align:right;white-space:nowrap;font-variant-numeric:tabular-nums;}
    .stmt-tbl tr.opening td{background:#fafaf8;font-style:italic;color:#666;}
    .stmt-tbl tr.closing td{background:#1a1a1a;color:#fff;font-weight:700;}
    .stmt-tbl tr.closing td.r{font-size:1rem;}
    .stmt-tbl tr:hover td{background:#fcfcfc;}
    .row-type{display:inline-block;padding:.1em .45em;border-radius:3px;font-size:.65rem;font-weight:700;text-transform:uppercase;letter-spacing:.04em;}
    .row-type-invoice{background:#dbeafe;color:#1e40af;}
    .row-type-payment{background:#dcfce7;color:#166534;}
    .row-type-credit_note{background:#fef3c7;color:#92400e;}

    .stmt-foot{margin-top:2rem;padding-top:1rem;border-top:1px solid #eee;color:#888;font-size:.78rem;text-align:center;}

    .empty{padding:2rem;text-align:center;color:#888;}

    @media print {
        body{background:#fff;}
        .noprint-bar{display:none;}
        .stmt-paper{margin:0;border:none;box-shadow:none;border-radius:0;padding:1.5rem;max-width:none;}
        .stmt-tbl tr.closing td{background:#000;}
    }
    </style>
</head>
<body>

<div class="noprint-bar">
    <div class="row">
        <a href="<?= htmlspecialchars($back_url) ?>" style="color:var(--ink-muted);text-decoration:none;">
            <?= htmlspecialchars($back_label) ?>
        </a>

        <form class="date-form" method="get">
            <?php if ($is_admin): ?>
                <input type="hidden" name="member_id" value="<?= (int)$member['id'] ?>">
            <?php endif; ?>
            <label for="from-date" style="color:var(--ink-muted);">From</label>
            <input type="date" id="from-date" name="from" value="<?= htmlspecialchars($from_date) ?>">
            <label for="to-date" style="color:var(--ink-muted);">to</label>
            <input type="date" id="to-date"   name="to"   value="<?= htmlspecialchars($to_date) ?>">
            <button type="submit" class="btn btn-outline">Update</button>
        </form>

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

<div class="stmt-paper">
    <div class="stmt-head">
        <div class="org">
            <h1>Customer Statement</h1>
            <p>Buy Local Lowveld NPC<br>buylocallowveld.co.za</p>
        </div>
        <div class="meta">
            <div class="lbl">Statement period</div>
            <div class="val"><?= htmlspecialchars(fmt_date($from_date)) ?> to <?= htmlspecialchars(fmt_date($to_date)) ?></div>
            <div class="lbl">Generated</div>
            <div class="val"><?= htmlspecialchars(date('j M Y')) ?></div>
        </div>
    </div>

    <div class="bill-to">
        <div class="lbl">Statement for</div>
        <div class="val"><?= htmlspecialchars($member['business_name'] ?? trim($member['first_name'].' '.$member['last_name'])) ?></div>
        <div class="sub">
            <?= htmlspecialchars(trim($member['first_name'].' '.$member['last_name'])) ?><br>
            <?= htmlspecialchars($member['email']) ?>
            <?= !empty($member['phone']) ? ' · ' . htmlspecialchars($member['phone']) : '' ?>
        </div>
    </div>

    <?php if (!$data['ok']): ?>
        <div class="empty">
            <p><strong>Couldn't load statement data.</strong></p>
            <p style="font-size:.85rem;"><?= htmlspecialchars($data['error'] ?? '') ?></p>
        </div>
    <?php elseif (empty($data['rows'])): ?>
        <div class="empty">
            <p>No transactions in this period.</p>
            <p style="font-size:.85rem;">Try adjusting the date range above to see earlier activity.</p>
        </div>
    <?php else: ?>

        <div class="stmt-summary">
            <div class="stat">
                <div class="lbl">Total invoiced</div>
                <div class="val"><?= fmt_money($data['totals']['invoiced']) ?></div>
            </div>
            <div class="stat">
                <div class="lbl">Total paid</div>
                <div class="val" style="color:#166534;"><?= fmt_money($data['totals']['paid']) ?></div>
            </div>
            <?php if ($data['totals']['credited'] > 0): ?>
                <div class="stat">
                    <div class="lbl">Credit notes</div>
                    <div class="val" style="color:#92400e;"><?= fmt_money($data['totals']['credited']) ?></div>
                </div>
            <?php endif; ?>
            <div class="stat" style="<?= $data['closing_balance'] > 0.005 ? 'background:#fef2f2;border-color:#fca5a5;' : '' ?>">
                <div class="lbl">Closing balance</div>
                <div class="val" style="<?= $data['closing_balance'] > 0.005 ? 'color:#991b1b;' : '' ?>">
                    <?= fmt_money($data['closing_balance']) ?>
                </div>
            </div>
        </div>

        <table class="stmt-tbl">
            <thead>
                <tr>
                    <th>Date</th>
                    <th>Type</th>
                    <th>Reference</th>
                    <th>Description</th>
                    <th class="r">Debit</th>
                    <th class="r">Credit</th>
                    <th class="r">Balance</th>
                </tr>
            </thead>
            <tbody>
                <?php if (abs($data['opening_balance']) > 0.005): ?>
                    <tr class="opening">
                        <td><?= htmlspecialchars(fmt_date($from_date)) ?></td>
                        <td colspan="3">Opening balance</td>
                        <td class="r"></td>
                        <td class="r"></td>
                        <td class="r"><?= fmt_money($data['opening_balance']) ?></td>
                    </tr>
                <?php endif; ?>

                <?php foreach ($data['rows'] as $r):
                    $local_id = ($r['type']==='invoice' && !empty($r['zoho_id']) && isset($local_map[$r['zoho_id']]))
                        ? $local_map[$r['zoho_id']] : null;
                ?>
                    <tr>
                        <td><?= htmlspecialchars(fmt_date($r['date'])) ?></td>
                        <td><span class="row-type row-type-<?= htmlspecialchars($r['type']) ?>"><?= htmlspecialchars(str_replace('_', ' ', $r['type'])) ?></span></td>
                        <td>
                            <?php if ($local_id): ?>
                                <a href="invoice.php?id=<?= $local_id ?>" target="_blank"><strong><?= htmlspecialchars($r['number']) ?></strong></a>
                            <?php else: ?>
                                <strong><?= htmlspecialchars($r['number']) ?></strong>
                            <?php endif; ?>
                        </td>
                        <td><?= htmlspecialchars($r['description']) ?></td>
                        <td class="r"><?= $r['debit']  > 0 ? fmt_money($r['debit'])  : '' ?></td>
                        <td class="r"><?= $r['credit'] > 0 ? fmt_money($r['credit']) : '' ?></td>
                        <td class="r"><?= fmt_money($r['balance']) ?></td>
                    </tr>
                <?php endforeach; ?>

                <tr class="closing">
                    <td colspan="6">Closing balance as of <?= htmlspecialchars(fmt_date($to_date)) ?></td>
                    <td class="r"><?= fmt_money($data['closing_balance']) ?></td>
                </tr>
            </tbody>
        </table>

    <?php endif; ?>

    <div class="stmt-foot">
        Live data from Zoho Books · Generated <?= date('j M Y H:i') ?>
    </div>
</div>

</body>
</html>