<?php

date_default_timezone_set('Africa/Lagos');

include "../includes/admin_auth.php";
include "../config/database.php";


/*
|--------------------------------------------------------------------------
| SEARCH
|--------------------------------------------------------------------------
*/

$search = trim($_GET['q'] ?? '');


/*
|--------------------------------------------------------------------------
| WALLET SUMMARY
|--------------------------------------------------------------------------
*/

$stmt = $pdo->query("
    SELECT

        COUNT(*) AS total_members,

        COALESCE(
            SUM(wallet_balance),
            0
        ) AS total_wallet_balance

    FROM users

    WHERE role = 'member'
");

$walletSummary =
    $stmt->fetch(PDO::FETCH_ASSOC);


$totalMembers =
    (int)($walletSummary['total_members'] ?? 0);

$totalWalletBalance =
    (float)($walletSummary['total_wallet_balance'] ?? 0);


/*
|--------------------------------------------------------------------------
| TOTAL FUNDING / DEDUCTIONS
|--------------------------------------------------------------------------
*/

$stmt = $pdo->query("
    SELECT

        COALESCE(
            SUM(
                CASE
                    WHEN balance_after > balance_before
                    THEN balance_after - balance_before
                    ELSE 0
                END
            ),
            0
        ) AS total_funded,

        COALESCE(
            SUM(
                CASE
                    WHEN balance_after < balance_before
                    THEN balance_before - balance_after
                    ELSE 0
                END
            ),
            0
        ) AS total_deducted

    FROM wallet_transactions

    WHERE status = 'successful'
");

$transactionSummary =
    $stmt->fetch(PDO::FETCH_ASSOC);


$totalFunded =
    (float)($transactionSummary['total_funded'] ?? 0);

$totalDeducted =
    (float)($transactionSummary['total_deducted'] ?? 0);


/*
|--------------------------------------------------------------------------
| MEMBER WALLETS
|--------------------------------------------------------------------------
*/

$sql = "
    SELECT

        u.id,
        u.fullname,
        u.phone,
        u.email,
        u.wallet_balance,

        COUNT(wt.id) AS total_transactions,

        COALESCE(
            SUM(
                CASE
                    WHEN
                        wt.status = 'successful'
                        AND wt.balance_after > wt.balance_before

                    THEN wt.balance_after - wt.balance_before

                    ELSE 0
                END
            ),
            0
        ) AS total_funded,

        COALESCE(
            SUM(
                CASE
                    WHEN
                        wt.status = 'successful'
                        AND wt.balance_after < wt.balance_before

                    THEN wt.balance_before - wt.balance_after

                    ELSE 0
                END
            ),
            0
        ) AS total_deducted,

        MAX(wt.created_at) AS last_activity

    FROM users u

    LEFT JOIN wallet_transactions wt
        ON wt.user_id = u.id

    WHERE u.role = 'member'
";


$params = [];


if ($search !== '') {

    $sql .= "
        AND (
            u.fullname LIKE ?
            OR u.phone LIKE ?
            OR u.email LIKE ?
        )
    ";

    $searchValue =
        '%' . $search . '%';

    $params[] = $searchValue;
    $params[] = $searchValue;
    $params[] = $searchValue;

}


$sql .= "
    GROUP BY
        u.id,
        u.fullname,
        u.phone,
        u.email,
        u.wallet_balance

    ORDER BY u.fullname ASC
";


$stmt = $pdo->prepare($sql);

$stmt->execute($params);

$wallets =
    $stmt->fetchAll(PDO::FETCH_ASSOC);

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta
    name="viewport"
    content="width=device-width, initial-scale=1.0"
>

<title>Wallets - Complete Bliss</title>


<link
    rel="stylesheet"
    href="../assets/css/admin.css"
>

<link
    rel="stylesheet"
    href="../assets/css/responsive.css"
>

<link
    rel="stylesheet"
    href="../assets/css/admin-wallets.css"
>

<link
    rel="stylesheet"
    href="../assets/css/admin-wallets-responsive.css"
>

<link
    rel="stylesheet"
    href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css"
>

</head>


<body>


<?php include "../includes/admin_sidebar.php"; ?>


<div class="sidebar-overlay"></div>


<?php include "../includes/admin_topbar.php"; ?>


<div class="main-content">


<main class="admin-wallets-page">


    <!-- ==========================================
         HEADER
    =========================================== -->

    <div class="admin-wallets-header">

        <div>

            <h1>

                <i class="fas fa-wallet"></i>

                Wallets

            </h1>

            <p>
                Monitor member wallet balances and
                wallet transaction activity.
            </p>

        </div>

    </div>



    <!-- ==========================================
         SUMMARY CARDS
    =========================================== -->

    <div class="wallet-summary-grid">


        <!-- TOTAL BALANCE -->

        <div class="wallet-summary-card">

            <div class="wallet-summary-icon balance">

                <i class="fas fa-wallet"></i>

            </div>

            <div>

                <span>
                    Total Wallet Balance
                </span>

                <h2>

                    ₦<?= number_format(
                        $totalWalletBalance,
                        2
                    ); ?>

                </h2>

                <small>
                    Current balance across members
                </small>

            </div>

        </div>



        <!-- TOTAL FUNDED -->

        <div class="wallet-summary-card">

            <div class="wallet-summary-icon funded">

                <i class="fas fa-arrow-down"></i>

            </div>

            <div>

                <span>
                    Total Wallet Funding
                </span>

                <h2>

                    ₦<?= number_format(
                        $totalFunded,
                        2
                    ); ?>

                </h2>

                <small>
                    Successful wallet credits
                </small>

            </div>

        </div>



        <!-- TOTAL DEDUCTED -->

        <div class="wallet-summary-card">

            <div class="wallet-summary-icon deducted">

                <i class="fas fa-arrow-up"></i>

            </div>

            <div>

                <span>
                    Total Wallet Deductions
                </span>

                <h2>

                    ₦<?= number_format(
                        $totalDeducted,
                        2
                    ); ?>

                </h2>

                <small>
                    Contributions and other deductions
                </small>

            </div>

        </div>



        <!-- MEMBERS -->

        <div class="wallet-summary-card">

            <div class="wallet-summary-icon members">

                <i class="fas fa-users"></i>

            </div>

            <div>

                <span>
                    Member Wallets
                </span>

                <h2>

                    <?= number_format(
                        $totalMembers
                    ); ?>

                </h2>

                <small>
                    Registered member wallets
                </small>

            </div>

        </div>


    </div>



    <!-- ==========================================
         SEARCH
    =========================================== -->

    <section class="wallet-search-card">


        <form
            method="GET"
            action="wallets.php"
            class="wallet-search-form"
        >


            <div class="wallet-search-box">

                <i class="fas fa-magnifying-glass"></i>

                <input
                    type="text"
                    name="q"
                    placeholder="Search member by name, phone or email..."
                    value="<?= htmlspecialchars($search); ?>"
                >

            </div>


            <button type="submit">

                Search

            </button>


            <?php if ($search !== ''): ?>

                <a
                    href="wallets.php"
                    class="wallet-search-reset"
                >

                    Reset

                </a>

            <?php endif; ?>


        </form>


    </section>



    <!-- ==========================================
         MEMBER WALLETS
    =========================================== -->

    <section class="wallet-records-card">


        <div class="wallet-records-header">

            <div>

                <h2>
                    Member Wallets
                </h2>

                <p>

                    <?= count($wallets); ?>

                    wallet<?= count($wallets) === 1
                        ? ''
                        : 's'; ?>

                    displayed

                </p>

            </div>

        </div>



        <?php if (count($wallets) > 0): ?>


            <div class="wallet-table-wrap">


                <table class="wallet-table">


                    <thead>

                        <tr>

                            <th>Member</th>

                            <th>Current Balance</th>

                            <th>Total Funded</th>

                            <th>Total Deducted</th>

                            <th>Transactions</th>

                            <th>Last Activity</th>

                            <th>Action</th>

                        </tr>

                    </thead>


                    <tbody>


                    <?php foreach ($wallets as $wallet): ?>


                        <tr>


                            <!-- MEMBER -->

                            <td>

                                <div class="wallet-member">


                                    <div class="wallet-member-icon">

                                        <i class="fas fa-user"></i>

                                    </div>


                                    <div>

                                        <strong>

                                            <?= htmlspecialchars(
                                                $wallet['fullname']
                                            ); ?>

                                        </strong>


                                        <small>

                                            <?= htmlspecialchars(
                                                $wallet['phone'] ?? ''
                                            ); ?>

                                        </small>


                                        <?php if (
                                            !empty($wallet['email'])
                                        ): ?>

                                            <small>

                                                <?= htmlspecialchars(
                                                    $wallet['email']
                                                ); ?>

                                            </small>

                                        <?php endif; ?>


                                    </div>


                                </div>

                            </td>



                            <!-- BALANCE -->

                            <td>

                                <strong class="wallet-balance-value">

                                    ₦<?= number_format(
                                        (float)$wallet['wallet_balance'],
                                        2
                                    ); ?>

                                </strong>

                            </td>



                            <!-- FUNDED -->

                            <td>

                                <span class="wallet-money funded">

                                    +₦<?= number_format(
                                        (float)$wallet['total_funded'],
                                        2
                                    ); ?>

                                </span>

                            </td>



                            <!-- DEDUCTED -->

                            <td>

                                <span class="wallet-money deducted">

                                    -₦<?= number_format(
                                        (float)$wallet['total_deducted'],
                                        2
                                    ); ?>

                                </span>

                            </td>



                            <!-- TRANSACTIONS -->

                            <td>

                                <span class="wallet-transaction-count">

                                    <?= number_format(
                                        (int)$wallet['total_transactions']
                                    ); ?>

                                </span>

                            </td>



                            <!-- LAST ACTIVITY -->

                            <td>

                                <?php if (
                                    !empty($wallet['last_activity'])
                                ): ?>

                                    <strong class="wallet-date">

                                        <?= date(
                                            'd M Y',
                                            strtotime(
                                                $wallet['last_activity']
                                            )
                                        ); ?>

                                    </strong>

                                    <small class="wallet-time">

                                        <?= date(
                                            'h:i A',
                                            strtotime(
                                                $wallet['last_activity']
                                            )
                                        ); ?>

                                    </small>

                                <?php else: ?>

                                    <span class="wallet-no-activity">

                                        No activity

                                    </span>

                                <?php endif; ?>

                            </td>

                            <td>

    <a
        href="wallet_transactions.php?user_id=<?= (int)$wallet['id']; ?>"
        class="wallet-view-btn"
    >

        <i class="fas fa-eye"></i>

        View Transactions

    </a>

</td>


                        </tr>


                    <?php endforeach; ?>


                    </tbody>


                </table>


            </div>


        <?php else: ?>


            <div class="wallet-empty-state">


                <div class="wallet-empty-icon">

                    <i class="fas fa-wallet"></i>

                </div>


                <h3>
                    No Wallets Found
                </h3>


                <p>

                    <?php if ($search !== ''): ?>

                        No member matches your search.

                    <?php else: ?>

                        No member wallets are available.

                    <?php endif; ?>

                </p>


            </div>


        <?php endif; ?>


    </section>


</main>


</div>


<script src="../assets/js/admin.js"></script>


</body>

</html>