<?php
ob_start();

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

require_once('../titancore/titanconfig.php');
require_once('../titancore/titanheader.php');

$uid = $_SESSION['user_id'];
$u_name = $_SESSION['user_name'] ?? 'User';

/* ================= RETRIEVE USER PROFILE METRICS ================= */
$user = $conn->query("SELECT * FROM users WHERE id='$uid'")->fetch_assoc();
$wallet = floatval($user['wallet'] ?? $user['balance'] ?? 0);
$phone  = $user['phone'];

/* ================= TRANSACTION SUMMARY ANALYTICS ================= */
// Calculate total historical debits logged against this specific customer account
$debitCalc = $conn->query("SELECT SUM(amount) AS total_debit FROM wallethistory WHERE userid='$phone' AND type='Debit'")->fetch_assoc();
$totalDebits = floatval($debitCalc['total_debit'] ?? 0);

// Calculate total historical credits logged against this specific customer account
$creditCalc = $conn->query("SELECT SUM(amount) AS total_credit FROM wallethistory WHERE userid='$phone' AND type='Credit'")->fetch_assoc();
$totalCredits = floatval($creditCalc['total_credit'] ?? 0);


/* ================= REGULAR PAGINATION SYSTEM ================= */
$limit = 10; 
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$offset = ($page - 1) * $limit;

// Fetch aggregate table volume row-count for structural calculation loops
$countQuery = $conn->query("SELECT COUNT(*) AS total_rows FROM wallethistory WHERE userid='$phone'");
$totalRows = $countQuery->fetch_assoc()['total_rows'];
$totalPages = ceil($totalRows / $limit);

// Execute slice selection for target ledger rendering pipeline
$history = $conn->query("
    SELECT * FROM wallethistory 
    WHERE userid='$phone' 
    ORDER BY id DESC 
    LIMIT $limit OFFSET $offset
");
?>

<div class="row mb-3">
    <div class="col-12">
        <div class="card bg-100 shadow-none border">
            <div class="row gx-0 flex-between-center p-3">
                <div class="col-sm-auto d-flex align-items-center">
                    <div class="icon-item bg-primary-subtle shadow-none me-3">
                        <span class="fas fa-wallet text-primary fs-4"></span>
                    </div>
                    <div>
                        <h6 class="text-primary fs-10 mb-0">Welcome, <?= htmlspecialchars($u_name); ?></h6>
                        <h4 class="text-primary fw-bold mb-0">Account Wallet Ledger <span class="text-info fw-medium">Statement logs</span></h4>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row g-3 mb-3">
    <div class="col-md-4">
        <div class="card border-0 shadow-sm border-top border-4 border-primary">
            <div class="card-body d-flex align-items-center justify-content-between py-3">
                <div>
                    <h6 class="text-muted text-uppercase fs-11 fw-bold mb-1">Available Funds</h6>
                    <h3 class="fw-bold text-primary mb-0">₹<?= number_format($wallet, 2); ?></h3>
                </div>
                <div class="avatar avatar-xl bg-primary-subtle rounded-circle d-flex align-items-center justify-content-center">
                    <span class="fas fa-money-check-alt text-primary fs-5"></span>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-4">
        <div class="card border-0 shadow-sm border-top border-4 border-success">
            <div class="card-body d-flex align-items-center justify-content-between py-3">
                <div>
                    <h6 class="text-muted text-uppercase fs-11 fw-bold mb-1">Cumulative Credits</h6>
                    <h3 class="fw-bold text-success mb-0">₹<?= number_format($totalCredits, 2); ?></h3>
                </div>
                <div class="avatar avatar-xl bg-success-subtle rounded-circle d-flex align-items-center justify-content-center">
                    <span class="fas fa-arrow-alt-circle-down text-success fs-5"></span>
                </div>
            </div>
        </div>
    </div>

    <div class="col-md-4">
        <div class="card border-0 shadow-sm border-top border-4 border-danger">
            <div class="card-body d-flex align-items-center justify-content-between py-3">
                <div>
                    <h6 class="text-muted text-uppercase fs-11 fw-bold mb-1">Cumulative Debits</h6>
                    <h3 class="fw-bold text-danger mb-0">₹<?= number_format($totalDebits, 2); ?></h3>
                </div>
                <div class="avatar avatar-xl bg-danger-subtle rounded-circle d-flex align-items-center justify-content-center">
                    <span class="fas fa-arrow-alt-circle-up text-danger fs-5"></span>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-12">
        <div class="card shadow-sm border-0">
            <div class="card-header bg-light d-flex align-items-center justify-content-between py-3">
                <h5 class="mb-0 text-dark fw-bold">
                    <i class="fas fa-list-alt me-2 text-primary"></i>Transaction History Logs
                </h5>
                <span class="badge bg-secondary font-monospace px-3 py-2">Total Operations: <?= $totalRows; ?></span>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-striped align-middle mb-0 text-center">
                        <thead class="table-light text-uppercase font-monospace fs-11 text-secondary">
                            <tr>
                                <th class="py-3">Log ID</th>
                                <th class="py-3">Activity Purpose / Intent Description</th>
                                <th class="py-3">Operation Variant</th>
                                <th class="py-3">Transaction Vol</th>
                                <th class="py-3">Resultant Balance</th>
                                <th class="py-3">Gateway Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($history && $history->num_rows > 0): ?>
                                <?php while ($row = $history->fetch_assoc()): ?>
                                    <tr>
                                        <td class="font-monospace fw-bold text-secondary">
                                            #<?= $row['id']; ?>
                                        </td>
                                        
                                        <td class="text-start ps-4">
                                            <div class="fw-semibold text-dark">
                                                <?= htmlspecialchars($row['purpose'] ?? 'Wallet Framework Adjustments'); ?>
                                            </div>
                                        </td>
                                        
                                        <td>
                                            <?php if (strcasecmp($row['type'], 'Credit') === 0): ?>
                                                <span class="badge badge-subtle-success px-2 py-1 fs-11 fw-bold">
                                                    <i class="fas fa-plus me-1"></i>Credit
                                                </span>
                                            <?php else: ?>
                                                <span class="badge badge-subtle-danger px-2 py-1 fs-11 fw-bold">
                                                    <i class="fas fa-minus me-1"></i>Debit
                                                </span>
                                            <?php endif; ?>
                                        </td>
                                        
                                        <td class="font-monospace fw-bold <?= strcasecmp($row['type'], 'Credit') === 0 ? 'text-success' : 'text-danger'; ?>">
                                            <?= strcasecmp($row['type'], 'Credit') === 0 ? '+' : '-'; ?>₹<?= number_format($row['amount'], 2); ?>
                                        </td>
                                        
                                        <td class="font-monospace text-dark fw-semibold">
                                            ₹<?= number_format($row['balance'], 2); ?>
                                        </td>
                                        
                                        <td>
                                            <?php 
                                            // Handle cases where status could be string tags '1' / '0' or names
                                            if ($row['status'] === '1' || strcasecmp($row['status'], 'Success') === 0) {
                                                echo '<span class="badge bg-success px-2 py-1"><i class="fas fa-check-circle me-1"></i>Success</span>';
                                            } elseif ($row['status'] === '0' || strcasecmp($row['status'], 'Pending') === 0) {
                                                echo '<span class="badge bg-warning text-dark px-2 py-1"><i class="fas fa-clock fa-spin me-1"></i>Pending</span>';
                                            } else {
                                                echo '<span class="badge bg-danger px-2 py-1"><i class="fas fa-times-circle me-1"></i>Failed</span>';
                                            }
                                            ?>
                                        </td>
                                    </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="6" class="text-muted py-4 text-center">
                                        <i class="fas fa-folder-open fs-2 mb-2 d-block text-400"></i>
                                        No transaction logs found for this account.
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <?php if ($totalPages > 1): ?>
                    <div class="card-footer bg-light d-flex justify-content-center py-3 border-top">
                        <nav aria-label="Statement navigation pagination loop container">
                            <ul class="pagination pagination-sm mb-0 shadow-none">
                                <li class="page-item <?= ($page <= 1) ? 'disabled' : ''; ?>">
                                    <a class="page-link" href="?page=<?= $page - 1; ?>" tabindex="-1">Previous</a>
                                </li>
                                
                                <?php 
                                $startPage = max(1, $page - 2);
                                $endPage = min($totalPages, $page + 2);
                                
                                for ($i = $startPage; $i <= $endPage; $i++): 
                                ?>
                                    <li class="page-item <?= ($page == $i) ? 'active' : ''; ?>">
                                        <a class="page-link" href="?page=<?= $i; ?>"><?= $i; ?></a>
                                    </li>
                                <?php endfor; ?>

                                <li class="page-item <?= ($page >= $totalPages) ? 'disabled' : ''; ?>">
                                    <a class="page-link" href="?page=<?= $page + 1; ?>">Next</a>
                                </li>
                            </ul>
                        </nav>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php
require_once('../titancore/TitanFooter.php');
ob_end_flush();
?>