<?php
/**
 * Payments Management - Admin Page
 */

$page_title = 'Payments';
require_once 'includes/header.php';

$message = '';
$error = '';

try {
    $pdo = getDBConnection();
    
    // Handle verification
    if (isset($_POST['verify_payment'])) {
        $stmt = $pdo->prepare("UPDATE payments SET status = 'verified', verified_at = CURRENT_TIMESTAMP WHERE id = ?");
        $stmt->execute([$_POST['payment_id']]);
        
        // Also update booking status if it was pending downpayment
        $stmt = $pdo->prepare("UPDATE bookings SET downpayment_paid = 1, booking_status = 'confirmed' 
                             WHERE id = (SELECT booking_id FROM payments WHERE id = ?)");
        $stmt->execute([$_POST['payment_id']]);

        // Notify user
        require_once 'includes/notification_helper.php';
        $stmt = $pdo->prepare("SELECT p.amount, b.user_id, b.id as booking_id, b.reference_number FROM payments p JOIN bookings b ON p.booking_id = b.id WHERE p.id = ?");
        $stmt->execute([$_POST['payment_id']]);
        $info = $stmt->fetch();
        if ($info) {
            addNotification(
                $info['user_id'],
                "Payment Verified",
                "Your payment of ₱" . number_format($info['amount'], 2) . " for booking #" . $info['reference_number'] . " has been verified. Your booking is now confirmed!",
                'success',
                "booking_details.php?booking_id=" . $info['booking_id']
            );
        }
        
        $message = 'Payment verified and booking confirmed!';
    }

    // Handle rejection
    if (isset($_POST['reject_payment'])) {
        $stmt = $pdo->prepare("UPDATE payments SET status = 'rejected' WHERE id = ?");
        $stmt->execute([$_POST['payment_id']]);

        // Notify user
        require_once 'includes/notification_helper.php';
        $stmt = $pdo->prepare("SELECT p.amount, b.user_id, b.id as booking_id, b.reference_number FROM payments p JOIN bookings b ON p.booking_id = b.id WHERE p.id = ?");
        $stmt->execute([$_POST['payment_id']]);
        $info = $stmt->fetch();
        if ($info) {
            addNotification(
                $info['user_id'],
                "Payment Rejected",
                "Your payment for booking #" . $info['reference_number'] . " was rejected. Please contact support or re-upload your proof of payment.",
                'error',
                "booking_details.php?booking_id=" . $info['booking_id']
            );
        }

        $message = 'Payment rejected!';
    }

    // Get payments
    $status_filter = $_GET['status'] ?? '';
    $query = "SELECT p.*, b.reference_number as booking_ref, u.first_name, u.last_name 
              FROM payments p 
              LEFT JOIN bookings b ON p.booking_id = b.id 
              LEFT JOIN users u ON b.user_id = u.id";
    
    if ($status_filter) {
        $query .= " WHERE p.status = :status";
    }
    
    $query .= " ORDER BY p.created_at DESC";
    
    $stmt = $pdo->prepare($query);
    if ($status_filter) {
        $stmt->bindParam(':status', $status_filter);
    }
    $stmt->execute();
    $payments = $stmt->fetchAll();

} catch (PDOException $e) {
    $payments = [];
    $error = "Database error: " . $e->getMessage();
}
?>

<div class="flex h-screen overflow-hidden">
    <?php include 'includes/sidebar.php'; ?>
    
    <div class="flex-1 flex flex-col overflow-hidden">
        <header class="sticky top-0 z-30 flex items-center bg-white/80 dark:bg-background-dark/80 backdrop-blur-md p-4 justify-between border-b border-slate-200 dark:border-slate-800 lg:px-8">
            <div class="flex items-center gap-4">
                <button class="text-slate-900 dark:text-white flex size-10 items-center justify-center hover:bg-slate-100 dark:hover:bg-slate-800 rounded-full lg:hidden" onclick="toggleSidebar()">
                    <span class="material-symbols-outlined">menu</span>
                </button>
                <h2 class="text-slate-900 dark:text-white text-clamp-lg font-bold">Payment Approvals</h2>
            </div>
        </header>

        <main class="flex-1 overflow-y-auto p-4 lg:p-8 pb-24 admin-content">
            <!-- Filter Tabs -->
            <div class="flex gap-2 mb-6 overflow-x-auto no-scrollbar pb-2">
                <a href="payments.php" class="px-4 py-2 rounded-full text-xs font-bold transition-colors <?= empty($status_filter) ? 'bg-primary text-white' : 'bg-white dark:bg-surface-dark text-slate-500 border border-slate-200 dark:border-slate-800' ?>">All</a>
                <a href="payments.php?status=pending" class="px-4 py-2 rounded-full text-xs font-bold transition-colors <?= $status_filter === 'pending' ? 'bg-orange-500 text-white' : 'bg-white dark:bg-surface-dark text-slate-500 border border-slate-200 dark:border-slate-800' ?>">Pending</a>
                <a href="payments.php?status=verified" class="px-4 py-2 rounded-full text-xs font-bold transition-colors <?= $status_filter === 'verified' ? 'bg-emerald-500 text-white' : 'bg-white dark:bg-surface-dark text-slate-500 border border-slate-200 dark:border-slate-800' ?>">Verified</a>
                <a href="payments.php?status=rejected" class="px-4 py-2 rounded-full text-xs font-bold transition-colors <?= $status_filter === 'rejected' ? 'bg-rose-500 text-white' : 'bg-white dark:bg-surface-dark text-slate-500 border border-slate-200 dark:border-slate-800' ?>">Rejected</a>
            </div>

            <?php if ($message): ?>
                <div class="bg-emerald-100 dark:bg-emerald-900/30 border border-emerald-400 text-emerald-700 dark:text-emerald-300 px-4 py-3 rounded-xl mb-6">
                    <?= htmlspecialchars($message) ?>
                </div>
            <?php endif; ?>

            <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 3xl:grid-cols-4 5xl:grid-cols-6 gap-6">
                <?php if (empty($payments)): ?>
                    <div class="col-span-full p-12 text-center text-slate-500 bg-white dark:bg-surface-dark rounded-2xl border border-slate-200 dark:border-slate-800">
                        No payments found.
                    </div>
                <?php else: ?>
                    <?php foreach ($payments as $p): ?>
                        <div class="bg-white dark:bg-surface-dark rounded-2xl border border-slate-200 dark:border-slate-800 p-6 shadow-sm flex flex-col">
                            <div class="flex justify-between items-start mb-4">
                                <div>
                                    <p class="text-[10px] font-bold text-slate-400 uppercase tracking-widest">Reference</p>
                                    <h3 class="font-bold text-primary"><?= $p['reference_number'] ?></h3>
                                </div>
                                <span class="px-2 py-1 rounded text-[10px] font-bold uppercase <?= 
                                    $p['status'] === 'verified' ? 'bg-green-100 text-green-700' : 
                                    ($p['status'] === 'pending' ? 'bg-orange-100 text-orange-700' : 'bg-red-100 text-red-700')
                                ?>">
                                    <?= $p['status'] ?>
                                </span>
                            </div>
                            
                            <div class="bg-slate-50 dark:bg-slate-900/50 rounded-xl p-4 mb-4 space-y-2">
                                <div class="flex justify-between text-xs">
                                    <span class="text-slate-500">Amount</span>
                                    <span class="font-bold text-slate-900 dark:text-white"><?= formatCurrency(convertCurrency($p['amount'], 'PHP', $selected_currency), $selected_currency) ?></span>
                                </div>
                                <div class="flex justify-between text-xs">
                                    <span class="text-slate-500">Method</span>
                                    <span class="font-medium"><?= strtoupper($p['payment_method']) ?></span>
                                </div>
                                <div class="flex justify-between text-xs">
                                    <span class="text-slate-500">Booking</span>
                                    <span class="font-medium"><?= $p['booking_ref'] ?></span>
                                </div>
                                <div class="flex justify-between text-xs">
                                    <span class="text-slate-500">Customer</span>
                                    <span class="font-medium"><?= htmlspecialchars($p['first_name'] . ' ' . $p['last_name']) ?></span>
                                </div>
                                <div class="pt-2 mt-2 border-t border-slate-100 dark:border-slate-800">
                                    <div class="flex justify-between text-xs">
                                        <span class="text-slate-500">Sender Name</span>
                                        <span class="font-bold text-primary"><?= htmlspecialchars($p['sender_name'] ?? 'N/A') ?></span>
                                    </div>
                                    <div class="flex justify-between text-xs">
                                        <span class="text-slate-500">Sender Number</span>
                                        <span class="font-medium"><?= htmlspecialchars($p['sender_number'] ?? 'N/A') ?></span>
                                    </div>
                                </div>
                            </div>

                            <?php if ($p['proof_of_payment']): ?>
                                <?php
                                    $proof_url = $p['proof_of_payment'];
                                    // If it's just a filename (doesn't start with http or /), prepend the path
                                    if (!preg_match('/^https?:\/\//', $proof_url) && (empty($proof_url) || $proof_url[0] !== '/')) {
                                        $proof_url = '../uploads/payments/' . $proof_url;
                                    }
                                ?>
                                <button onclick="window.open('<?= $proof_url ?>')" class="mb-4 text-xs font-bold text-primary flex items-center gap-1 hover:underline">
                                    <span class="material-symbols-outlined text-sm">image</span>
                                    View Proof of Payment
                                </button>
                            <?php endif; ?>

                            <div class="mt-auto pt-4 flex gap-2">
                                <?php if ($p['status'] === 'pending'): ?>
                                    <form method="POST" class="flex-1">
                                        <input type="hidden" name="payment_id" value="<?= $p['id'] ?>">
                                        <button type="submit" name="verify_payment" class="w-full bg-primary text-white py-2 rounded-lg text-xs font-bold hover:bg-primary/90 transition-colors cursor-pointer">Verify</button>
                                    </form>
                                    <form method="POST" class="flex-1">
                                        <input type="hidden" name="payment_id" value="<?= $p['id'] ?>">
                                        <button type="submit" name="reject_payment" class="w-full border border-slate-200 dark:border-slate-800 py-2 rounded-lg text-xs font-bold hover:bg-slate-50 dark:hover:bg-slate-900 transition-colors text-rose-500 cursor-pointer">Reject</button>
                                    </form>
                                <?php else: ?>
                                    <button disabled class="w-full bg-slate-100 dark:bg-slate-800 text-slate-400 py-2 rounded-lg text-xs font-bold cursor-not-allowed">Verified on <?= date('M d, Y', strtotime($p['verified_at'])) ?></button>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </main>
    </div>
</div>

<?php include 'includes/footer.php'; ?>
