<?php

date_default_timezone_set('Africa/Lagos');

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


/*
|--------------------------------------------------------------------------
| FILTERS
|--------------------------------------------------------------------------
*/

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

$statusFilter =
    trim($_GET['status'] ?? 'all');

$directionFilter =
    trim($_GET['direction'] ?? 'all');


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

$stmt = $pdo->query("
    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_received,

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

                    THEN balance_before - balance_after

                    ELSE 0
                END
            ),
            0
        ) AS total_deducted,

        COALESCE(
            SUM(
                CASE
                    WHEN status = 'successful'
                    THEN 1
                    ELSE 0
                END
            ),
            0
        ) AS successful_count,

        COALESCE(
            SUM(
                CASE
                    WHEN status != 'successful'
                    THEN 1
                    ELSE 0
                END
            ),
            0
        ) AS other_count

    FROM wallet_transactions
");

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


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

$totalReceived =
    (float)($summary['total_received'] ?? 0);

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

$successfulCount =
    (int)($summary['successful_count'] ?? 0);

$otherCount =
    (int)($summary['other_count'] ?? 0);


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

$sql = "
    SELECT

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

        u.fullname,
        u.phone

    FROM wallet_transactions wt

    INNER JOIN users u
        ON wt.user_id = u.id

    WHERE 1 = 1
";


$params = [];


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

if ($search !== '') {

    $sql .= "
        AND (
            u.fullname LIKE ?
            OR u.phone LIKE ?
            OR wt.reference LIKE ?
            OR wt.description LIKE ?
        )
    ";

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

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

}


/*
|--------------------------------------------------------------------------
| STATUS
|--------------------------------------------------------------------------
*/

if ($statusFilter !== 'all') {

    $sql .= "
        AND wt.status = ?
    ";

    $params[] =
        $statusFilter;

}


/*
|--------------------------------------------------------------------------
| DIRECTION
|--------------------------------------------------------------------------
*/

if ($directionFilter === 'credit') {

    $sql .= "
        AND wt.balance_after > wt.balance_before
    ";

}

elseif ($directionFilter === 'debit') {

    $sql .= "
        AND wt.balance_after < wt.balance_before
    ";

}


$sql .= "
    ORDER BY
        wt.created_at DESC,
        wt.id DESC
";


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

$stmt->execute($params);

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

    /*
|--------------------------------------------------------------------------
| PAYMENT PAGINATION
|--------------------------------------------------------------------------
*/

$recordsPerPage = 20;

$totalPaymentRecords =
    count($payments);


$paymentPage =
    max(
        1,
        (int)($_GET['page'] ?? 1)
    );


$totalPaymentPages =
    max(
        1,
        (int)ceil(
            $totalPaymentRecords /
            $recordsPerPage
        )
    );


if ($paymentPage > $totalPaymentPages) {

    $paymentPage =
        $totalPaymentPages;

}


$paymentOffset =
    ($paymentPage - 1)
    * $recordsPerPage;


$paginatedPayments =
    array_slice(
        $payments,
        $paymentOffset,
        $recordsPerPage
    );


$showingFrom =
    $totalPaymentRecords > 0
        ? $paymentOffset + 1
        : 0;


$showingTo =
    min(
        $paymentOffset
        + $recordsPerPage,
        $totalPaymentRecords
    );


$paymentPaginationParams = [

    'q' =>
        $search,

    'direction' =>
        $directionFilter,

    'status' =>
        $statusFilter

];

?>

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

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

<title>Payments - 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-payments.css"
>

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


    <!-- HEADER -->

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

        <div>

            <h1>

                <i class="fas fa-money-bill-transfer"></i>

                Payments

            </h1>

            <p>
                Monitor financial transactions across Complete Bliss.
            </p>

        </div>

    </div>



    <!-- SUMMARY -->

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


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

            <div class="payment-summary-icon received">

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

            </div>

            <div>

                <span>
                    Total Money Received
                </span>

                <h2>

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

                </h2>

                <small>
                    Successful wallet credits
                </small>

            </div>

        </div>



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

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

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

            </div>

            <div>

                <span>
                    Total Deductions
                </span>

                <h2>

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

                </h2>

                <small>
                    Contributions and other debits
                </small>

            </div>

        </div>



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

            <div class="payment-summary-icon success">

                <i class="fas fa-circle-check"></i>

            </div>

            <div>

                <span>
                    Successful Transactions
                </span>

                <h2>
                    <?= $successfulCount; ?>
                </h2>

                <small>
                    Completed transactions
                </small>

            </div>

        </div>



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

            <div class="payment-summary-icon other">

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

            </div>

            <div>

                <span>
                    Pending / Failed
                </span>

                <h2>
                    <?= $otherCount; ?>
                </h2>

                <small>
                    Transactions requiring attention
                </small>

            </div>

        </div>


    </div>



    <!-- FILTER -->

    <section class="payment-filter-card">


        <form
            method="GET"
            action="payments.php"
            class="payment-filter-form"
        >


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

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

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

            </div>



            <select name="direction">

                <option
                    value="all"
                    <?= $directionFilter === 'all'
                        ? 'selected'
                        : ''; ?>
                >
                    All Transactions
                </option>

                <option
                    value="credit"
                    <?= $directionFilter === 'credit'
                        ? 'selected'
                        : ''; ?>
                >
                    Money In
                </option>

                <option
                    value="debit"
                    <?= $directionFilter === 'debit'
                        ? 'selected'
                        : ''; ?>
                >
                    Money Out
                </option>

            </select>



            <select name="status">

                <option
                    value="all"
                    <?= $statusFilter === 'all'
                        ? 'selected'
                        : ''; ?>
                >
                    All Statuses
                </option>

                <option
                    value="successful"
                    <?= $statusFilter === 'successful'
                        ? 'selected'
                        : ''; ?>
                >
                    Successful
                </option>

                <option
                    value="pending"
                    <?= $statusFilter === 'pending'
                        ? 'selected'
                        : ''; ?>
                >
                    Pending
                </option>

                <option
                    value="failed"
                    <?= $statusFilter === 'failed'
                        ? 'selected'
                        : ''; ?>
                >
                    Failed
                </option>

            </select>



            <button type="submit">

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

                Apply

            </button>



            <a
                href="payments.php"
                class="payment-reset-btn"
            >

                Reset

            </a>


        </form>


    </section>



    <!-- TABLE -->

    <section class="payment-record-card">


        <div class="payment-record-header">

            <div>

                <h2>
                    Transaction Records
                </h2>

                <p>

    <?php if ($totalPaymentRecords > 0): ?>

        Showing

        <strong>
            <?= $showingFrom; ?>
        </strong>

        –

        <strong>
            <?= $showingTo; ?>
        </strong>

        of

        <strong>
            <?= $totalPaymentRecords; ?>
        </strong>

        transactions

    <?php else: ?>

        0 transactions

    <?php endif; ?>

</p>

            </div>

        </div>



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


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


            <table class="payment-table">


                <thead>

                    <tr>

                        <th>Date</th>

                        <th>Member</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 ($paginatedPayments as $payment): ?>


                    <?php

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


                    $realAmount =
                        abs(
                            (float)$payment['balance_after']
                            -
                            (float)$payment['balance_before']
                        );

                    ?>


                    <tr>


                        <td>

                            <strong class="payment-date">

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

                            </strong>

                            <small>

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

                            </small>

                        </td>



                        <td>

                            <div class="payment-member">

                                <strong>

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

                                </strong>

                                <small>

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

                                </small>

                            </div>

                        </td>



                        <td>

                            <span class="payment-type">

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

                            </span>

                        </td>



                        <td>

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

                        </td>



                        <td>

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

                                <span class="payment-reference">

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

                                </span>

                            <?php else: ?>

                                —

                            <?php endif; ?>

                        </td>



                        <td>

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

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

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

                            </strong>

                        </td>



                        <td>

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

                        </td>



                        <td>

                            <strong>

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

                            </strong>

                        </td>



                        <td>

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

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

                            </span>

                        </td>


                    </tr>


                <?php endforeach; ?>


                </tbody>


            </table>


        </div>


        <?php if ($totalPaymentPages > 1): ?>

<div class="payment-pagination">


    <!-- PREVIOUS -->

    <?php if ($paymentPage > 1): ?>

        <a
            href="?<?= htmlspecialchars(
                http_build_query(
                    array_merge(
                        $paymentPaginationParams,
                        [
                            'page' =>
                                $paymentPage - 1
                        ]
                    )
                )
            ); ?>"
            class="payment-page-nav"
        >

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

            Previous

        </a>

    <?php else: ?>

        <span class="payment-page-nav disabled">

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

            Previous

        </span>

    <?php endif; ?>



    <!-- PAGE NUMBERS -->

    <div class="payment-page-numbers">

        <?php for (
            $pageNumber = 1;
            $pageNumber <= $totalPaymentPages;
            $pageNumber++
        ): ?>


            <?php if (
                $pageNumber === $paymentPage
            ): ?>

                <span class="payment-page-number active">

                    <?= $pageNumber; ?>

                </span>

            <?php else: ?>

                <a
                    href="?<?= htmlspecialchars(
                        http_build_query(
                            array_merge(
                                $paymentPaginationParams,
                                [
                                    'page' =>
                                        $pageNumber
                                ]
                            )
                        )
                    ); ?>"
                    class="payment-page-number"
                >

                    <?= $pageNumber; ?>

                </a>

            <?php endif; ?>


        <?php endfor; ?>

    </div>



    <!-- NEXT -->

    <?php if (
        $paymentPage < $totalPaymentPages
    ): ?>

        <a
            href="?<?= htmlspecialchars(
                http_build_query(
                    array_merge(
                        $paymentPaginationParams,
                        [
                            'page' =>
                                $paymentPage + 1
                        ]
                    )
                )
            ); ?>"
            class="payment-page-nav"
        >

            Next

            <i class="fas fa-chevron-right"></i>

        </a>

    <?php else: ?>

        <span class="payment-page-nav disabled">

            Next

            <i class="fas fa-chevron-right"></i>

        </span>

    <?php endif; ?>


</div>

<?php endif; ?>


        <?php else: ?>


            <div class="payment-empty">

                <i class="fas fa-money-bill-transfer"></i>

                <h3>
                    No Transactions Found
                </h3>

                <p>
                    No payment records match your selected filters.
                </p>

            </div>


        <?php endif; ?>


    </section>


</main>


</div>


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


</body>

</html>