<?php
require_once 'config.php';
require_once 'includes/db.php';
require_once 'includes/functions.php';
require_login();

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    die("Access Denied. Admins only.");
}

$admin_id = $_SESSION['user_id'];
$success = '';
$error   = '';

// ─── Handle Actions ────────────────────────────────────────────────────────
if (isset($_POST['action'])) {
    $action = $_POST['action'];
    $wid    = (int)($_POST['withdrawal_id'] ?? 0);

    if ($action === 'complete_payment') {
        try {
            $pdo->beginTransaction();
            
            // Update withdrawal status
            $stmt = $pdo->prepare("UPDATE withdrawals SET status = 'completed', updated_at = NOW() WHERE id = ?");
            $stmt->execute([$wid]);

            // Log the action
            $stmt = $pdo->prepare("INSERT INTO admin_logs (admin_id, action, target_id, details) VALUES (?, 'complete_withdrawal', ?, 'Marked withdrawal as completed')");
            $stmt->execute([$admin_id, $wid]);

            $pdo->commit();
            $success = "Payment #$wid marked as completed.";
        } catch (PDOException $e) {
            $pdo->rollBack();
            $error = "Error: " . $e->getMessage();
        }
    }
}

// ─── Fetch Metrics ─────────────────────────────────────────────────────────
try {
    // Total Available Balance (Sum of all users)
    // Formula: Total Earned - Total Withdrawn (completed or pending)
    $stmt = $pdo->query("
        SELECT 
            (SELECT SUM(amount) FROM transactions WHERE status = 'completed') as total_revenue,
            (SELECT SUM(amount) FROM withdrawals WHERE status IN ('completed', 'pending')) as total_payouts_reserved
    ");
    $metrics = $stmt->fetch();
    $total_platform_balance = ($metrics['total_revenue'] ?? 0) - ($metrics['total_payouts_reserved'] ?? 0);

    // Total Paid Out
    $total_paid_out = $pdo->query("SELECT SUM(amount) FROM withdrawals WHERE status = 'completed'")->fetchColumn() ?: 0;

    // Total Pending
    $total_pending = $pdo->query("SELECT SUM(amount) FROM withdrawals WHERE status = 'pending'")->fetchColumn() ?: 0;

} catch (PDOException $e) {}

// ─── Fetch Withdrawals ─────────────────────────────────────────────────────
try {
    $withdrawals = $pdo->query("
        SELECT w.*, u.name as user_name, u.email as user_email 
        FROM withdrawals w 
        JOIN users u ON w.user_id = u.id 
        ORDER BY w.created_at DESC
    ")->fetchAll();
} catch (PDOException $e) { $withdrawals = []; }

// ─── Fetch User Payout Totals ──────────────────────────────────────────────
try {
    $user_payout_totals = $pdo->query("
        SELECT u.name, u.email, 
               SUM(CASE WHEN w.status = 'completed' THEN w.amount ELSE 0 END) as total_paid,
               SUM(CASE WHEN w.status = 'pending' THEN w.amount ELSE 0 END) as total_pending
        FROM users u
        LEFT JOIN withdrawals w ON u.id = w.user_id
        GROUP BY u.id
        HAVING total_paid > 0 OR total_pending > 0
        ORDER BY total_paid DESC
    ")->fetchAll();
} catch (PDOException $e) { $user_payout_totals = []; }

// ─── Fetch Admin Logs ──────────────────────────────────────────────────────
try {
    $logs = $pdo->query("
        SELECT l.*, u.name as admin_name 
        FROM admin_logs l 
        JOIN users u ON l.admin_id = u.id 
        ORDER BY l.created_at DESC LIMIT 50
    ")->fetchAll();
} catch (PDOException $e) { $logs = []; }

$pageTitle = "Manage Payments - Admin";
?>
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<head>
    <title><?= $pageTitle ?></title>
    <?php include 'includes/head.php'; ?>
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
    <style>
        .metric-card { transition: all 0.3s ease; }
        .metric-card:hover { transform: translateY(-3px); }
    </style>
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>
    <main class="dashboard-main">
        <?php include 'includes/header.php'; ?>
        
        <div class="dashboard-main-body">
            <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-24">
                <div class="d-flex align-items-center gap-12">
                     <h6 class="fw-semibold mb-0">Payment Management</h6>
                     <span class="badge bg-primary-focus text-primary-main d-flex align-items-center gap-1">
                         <i class="ri-shield-user-line"></i> Admin Only
                     </span>
                </div>
                <ul class="d-flex align-items-center gap-2">
                    <li class="fw-medium"><a href="superadmin.php" class="hover-text-primary text-secondary-light text-sm">Admin</a></li>
                    <li>-</li>
                    <li class="fw-medium text-sm">Manage Payments</li>
                </ul>
            </div>

            <style>
                .glass-card {
                    background: rgba(255, 255, 255, 0.8) !important;
                    backdrop-filter: blur(10px);
                    border: 1px solid rgba(255, 255, 255, 0.4) !important;
                    box-shadow: 0 8px 32px rgba(0,0,0,0.05) !important;
                }
                .sophisticated-tab .nav-link {
                    color: #64748b;
                    border-bottom: 2px solid transparent !important;
                    transition: all 0.3s;
                }
                .sophisticated-tab .nav-link.active {
                    color: #4e73df;
                    border-bottom-color: #4e73df !important;
                    background: transparent !important;
                }
                .pulse-pending {
                    animation: pulse-ring 1.5s cubic-bezier(0.24, 0, 0.38, 1) infinite;
                }
                @keyframes pulse-ring {
                    0% { transform: scale(.8); opacity: .5; }
                    80%, 100% { transform: scale(1.3); opacity: 0; }
                }
            </style>

            <!-- Global Metrics -->
            <div class="row gy-4 mb-32">
                <div class="col-xxl-4 col-sm-6">
                    <div class="card p-24 radius-12 border-0 metric-card" style="background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%);">
                        <div class="d-flex align-items-center justify-content-between">
                            <div>
                                <span class="fw-medium text-white-50 text-xs text-uppercase tracking-wider">Earning Reserved</span>
                                <h3 class="text-white fw-bold mb-0 mt-4">TSH <?= number_format($total_platform_balance) ?></h3>
                                <div class="text-white-50 text-xs mt-8">Total across all users</div>
                            </div>
                            <div class="w-60-px h-60-px radius-16 d-flex justify-content-center align-items-center bg-white-10 text-white text-3xl">
                                <iconify-icon icon="solar:bank-bold-duotone"></iconify-icon>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-xxl-4 col-sm-6">
                    <div class="card p-24 radius-12 border-0 metric-card" style="background: linear-gradient(135deg, #10b981 0%, #059669 100%);">
                        <div class="d-flex align-items-center justify-content-between">
                            <div>
                                <span class="fw-medium text-white-50 text-xs text-uppercase tracking-wider">Success Payouts</span>
                                <h3 class="text-white fw-bold mb-0 mt-4">TSH <?= number_format($total_paid_out) ?></h3>
                                <div class="text-white-50 text-xs mt-8">Successfully processed</div>
                            </div>
                            <div class="w-60-px h-60-px radius-16 d-flex justify-content-center align-items-center bg-white-10 text-white text-3xl">
                                <iconify-icon icon="solar:check-circle-bold-duotone"></iconify-icon>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-xxl-4 col-sm-6">
                    <div class="card p-24 radius-12 border-0 metric-card" style="background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);">
                        <div class="d-flex align-items-center justify-content-between">
                            <div>
                                <span class="fw-medium text-white-50 text-xs text-uppercase tracking-wider">Pending Payouts</span>
                                <h3 class="text-white fw-bold mb-0 mt-4">TSH <?= number_format($total_pending) ?></h3>
                                <div class="text-white-50 text-xs mt-8">Awaiting admin action</div>
                            </div>
                            <div class="w-60-px h-60-px radius-16 d-flex justify-content-center align-items-center bg-white-10 text-white text-3xl">
                                <iconify-icon icon="solar:clock-circle-bold-duotone"></iconify-icon>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <?php if($success): ?>
                <div class="alert alert-success alert-dismissible bg-success-focus text-success-main border-0 fade show mb-24 radius-12" role="alert">
                    <i class="ri-check-line me-8"></i> <?= $success ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <!-- Tabbed Interface for Organization -->
            <ul class="nav nav-tabs border-0 sophisticated-tab gap-24 mb-16" id="paymentTabs" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active px-0 py-12 fw-bold" id="requests-tab" data-bs-toggle="tab" data-bs-target="#requests" type="button" role="tab">Withdrawal Requests</button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link px-0 py-12 fw-bold" id="user-totals-tab" data-bs-toggle="tab" data-bs-target="#user-totals" type="button" role="tab">User History</button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link px-0 py-12 fw-bold" id="audit-logs-tab" data-bs-toggle="tab" data-bs-target="#audit-logs" type="button" role="tab">Audit Trails</button>
                </li>
            </ul>

            <div class="tab-content" id="paymentTabsContent">
                <!-- Tab 1: Withdrawal Requests -->
                <div class="tab-pane fade show active" id="requests" role="tabpanel">
                    <div class="card radius-12 border-0 mt-16">
                        <div class="card-header border-bottom bg-base">
                            <h6 class="mb-0 fw-bold">Withdrawal Requests</h6>
                        </div>
                        <div class="card-body p-24">
                            <div class="table-responsive">
                                <table class="table mb-0" id="requestsTable">
                                    <thead class="bg-base text-sm">
                                        <tr>
                                            <th>ID</th>
                                            <th>Date</th>
                                            <th>User Info</th>
                                            <th>Method</th>
                                            <th>Destination</th>
                                            <th>Amount</th>
                                            <th>Status</th>
                                            <th class="text-end">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php if(!empty($withdrawals)): ?>
                                            <?php foreach($withdrawals as $w): ?>
                                            <tr>
                                                <td class="fw-bold text-primary-600 text-xs" style="font-family:monospace;">
                                                    <?= htmlspecialchars($w['withdrawal_id'] ?: 'WDR-'.str_pad($w['id'], 6, '0', STR_PAD_LEFT)) ?>
                                                </td>
                                                <td><?= date('d M, Y', strtotime($w['created_at'])) ?></td>
                                                <td>
                                                    <div class="fw-semibold text-sm"><?= htmlspecialchars($w['user_name']) ?></div>
                                                    <div class="text-secondary-light text-xs"><?= htmlspecialchars($w['user_email']) ?></div>
                                                </td>
                                                <td>
                                                    <span class="badge <?= $w['method'] == 'Bank transfer' ? 'bg-info-focus text-info-main' : 'bg-primary-focus text-primary-main' ?> text-xs">
                                                        <?= htmlspecialchars($w['method']) ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <div class="text-xs fw-medium"><?= htmlspecialchars($w['network_or_bank']) ?></div>
                                                    <div class="text-xs text-secondary-light font-monospace"><?= htmlspecialchars($w['mobile_or_account']) ?></div>
                                                    <div class="text-xs text-dark mt-2"><?= htmlspecialchars($w['account_holder_name']) ?></div>
                                                </td>
                                                <td class="fw-bold text-sm text-primary-main">TSH <?= number_format($w['amount']) ?></td>
                                                <td>
                                                    <?php if($w['status'] == 'completed'): ?>
                                                        <span class="bg-success-focus text-success-main px-12 py-4 rounded-pill fw-medium text-xs">Completed</span>
                                                    <?php elseif($w['status'] == 'cancelled'): ?>
                                                        <span class="bg-danger-focus text-danger-main px-12 py-4 rounded-pill fw-medium text-xs">Cancelled</span>
                                                    <?php else: ?>
                                                        <span class="bg-warning-focus text-warning-main px-12 py-4 rounded-pill fw-medium text-xs pulse-warning">Pending</span>
                                                    <?php endif; ?>
                                                </td>
                                                <td class="text-end">
                                                    <?php if($w['status'] == 'pending'): ?>
                                                        <form method="POST" class="d-inline" onsubmit="return confirm('Confirm payment completion?')">
                                                            <input type="hidden" name="action" value="complete_payment">
                                                            <input type="hidden" name="withdrawal_id" value="<?= $w['id'] ?>">
                                                            <button type="submit" class="btn btn-sm btn-success-600 radius-8 px-16">
                                                                <i class="ri-check-double-line"></i> Mark Paid
                                                            </button>
                                                        </form>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Tab 2: User Export/Summary -->
                <div class="tab-pane fade" id="user-totals" role="tabpanel">
                    <div class="card radius-12 border-0 mt-16">
                        <div class="card-header border-bottom bg-base">
                            <h6 class="mb-0 fw-bold">User Payout Summary</h6>
                        </div>
                        <div class="card-body p-24">
                            <div class="table-responsive">
                                <table class="table mb-0" id="userTotalsTable">
                                    <thead class="bg-base text-sm">
                                        <tr>
                                            <th>User</th>
                                            <th>Total Paid Out</th>
                                            <th>Total Pending</th>
                                            <th>Overall Activity</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach($user_payout_totals as $up): ?>
                                        <tr>
                                            <td>
                                                <div class="fw-semibold text-sm"><?= htmlspecialchars($up['name']) ?></div>
                                                <div class="text-secondary-light text-xs"><?= htmlspecialchars($up['email']) ?></div>
                                            </td>
                                            <td class="fw-bold text-success-main text-sm">TSH <?= number_format($up['total_paid']) ?></td>
                                            <td class="fw-bold text-warning-main text-sm">TSH <?= number_format($up['total_pending']) ?></td>
                                            <td style="width: 200px;">
                                                <div class="progress h-8-px radius-4">
                                                    <div class="progress-bar bg-success-main" style="width: 100%"></div>
                                                </div>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Tab 3: Audit Logs -->
                <div class="tab-pane fade" id="audit-logs" role="tabpanel">
                    <div class="card radius-12 border-0 mt-16">
                        <div class="card-header border-bottom bg-base">
                            <h6 class="mb-0 fw-bold">Administrative Audit Trails</h6>
                        </div>
                        <div class="card-body p-24">
                            <div class="table-responsive">
                                <table class="table mb-0" id="logsTable">
                                    <thead class="bg-base text-sm">
                                        <tr>
                                            <th>Timestamp</th>
                                            <th>Admin</th>
                                            <th>Action</th>
                                            <th>Target ID</th>
                                            <th>Details</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach($logs as $l): ?>
                                        <tr>
                                            <td class="text-xs"><?= date('d M, Y H:i:s', strtotime($l['created_at'])) ?></td>
                                            <td><span class="badge bg-dark-focus text-dark-main text-xs"><?= htmlspecialchars($l['admin_name']) ?></span></td>
                                            <td class="text-sm fw-medium"><?= htmlspecialchars($l['action']) ?></td>
                                            <td class="text-sm">#<?= $l['target_id'] ?></td>
                                            <td class="text-xs text-secondary-light"><?= htmlspecialchars($l['details']) ?></td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

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

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#requestsTable').DataTable({
                "order": [[0, "desc"]],
                "pageLength": 10
            });
            $('#userTotalsTable').DataTable({
                "order": [[1, "desc"]]
            });
            $('#logsTable').DataTable({
                "order": [[0, "desc"]],
                "pageLength": 15
            });
        });
    </script>
</body>
</html>


