<?php

date_default_timezone_set('Africa/Lagos');

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


$userId = (int)($_GET['user_id'] ?? 0);


if ($userId <= 0) {

    header("Location: wallets.php");
    exit();

}


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

$stmt = $pdo->prepare("
    SELECT
        id,
        fullname,
        phone,
        email,
        wallet_balance

    FROM users

    WHERE id = ?
    AND role = 'member'

    LIMIT 1
");

$stmt->execute([$userId]);

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


if (!$member) {

    header("Location: wallets.php");
    exit();

}


/*
|--------------------------------------------------------------------------
| TRANSACTION SUMMARY
|--------------------------------------------------------------------------
*/

$stmt = $pdo->prepare("
    SELECT

        COUNT(*) AS total_transactions,

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

                    THEN balance_after - balance_before
                    ELSE 0
                END
            ),
            0
        ) AS total_funded,

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

                    THEN balance_before - balance_after
                    ELSE 0
                END
            ),
            0
        ) AS total_deducted

    FROM wallet_transactions

    WHERE user_id = ?
");

$stmt->execute([$userId]);

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


$totalTransactions =
    (int)($summary['total_transactions'] ?? 0);

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

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


/*
|--------------------------------------------------------------------------
| TRANSACTIONS
|--------------------------------------------------------------------------
*/

$stmt = $pdo->prepare("
    SELECT

        id,
        transaction_type,
        amount,
        balance_before,
        balance_after,
        reference,
        description,
        status,
        created_at

    FROM wallet_transactions

    WHERE user_id = ?

    ORDER BY created_at DESC, id DESC
");

$stmt->execute([$userId]);

$transactions =
    $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>Wallet Transactions - 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-wallet-transactions.css"
>

<link
    rel="stylesheet"
    href="../assets/css/admin-wallet-transactions-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="wallet-transactions-page">


    <!-- HEADER -->

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

        <div>

            <h1>
                <i class="fas fa-receipt"></i>
                Wallet Transactions
            </h1>

            <p>
                Transaction history for
                <strong>
                    <?= htmlspecialchars($member['fullname']); ?>
                </strong>
            </p>

        </div>


        <a
            href="wallets.php"
            class="wallet-back-btn"
        >

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

            Back to Wallets

        </a>

    </div>



    <!-- MEMBER CARD -->

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

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

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

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

            </div>

            <div>

                <h2>
                    <?= htmlspecialchars($member['fullname']); ?>
                </h2>

                <p>
                    <?= htmlspecialchars($member['phone'] ?? ''); ?>
                </p>

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

                    <p>
                        <?= htmlspecialchars($member['email']); ?>
                    </p>

                <?php endif; ?>

            </div>

        </div>


        <div class="wallet-current-balance">

            <span>
                Current Wallet Balance
            </span>

            <strong>

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

            </strong>

        </div>

    </section>



    <!-- SUMMARY -->

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


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

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

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

            </div>

            <div>

                <span>
                    Total Funded
                </span>

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

            </div>

        </div>


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

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

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

            </div>

            <div>

                <span>
                    Total Deducted
                </span>

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

            </div>

        </div>


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

            <div class="wallet-tx-icon transactions">

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

            </div>

            <div>

                <span>
                    Transactions
                </span>

                <h3>
                    <?= number_format($totalTransactions); ?>
                </h3>

            </div>

        </div>


    </div>



    <!-- TRANSACTION TABLE -->

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


        <div class="wallet-transactions-card-header">

            <h2>
                Transaction History
            </h2>

            <p>
                <?= count($transactions); ?>
                record<?= count($transactions) === 1 ? '' : 's'; ?>
            </p>

        </div>


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


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


                <table class="wallet-transactions-table">

                    <thead>

                        <tr>
                            <th>Date</th>
                            <th>Type</th>
                            <th>Description</th>
                            <th>Reference</th>
                            <th>Amount</th>
                            <th>Before</th>
                            <th>After</th>
                            <th>Status</th>
                        </tr>

                    </thead>


                    <tbody>


                    <?php foreach ($transactions as $transaction): ?>


                        <?php

                        $isCredit =
                            (float)$transaction['balance_after']
                            >
                            (float)$transaction['balance_before'];

                        ?>


                        <tr>


                            <td>

                                <strong class="wallet-tx-date">

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

                                </strong>

                                <small>

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

                                </small>

                            </td>


                            <td>

                                <span class="wallet-tx-type">

                                    <?= htmlspecialchars(
                                        ucwords(
                                            str_replace(
                                                '_',
                                                ' ',
                                                $transaction['transaction_type']
                                            )
                                        )
                                    ); ?>

                                </span>

                            </td>


                            <td>

                                <?= htmlspecialchars(
                                    $transaction['description'] ?? '—'
                                ); ?>

                            </td>


                            <td>

                                <?php if (!empty($transaction['reference'])): ?>

                                    <span class="wallet-tx-reference">

                                        <?= htmlspecialchars(
                                            $transaction['reference']
                                        ); ?>

                                    </span>

                                <?php else: ?>

                                    —

                                <?php endif; ?>

                            </td>


                            <td>

                                <strong class="<?= $isCredit
                                    ? 'wallet-credit'
                                    : 'wallet-debit'; ?>">

                                    <?= $isCredit ? '+' : '-'; ?>

                                    ₦<?= number_format(
                                        abs(
                                            (float)$transaction['balance_after']
                                            -
                                            (float)$transaction['balance_before']
                                        ),
                                        2
                                    ); ?>

                                </strong>

                            </td>


                            <td>

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

                            </td>


                            <td>

                                <strong>

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

                                </strong>

                            </td>


                            <td>

                                <span class="wallet-tx-status <?= strtolower(
                                    $transaction['status']
                                ); ?>">

                                    <?= htmlspecialchars(
                                        ucfirst($transaction['status'])
                                    ); ?>

                                </span>

                            </td>


                        </tr>


                    <?php endforeach; ?>


                    </tbody>

                </table>


            </div>


        <?php else: ?>


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

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

                <h3>
                    No Transactions
                </h3>

                <p>
                    This member has no wallet transaction history yet.
                </p>

            </div>


        <?php endif; ?>


    </section>


</main>

</div>


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

</body>
</html>