<?php
$page_title = 'Zoho Books Log';
require __DIR__ . '/_guard.php';
require_once __DIR__ . '/../includes/zoho.php';

// Test connection action
$test_result = null;
$retry_result = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    if (($_POST['do'] ?? '') === 'test') {
        $token = zoho_access_token();
        if ($token) {
            $r = zoho_request('GET', '/organizations');
            if ($r['ok']) {
                $orgs = $r['data']['organizations'] ?? [];
                $names = array_map(fn($o) => $o['name'] . ' (#' . $o['organization_id'] . ')', $orgs);
                $test_result = ['ok' => true, 'msg' => 'Connection works! Organisations: ' . implode(', ', $names)];
            } else {
                $test_result = ['ok' => false, 'msg' => 'API call failed (HTTP ' . $r['status'] . '). Check log below.'];
            }
        } else {
            $test_result = ['ok' => false, 'msg' => 'Could not obtain access token. Check credentials in config.'];
        }
    }
    if (($_POST['do'] ?? '') === 'retry_invoice') {
        $inv_id = (int)($_POST['invoice_id'] ?? 0);
        if ($inv_id > 0) {
            $r = zoho_record_payment_full($inv_id, $_POST['gateway'] ?? 'payfast');
            if ($r['ok']) {
                // Now that we have the Zoho invoice number, send the deferred
                // payment_received email that we held back when the original
                // ITN ran without Zoho available.
                $inv = db_row('SELECT * FROM invoices WHERE id=:id', ['id'=>$inv_id]);
                $member = $inv ? db_row('SELECT * FROM members WHERE id=:id', ['id'=>$inv['member_id']]) : null;
                if ($inv && $member && !empty($inv['number'])) {
                    require_once __DIR__ . '/../includes/mailer.php';
                    $amount_display = 'R ' . number_format(($inv['amount_cents'] ?? 0)/100, 2, '.', ' ');
                    $next_date = $member['renewal_date']
                        ? date('j F Y', strtotime($member['renewal_date']))
                        : date('j F Y', strtotime('+1 month'));

                    email_enqueue('payment_received', $member['email'],
                        trim($member['first_name'].' '.$member['last_name']),
                        [
                            'first_name'       => $member['first_name'],
                            'business_name'    => $member['business_name'],
                            'tier'             => $member['tier'],
                            'amount'           => $amount_display,
                            'invoice_number'   => $inv['number'],
                            'next_charge_date' => $next_date,
                        ]
                    );
                }
                $retry_result = ['ok'=>true, 'msg'=>"Sync OK for invoice #$inv_id (Zoho number {$r['invoice_number']})"];
            } else {
                $retry_result = ['ok'=>false, 'msg'=>"Sync still failing: " . ($r['error'] ?? 'unknown')];
            }
        }
    }
}

// Invoices that need Zoho attention — either a sync error was recorded,
// or the invoice has been paid but has no Zoho number assigned yet.
$failed_syncs = db_all(
    "SELECT i.*, m.email AS member_email, m.business_name
       FROM invoices i
       LEFT JOIN members m ON m.id = i.member_id
      WHERE i.status = 'paid'
        AND (i.number IS NULL OR i.zoho_sync_error IS NOT NULL)
        AND i.zoho_invoice_id IS NULL
      ORDER BY i.id DESC
      LIMIT 50"
);

$entries = db_all(
    'SELECT z.*, m.business_name, m.email AS member_email
       FROM zoho_log z
       LEFT JOIN members m ON m.id = z.member_id
       ORDER BY z.created_at DESC LIMIT 200'
);

$counts = [
    'total'  => (int)db_value('SELECT COUNT(*) FROM zoho_log'),
    'fail'   => (int)db_value('SELECT COUNT(*) FROM zoho_log WHERE success=0'),
    'today'  => (int)db_value("SELECT COUNT(*) FROM zoho_log WHERE created_at >= CURDATE()"),
];
?>

<style>
.atbl{width:100%;border-collapse:collapse;font-size:.84rem;}
.atbl th{padding:.55rem 1rem;background:var(--surface-alt);font-size:.7rem;text-transform:uppercase;letter-spacing:.05em;color:var(--ink-muted);border-bottom:2px solid var(--line);text-align:left;white-space:nowrap;}
.atbl td{padding:.55rem 1rem;border-bottom:1px solid var(--line);vertical-align:top;font-family:var(--font-sans);}
.atbl tbody tr:hover td{background:#fafafa;}
.zlog-status-ok{color:#16a34a;font-weight:700;}
.zlog-status-fail{color:#b91c1c;font-weight:700;}
.zlog-detail{font-family:ui-monospace,Menlo,monospace;font-size:.75rem;color:var(--ink-muted);max-width:520px;white-space:pre-wrap;word-break:break-all;}
.zlog-collapse{cursor:pointer;}
details summary{cursor:pointer;color:var(--brand-primary);font-size:.78rem;}
.cfg-badge{display:inline-block;padding:.2em .55em;font-size:.72rem;font-weight:700;border-radius:3px;}
.cfg-ok{background:#dcfce7;color:#166534;}
.cfg-bad{background:#fee2e2;color:#991b1b;}
</style>

<?php
$settings_section = 'zoho';
require __DIR__ . '/_settings_open.php';
?>

<div class="settings-page-head" style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:1rem;">
    <div>
        <h1>Zoho Books</h1>
        <p class="crumb">Audit trail of API calls + a test page.</p>
    </div>
    <div style="display:flex;gap:.5rem;">
        <form method="post" style="display:inline;">
            <?= csrf_field() ?>
            <input type="hidden" name="do" value="test">
            <button type="submit" class="btn">Test connection</button>
        </form>
    </div>
</div>

<!-- Config status row -->
<div class="card" style="margin-bottom:1rem;display:flex;gap:1rem;flex-wrap:wrap;align-items:center;">
    <strong style="font-size:.88rem;">Configuration:</strong>
    <span class="cfg-badge <?= zoho_is_configured() ? 'cfg-ok' : 'cfg-bad' ?>">
        <?= zoho_is_configured() ? '✓ Configured' : '✗ Missing values' ?>
    </span>
    <span class="muted" style="font-size:.82rem;">
        DC: <code><?= htmlspecialchars(defined('ZOHO_DC') ? ZOHO_DC : '?') ?></code> ·
        Org: <code><?= htmlspecialchars(defined('ZOHO_ORG_ID') ? ZOHO_ORG_ID : '?') ?></code> ·
        Total calls: <strong><?= number_format($counts['total']) ?></strong> ·
        Today: <strong><?= $counts['today'] ?></strong> ·
        Failed: <strong style="color:<?= $counts['fail']>0?'#b91c1c':'inherit' ?>;"><?= $counts['fail'] ?></strong>
    </span>
</div>

<?php if ($test_result): ?>
    <div class="alert <?= $test_result['ok']?'alert-success':'alert-error' ?>" style="margin-bottom:1rem;">
        <?= htmlspecialchars($test_result['msg']) ?>
    </div>
<?php endif; ?>

<?php if ($retry_result): ?>
    <div class="alert <?= $retry_result['ok']?'alert-success':'alert-error' ?>" style="margin-bottom:1rem;">
        <?= htmlspecialchars($retry_result['msg']) ?>
    </div>
<?php endif; ?>

<?php if (!empty($failed_syncs)): ?>
    <h2 style="margin:1.5rem 0 .5rem;font-size:1.05rem;">⚠ Invoices that need Zoho attention</h2>
    <p class="muted" style="margin:0 0 .75rem;font-size:.85rem;">
        Paid by the customer locally, but Zoho automation didn't complete. The customer hasn't received
        their receipt email yet — that goes out automatically when the sync succeeds. Most common cause:
        PayFast bank account not yet configured in <a href="payment-fees.php">Settings → Payment Fees</a>.
        Fix the cause, then click Retry.
    </p>
    <div class="card" style="padding:0;overflow:auto;margin-bottom:1.5rem;">
        <table class="atbl">
            <thead>
                <tr><th>Invoice</th><th>Member</th><th>Amount</th><th>Error</th><th></th></tr>
            </thead>
            <tbody>
            <?php foreach ($failed_syncs as $fs): ?>
                <tr>
                    <td>
                        <?php if (!empty($fs['number'])): ?>
                            <strong><?= htmlspecialchars($fs['number']) ?></strong>
                        <?php else: ?>
                            <span style="color:#b91c1c;font-weight:600;">No number yet</span>
                            <br><span class="muted" style="font-size:.7rem;">local id #<?= $fs['id'] ?></span>
                        <?php endif; ?>
                    </td>
                    <td><?= htmlspecialchars($fs['business_name'] ?? '') ?><br><span class="muted" style="font-size:.78rem;"><?= htmlspecialchars($fs['member_email'] ?? '') ?></span></td>
                    <td>R <?= number_format(($fs['amount_cents'] ?? 0)/100, 2) ?></td>
                    <td style="font-size:.78rem;color:#b91c1c;max-width:340px;">
                        <?= htmlspecialchars(mb_substr($fs['zoho_sync_error'] ?? '(no error logged — Zoho call may have crashed before being logged)', 0, 200)) ?>
                    </td>
                    <td style="text-align:right;white-space:nowrap;">
                        <form method="post" style="display:inline;">
                            <?= csrf_field() ?>
                            <input type="hidden" name="do" value="retry_invoice">
                            <input type="hidden" name="invoice_id" value="<?= $fs['id'] ?>">
                            <input type="hidden" name="gateway" value="payfast">
                            <button type="submit" style="background:none;border:none;color:var(--brand-primary);cursor:pointer;font-size:.85rem;font-family:inherit;">↻ Retry sync</button>
                        </form>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
<?php endif; ?>

<?php if (empty($entries)): ?>
    <div class="card"><p class="muted" style="margin:0;">No log entries yet. Click "Test connection" or sync a member to generate activity.</p></div>
<?php else: ?>
<div class="card" style="padding:0;overflow:auto;">
    <table class="atbl">
        <thead>
            <tr>
                <th>When</th>
                <th>Member</th>
                <th>Method</th>
                <th>Endpoint</th>
                <th style="text-align:center;">Status</th>
                <th>Note</th>
                <th style="width:240px;">Detail</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($entries as $e): ?>
            <tr>
                <td style="white-space:nowrap;font-size:.78rem;color:var(--ink-muted);">
                    <?= htmlspecialchars(date('j M H:i:s', strtotime($e['created_at']))) ?>
                </td>
                <td>
                    <?php if ($e['member_id']): ?>
                        <a href="member-edit.php?id=<?= $e['member_id'] ?>"><?= htmlspecialchars($e['business_name'] ?: $e['member_email']) ?></a>
                    <?php else: ?>
                        <span class="muted">—</span>
                    <?php endif; ?>
                </td>
                <td><code style="font-size:.78rem;"><?= htmlspecialchars($e['method']) ?></code></td>
                <td><code style="font-size:.78rem;"><?= htmlspecialchars($e['endpoint']) ?></code></td>
                <td style="text-align:center;">
                    <span class="<?= $e['success']?'zlog-status-ok':'zlog-status-fail' ?>">
                        <?= htmlspecialchars($e['http_status']) ?>
                    </span>
                </td>
                <td><?= htmlspecialchars($e['note'] ?? '') ?></td>
                <td>
                    <?php if (!empty($e['response'])): ?>
                        <details>
                            <summary>Response</summary>
                            <div class="zlog-detail"><?= htmlspecialchars(mb_substr($e['response'], 0, 1500)) ?></div>
                        </details>
                    <?php endif; ?>
                    <?php if (!empty($e['request'])): ?>
                        <details>
                            <summary>Request</summary>
                            <div class="zlog-detail"><?= htmlspecialchars(mb_substr($e['request'], 0, 1500)) ?></div>
                        </details>
                    <?php endif; ?>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>
<p class="muted" style="font-size:.8rem;margin:.5rem 0 0;">Showing latest <?= count($entries) ?> entries.</p>
<?php endif; ?>

<?php require __DIR__ . '/_settings_close.php'; ?>

<?php require __DIR__ . '/_footer.php'; ?>