<?php
/**
 * REVENDA — Admin Manual Payment Verification Console
 * @version 3.0.0
 * Path: /pages/admin/payments.php
 * Route: ?page=admin-payments
 *
 * Approves/rejects manual payment attempts (bank transfer, PayPal, Wise,
 * Airtm, mobile money, etc.) for both property bookings and tour bookings.
 * Routes approved payments through PaymentService::markPaid() so that
 * confirmation emails fire correctly for the right booking type.
 */

if (!defined('APP_START')) { http_response_code(403); exit('Direct access denied'); }
if (!isAdmin()) { setMessage('Admin access required', 'error'); redirect('/?page=dashboard'); exit; }

$db  = db();
$now = date('Y-m-d H:i:s');

$flash     = null;
$flashType = 'success';

// ============================================================
// HANDLE APPROVE / REJECT
// ============================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['admin_payment_action'])) {
    $action    = (string)$_POST['admin_payment_action'];
    $attemptId = (int)($_POST['attempt_id'] ?? 0);
    $note      = trim((string)($_POST['admin_note'] ?? ''));

    if ($attemptId > 0) {
        $attempt = $db->fetchOne("SELECT * FROM payment_attempts WHERE id = ? LIMIT 1", [$attemptId]);

        if (!$attempt) {
            $flash = 'Payment attempt not found.';
            $flashType = 'error';
        } elseif ($action === 'approve') {
            try {
                $db->query(
                    "UPDATE payment_attempts
                     SET status = 'paid', paid_at = NOW(), callback_payload = ?
                     WHERE id = ?",
                    [
                        json_encode([
                            'admin_note'  => $note,
                            'verified_by' => (int)$_SESSION['user_id'],
                            'verified_at' => $now,
                        ]),
                        $attemptId,
                    ]
                );

                $bookingId   = (int)($attempt['booking_id'] ?? 0);
                $bookingType = strtolower((string)($attempt['booking_type'] ?? 'property'));
                if (!in_array($bookingType, ['property', 'tour', 'event'], true)) {
                    $bookingType = 'property';
                }

                // Route through PaymentService so emails fire correctly
                if (function_exists('payment_service') && !empty($attempt['reference'])) {
                    try {
                        payment_service()->markPaid((string)$attempt['reference'], [
                            'admin_approved' => true,
                            'admin_id'       => (int)$_SESSION['user_id'],
                        ]);
                    } catch (Throwable $e) {
                        error_log('admin payments markPaid: ' . $e->getMessage());
                    }
                }

                // Fallback direct update in case PaymentService did not run
                if ($bookingId > 0) {
                    try {
                        if ($bookingType === 'tour') {
                            $db->query(
                                "UPDATE tour_bookings
                                 SET payment_status = 'paid',
                                     status = CASE WHEN status IN ('inquiry','pending') THEN 'confirmed' ELSE status END,
                                     deposit_paid = CASE WHEN deposit_paid = 0 OR deposit_paid IS NULL THEN total ELSE deposit_paid END,
                                     balance_due = 0,
                                     payment_method_chosen = COALESCE(NULLIF(payment_method_chosen, ''), ?)
                                 WHERE id = ?",
                                [(string)$attempt['gateway_code'], $bookingId]
                            );
                        } else {
                            $db->query(
                                "UPDATE bookings
                                 SET payment_status = 'paid',
                                     status = CASE WHEN status = 'pending' THEN 'confirmed' ELSE status END,
                                     paid_at = COALESCE(paid_at, NOW()),
                                     payment_method_chosen = COALESCE(NULLIF(payment_method_chosen, ''), ?)
                                 WHERE id = ?",
                                [(string)$attempt['gateway_code'], $bookingId]
                            );
                        }
                    } catch (Throwable $e) {
                        error_log('admin payments fallback update: ' . $e->getMessage());
                    }
                }

                $flash = 'Payment #' . $attemptId . ' approved — booking confirmed and guest notified.';
            } catch (Throwable $e) {
                error_log('admin payments approve: ' . $e->getMessage());
                $flash     = 'Approval failed: ' . $e->getMessage();
                $flashType = 'error';
            }
        } elseif ($action === 'reject') {
            try {
                $db->query(
                    "UPDATE payment_attempts
                     SET status = 'failed', error_message = ?
                     WHERE id = ?",
                    [$note !== '' ? $note : 'Rejected by admin', $attemptId]
                );

                $bookingId   = (int)($attempt['booking_id'] ?? 0);
                $bookingType = strtolower((string)($attempt['booking_type'] ?? 'property'));
                if (!in_array($bookingType, ['property', 'tour', 'event'], true)) {
                    $bookingType = 'property';
                }

                if ($bookingId > 0) {
                    try {
                        if ($bookingType === 'tour') {
                            $b = $db->fetchOne("SELECT * FROM tour_bookings WHERE id = ? LIMIT 1", [$bookingId]);
                            $ref = $b ? (string)($b['booking_ref'] ?? '') : '';
                            $link = '/?page=tour-booking-confirm&ref=' . urlencode($ref);
                        } else {
                            $b = $db->fetchOne("SELECT * FROM bookings WHERE id = ? LIMIT 1", [$bookingId]);
                            $ref = $b ? (string)($b['booking_reference'] ?? '') : '';
                            $link = '/?page=booking&id=' . $bookingId;
                        }

                        if ($b && function_exists('createNotification')) {
                            createNotification(
                                (int)($b['user_id'] ?? 0),
                                'payment',
                                'Payment could not be verified',
                                'We could not verify your ' . strtoupper((string)$attempt['gateway_code']) . ' payment. Please check the reference or upload a new proof.',
                                $link,
                                'fa-exclamation-circle'
                            );
                        }
                    } catch (Throwable $e) {}
                }

                $flash = 'Payment #' . $attemptId . ' rejected.';
            } catch (Throwable $e) {
                error_log('admin payments reject: ' . $e->getMessage());
                $flash     = 'Reject failed: ' . $e->getMessage();
                $flashType = 'error';
            }
        }
    }
}

// ============================================================
// LOAD DATA
// ============================================================
$pendingAttempts = [];
$recentApproved  = [];

try {
    $pendingAttempts = $db->fetchAll(
        "SELECT pa.*,
                COALESCE(b.booking_reference, tb.booking_ref) AS _ref,
                COALESCE(b.guest_name, tb.guest_name)         AS _guest,
                COALESCE(b.total_amount, tb.total)            AS _total,
                COALESCE(b.currency, tb.currency)             AS _currency
         FROM payment_attempts pa
         LEFT JOIN bookings      b  ON pa.booking_type = 'property' AND pa.booking_id = b.id
         LEFT JOIN tour_bookings tb ON pa.booking_type = 'tour'     AND pa.booking_id = tb.id
         WHERE pa.status IN ('pending', 'initiated')
         ORDER BY pa.created_at DESC
         LIMIT 100"
    ) ?: [];
} catch (Throwable $e) {
    error_log('admin payments pending: ' . $e->getMessage());
}

try {
    $recentApproved = $db->fetchAll(
        "SELECT pa.*,
                COALESCE(b.booking_reference, tb.booking_ref) AS _ref,
                COALESCE(b.guest_name, tb.guest_name)         AS _guest,
                COALESCE(b.total_amount, tb.total)            AS _total,
                COALESCE(b.currency, tb.currency)             AS _currency
         FROM payment_attempts pa
         LEFT JOIN bookings      b  ON pa.booking_type = 'property' AND pa.booking_id = b.id
         LEFT JOIN tour_bookings tb ON pa.booking_type = 'tour'     AND pa.booking_id = tb.id
         WHERE pa.status = 'paid' AND pa.paid_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
         ORDER BY pa.paid_at DESC
         LIMIT 30"
    ) ?: [];
} catch (Throwable $e) {
    error_log('admin payments recent: ' . $e->getMessage());
}

$pageTitle = 'Manual Payment Verification';
require_once dirname(__DIR__, 2) . '/includes/header.php';
?>

<style>
.ap-page { background: #0f0c29; min-height: 100vh; padding: 100px 0 80px; color: white; }
.ap-page .container { max-width: 1400px; margin: 0 auto; padding: 0 20px; }
.ap-head { margin-bottom: 26px; }
.ap-head h1 { font-size: 28px; font-weight: 800; margin-bottom: 4px; display: flex; align-items: center; gap: 10px; }
.ap-head h1 .grad { background: linear-gradient(135deg, #667eea, #764ba2); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
.ap-head .sub { color: #a0aec0; font-size: 13px; }

.ap-flash { padding: 14px 20px; border-radius: 12px; margin-bottom: 22px; font-size: 13.5px; font-weight: 600; }
.ap-flash.success { background: rgba(0,184,148,0.12); border: 1px solid rgba(0,184,148,0.4); color: #6ee7b7; }
.ap-flash.error { background: rgba(245,87,108,0.12); border: 1px solid rgba(245,87,108,0.4); color: #fca5a5; }

.ap-stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 14px; margin-bottom: 24px; }
.ap-stat { background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08); border-radius: 14px; padding: 16px 18px; }
.ap-stat .v { font-size: 26px; font-weight: 900; font-family: 'SF Mono', Monaco, monospace; color: #a3bffa; line-height: 1; }
.ap-stat .l { font-size: 10px; color: #a0aec0; text-transform: uppercase; letter-spacing: 0.06em; font-weight: 800; margin-top: 6px; }

.ap-table-wrap { background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08); border-radius: 16px; overflow: hidden; margin-bottom: 26px; }
.ap-table-wrap h2 { padding: 18px 22px; font-size: 15px; font-weight: 800; border-bottom: 1px solid rgba(255,255,255,0.06); display: flex; align-items: center; gap: 8px; margin: 0; }
.ap-table-wrap h2 .badge { margin-left: auto; font-size: 10px; padding: 3px 10px; border-radius: 50px; background: rgba(246,173,85,0.15); color: #f6ad55; font-weight: 800; }

table.ap { width: 100%; border-collapse: collapse; font-size: 13px; }
table.ap thead { background: rgba(0,0,0,0.2); }
table.ap th { padding: 12px 14px; text-align: left; font-size: 10.5px; text-transform: uppercase; letter-spacing: 0.06em; color: #a0aec0; font-weight: 800; border-bottom: 1px solid rgba(255,255,255,0.06); }
table.ap td { padding: 14px 14px; border-bottom: 1px solid rgba(255,255,255,0.04); vertical-align: top; }
table.ap tr:last-child td { border-bottom: none; }
table.ap tr:hover { background: rgba(255,255,255,0.02); }

.ap-mono { font-family: 'SF Mono', Monaco, monospace; font-size: 12px; }
.ap-pill { display: inline-flex; align-items: center; gap: 5px; padding: 4px 10px; border-radius: 50px; font-size: 10px; font-weight: 800; text-transform: uppercase; letter-spacing: 0.04em; }
.ap-pill.pending { background: rgba(246,173,85,0.15); color: #f6ad55; }
.ap-pill.paid { background: rgba(0,184,148,0.15); color: #6ee7b7; }
.ap-pill.failed { background: rgba(245,87,108,0.15); color: #fca5a5; }
.ap-pill.method { background: rgba(102,126,234,0.15); color: #a3bffa; }
.ap-pill.kind { background: rgba(240,147,251,0.15); color: #f0abfc; }

.ap-actions { display: flex; gap: 6px; flex-direction: column; }
.ap-actions textarea { width: 100%; padding: 6px 8px; font-size: 11.5px; background: rgba(0,0,0,0.2); border: 1px solid rgba(255,255,255,0.1); border-radius: 6px; color: white; resize: vertical; min-height: 44px; font-family: inherit; }
.ap-btn { padding: 7px 14px; border-radius: 8px; font-weight: 800; font-size: 11px; cursor: pointer; border: none; font-family: inherit; text-transform: uppercase; letter-spacing: 0.04em; transition: all 0.15s; }
.ap-btn.approve { background: linear-gradient(135deg, #00b894, #10b981); color: white; }
.ap-btn.approve:hover { transform: translateY(-1px); box-shadow: 0 6px 18px rgba(0,184,148,0.4); }
.ap-btn.reject { background: rgba(245,87,108,0.15); color: #fca5a5; border: 1px solid rgba(245,87,108,0.35); }
.ap-btn.reject:hover { background: rgba(245,87,108,0.25); color: white; }

.ap-empty { padding: 60px 20px; text-align: center; color: #a0aec0; font-size: 14px; }
.ap-empty i { font-size: 48px; opacity: 0.3; display: block; margin-bottom: 16px; color: #a3bffa; }

.ap-proof-link { display: inline-flex; align-items: center; gap: 5px; padding: 4px 10px; border-radius: 6px; background: rgba(102,126,234,0.15); color: #a3bffa; font-size: 11px; text-decoration: none; font-weight: 700; }
.ap-proof-link:hover { background: rgba(102,126,234,0.28); color: white; }

@media (max-width: 900px) {
    .ap-stats { grid-template-columns: repeat(2, 1fr); }
    table.ap { font-size: 12px; }
    table.ap th, table.ap td { padding: 10px 8px; }
}
</style>

<div class="ap-page">
    <div class="container">

        <div class="ap-head">
            <h1>💳 <span class="grad">Manual Payment Verification</span></h1>
            <p class="sub">Review pending payment proofs — approve to confirm the booking, or reject with a note.</p>
        </div>

        <?php if ($flash): ?>
            <div class="ap-flash <?= $flashType === 'error' ? 'error' : 'success' ?>">
                <?= htmlspecialchars($flash, ENT_QUOTES, 'UTF-8') ?>
            </div>
        <?php endif; ?>

        <div class="ap-stats">
            <div class="ap-stat">
                <div class="v"><?= number_format(count($pendingAttempts)) ?></div>
                <div class="l">Pending verification</div>
            </div>
            <div class="ap-stat">
                <div class="v"><?= number_format(count($recentApproved)) ?></div>
                <div class="l">Approved (30d)</div>
            </div>
            <div class="ap-stat">
                <div class="v">
                    <?php
                    $pendingTotal = 0.0;
                    foreach ($pendingAttempts as $p) $pendingTotal += (float)($p['amount'] ?? 0);
                    echo '$' . number_format($pendingTotal, 2);
                    ?>
                </div>
                <div class="l">Pending amount</div>
            </div>
            <div class="ap-stat">
                <div class="v">
                    <?php
                    $approvedTotal = 0.0;
                    foreach ($recentApproved as $p) $approvedTotal += (float)($p['amount'] ?? 0);
                    echo '$' . number_format($approvedTotal, 2);
                    ?>
                </div>
                <div class="l">Approved amount (30d)</div>
            </div>
        </div>

        <div class="ap-table-wrap">
            <h2>
                <i class="fas fa-hourglass-half" style="color: #f6ad55;"></i>
                Pending verification
                <?php if (!empty($pendingAttempts)): ?>
                    <span class="badge"><?= number_format(count($pendingAttempts)) ?> waiting</span>
                <?php endif; ?>
            </h2>

            <?php if (empty($pendingAttempts)): ?>
                <div class="ap-empty">
                    <i class="fas fa-check-double"></i>
                    All manual payments are caught up. Nothing waiting for verification.
                </div>
            <?php else: ?>
                <table class="ap">
                    <thead>
                        <tr>
                            <th>Attempt</th>
                            <th>Booking</th>
                            <th>Type</th>
                            <th>Method</th>
                            <th>Amount</th>
                            <th>Reference / Proof</th>
                            <th>Submitted</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($pendingAttempts as $p):
                            $proofPath = trim((string)($p['manual_proof_path'] ?? ''));
                            $proofUrl  = $proofPath !== '' ? '/uploads/' . ltrim($proofPath, '/') : '';
                            $btype     = strtolower((string)($p['booking_type'] ?? 'property'));
                            $bId       = (int)($p['booking_id'] ?? 0);
                            $refLabel  = (string)($p['_ref'] ?? ('#' . $bId));
                        ?>
                            <tr>
                                <td>
                                    <div class="ap-mono">#<?= (int)$p['id'] ?></div>
                                    <div style="font-size: 10.5px; color: #a0aec0; margin-top: 2px;">
                                        <?= htmlspecialchars((string)($p['reference'] ?? ''), ENT_QUOTES, 'UTF-8') ?>
                                    </div>
                                </td>
                                <td>
                                    <?php if ($bId > 0): ?>
                                        <?php if ($btype === 'tour'): ?>
                                            <a href="/?page=tour-booking-confirm&ref=<?= urlencode($refLabel) ?>" style="color: #a3bffa; text-decoration: none; font-weight: 700;" target="_blank">
                                                <?= htmlspecialchars($refLabel, ENT_QUOTES, 'UTF-8') ?>
                                            </a>
                                        <?php else: ?>
                                            <a href="/?page=admin-booking-detail&id=<?= $bId ?>" style="color: #a3bffa; text-decoration: none; font-weight: 700;" target="_blank">
                                                <?= htmlspecialchars($refLabel, ENT_QUOTES, 'UTF-8') ?>
                                            </a>
                                        <?php endif; ?>
                                        <div style="font-size: 11px; color: #a0aec0; margin-top: 3px;">
                                            <?= htmlspecialchars((string)($p['_guest'] ?? ''), ENT_QUOTES, 'UTF-8') ?>
                                        </div>
                                    <?php else: ?>
                                        <span style="color: #a0aec0;">No booking linked</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="ap-pill kind"><?= htmlspecialchars(strtoupper($btype), ENT_QUOTES, 'UTF-8') ?></span>
                                </td>
                                <td>
                                    <span class="ap-pill method"><?= htmlspecialchars(strtoupper((string)($p['gateway_code'] ?? '')), ENT_QUOTES, 'UTF-8') ?></span>
                                </td>
                                <td>
                                    <div class="ap-mono" style="font-weight: 800; color: white;">
                                        <?= htmlspecialchars((string)($p['currency'] ?? 'USD'), ENT_QUOTES, 'UTF-8') ?>
                                        <?= number_format((float)($p['amount'] ?? 0), 2) ?>
                                    </div>
                                </td>
                                <td>
                                    <?php if (!empty($p['manual_reference'])): ?>
                                        <div class="ap-mono" style="font-size: 11px;">
                                            <?= htmlspecialchars((string)$p['manual_reference'], ENT_QUOTES, 'UTF-8') ?>
                                        </div>
                                    <?php endif; ?>
                                    <?php if ($proofUrl !== ''): ?>
                                        <a href="<?= htmlspecialchars($proofUrl, ENT_QUOTES, 'UTF-8') ?>" target="_blank" rel="noopener" class="ap-proof-link" style="margin-top: 6px;">
                                            <i class="fas fa-paperclip"></i> View proof
                                        </a>
                                    <?php else: ?>
                                        <span style="font-size: 11px; color: #a0aec0;">No proof uploaded</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <div style="font-size: 11.5px;">
                                        <?= htmlspecialchars(date('M j, Y', strtotime((string)($p['created_at'] ?? 'now'))), ENT_QUOTES, 'UTF-8') ?>
                                    </div>
                                    <div style="font-size: 10.5px; color: #a0aec0; margin-top: 2px;">
                                        <?= htmlspecialchars(date('g:i A', strtotime((string)($p['created_at'] ?? 'now'))), ENT_QUOTES, 'UTF-8') ?>
                                    </div>
                                </td>
                                <td>
                                    <div class="ap-actions">
                                        <form method="POST" style="display: flex; flex-direction: column; gap: 4px;">
                                            <input type="hidden" name="admin_payment_action" value="approve">
                                            <input type="hidden" name="attempt_id" value="<?= (int)$p['id'] ?>">
                                            <textarea name="admin_note" placeholder="Optional note"></textarea>
                                            <button type="submit" class="ap-btn approve" onclick="return confirm('Approve payment #<?= (int)$p['id'] ?>? This will mark the booking as paid and send confirmation emails.')">
                                                <i class="fas fa-check"></i> Approve
                                            </button>
                                        </form>
                                        <form method="POST" style="display: flex; flex-direction: column; gap: 4px;">
                                            <input type="hidden" name="admin_payment_action" value="reject">
                                            <input type="hidden" name="attempt_id" value="<?= (int)$p['id'] ?>">
                                            <textarea name="admin_note" placeholder="Reason"></textarea>
                                            <button type="submit" class="ap-btn reject" onclick="return confirm('Reject payment #<?= (int)$p['id'] ?>?')">
                                                <i class="fas fa-times"></i> Reject
                                            </button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>

        <div class="ap-table-wrap">
            <h2>
                <i class="fas fa-check-double" style="color: #00b894;"></i>
                Recently approved (last 30 days)
            </h2>

            <?php if (empty($recentApproved)): ?>
                <div class="ap-empty">
                    <i class="fas fa-inbox"></i>
                    No payments approved in the last 30 days.
                </div>
            <?php else: ?>
                <table class="ap">
                    <thead>
                        <tr>
                            <th>Attempt</th>
                            <th>Booking</th>
                            <th>Type</th>
                            <th>Method</th>
                            <th>Amount</th>
                            <th>Approved</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($recentApproved as $p):
                            $btype = strtolower((string)($p['booking_type'] ?? 'property'));
                            $bId   = (int)($p['booking_id'] ?? 0);
                            $refLabel = (string)($p['_ref'] ?? '');
                        ?>
                            <tr>
                                <td>
                                    <div class="ap-mono">#<?= (int)$p['id'] ?></div>
                                    <div style="font-size: 10.5px; color: #a0aec0; margin-top: 2px;">
                                        <?= htmlspecialchars((string)($p['reference'] ?? ''), ENT_QUOTES, 'UTF-8') ?>
                                    </div>
                                </td>
                                <td>
                                    <?php if ($bId > 0): ?>
                                        <a href="/?page=admin-booking-detail&id=<?= $bId ?>" style="color: #a3bffa; text-decoration: none; font-weight: 700;" target="_blank">
                                            <?= htmlspecialchars($refLabel, ENT_QUOTES, 'UTF-8') ?>
                                        </a>
                                        <div style="font-size: 11px; color: #a0aec0; margin-top: 3px;">
                                            <?= htmlspecialchars((string)($p['_guest'] ?? ''), ENT_QUOTES, 'UTF-8') ?>
                                        </div>
                                    <?php else: ?>
                                        —
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="ap-pill kind"><?= htmlspecialchars(strtoupper($btype), ENT_QUOTES, 'UTF-8') ?></span>
                                </td>
                                <td>
                                    <span class="ap-pill method"><?= htmlspecialchars(strtoupper((string)($p['gateway_code'] ?? '')), ENT_QUOTES, 'UTF-8') ?></span>
                                </td>
                                <td>
                                    <div class="ap-mono" style="font-weight: 800;">
                                        <?= htmlspecialchars((string)($p['currency'] ?? 'USD'), ENT_QUOTES, 'UTF-8') ?>
                                        <?= number_format((float)($p['amount'] ?? 0), 2) ?>
                                    </div>
                                </td>
                                <td>
                                    <span class="ap-pill paid">Paid</span>
                                    <div style="font-size: 11px; color: #a0aec0; margin-top: 3px;">
                                        <?= htmlspecialchars(date('M j, g:i A', strtotime((string)($p['paid_at'] ?? 'now'))), ENT_QUOTES, 'UTF-8') ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>

    </div>
</div>

<?php require_once dirname(__DIR__, 2) . '/includes/footer.php'; ?>