<?php
$pageName  = "Account History";
include($_SERVER['DOCUMENT_ROOT'] . "/user/layout/header.php");

// Stats queries
$sql = "SELECT SUM(amount) FROM transactions WHERE user_id =:id AND transaction_type='credit' ORDER BY trans_id";
$stmt = $conn->prepare($sql);
$stmt->execute(['id' => $user_id]);
$total = $stmt->fetch(PDO::FETCH_NUM);
$inflow = $total[0] ?? 0;

$sql = "SELECT SUM(amount) FROM transactions WHERE user_id =:id AND transaction_type='debit' ORDER BY trans_id";
$stmt = $conn->prepare($sql);
$stmt->execute(['id' => $user_id]);
$total = $stmt->fetch(PDO::FETCH_NUM);
$outflow = $total[0] ?? 0;

// Pagination setup
$records_per_page = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$page = max(1, $page);
$offset = ($page - 1) * $records_per_page;

// Get total count
$count_sql = "SELECT COUNT(*) FROM transactions WHERE user_id =:user_id";
$count_stmt = $conn->prepare($count_sql);
$count_stmt->execute(['user_id' => $user_id]);
$total_records = $count_stmt->fetchColumn();
$total_pages = ceil($total_records / $records_per_page);

// Get paginated results
$sql2 = "SELECT * FROM transactions WHERE user_id =:user_id ORDER BY trans_id DESC LIMIT :limit OFFSET :offset";
$wire = $conn->prepare($sql2);
$wire->bindValue(':user_id', $user_id, PDO::PARAM_INT);
$wire->bindValue(':limit', $records_per_page, PDO::PARAM_INT);
$wire->bindValue(':offset', $offset, PDO::PARAM_INT);
$wire->execute();
?>
    <!-- Main Content Area -->
    <main class="pt-10 md:pt-14 pb-24 md:pb-8 min-h-screen lg:ml-80">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
            
<div x-data="{ 
    filterOpen: false, 
    selectedFilter: 'all',
    searchQuery: '',
    viewMode: 'list'
}" class="space-y-5">

    <!-- Page Header -->
    <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
        <div>
            <h1 class="text-2xl font-semibold text-[#0D1B23] mb-1">Transaction History</h1>
            <p class="text-sm text-[#7A7A7A]">Track and manage all your account activities</p>
        </div>
        
        <!-- Action Buttons -->
        <div class="flex items-center gap-3">
            <!-- Search -->
            <div class="relative hidden md:block">
                <input 
                    type="text" 
                    x-model="searchQuery"
                    placeholder="Search transactions..." 
                    class="pl-10 pr-4 py-2.5 bg-white border border-[#E0E5E5] rounded-lg text-sm text-[#0D1B23] placeholder-gray-500 focus:border-primary-500 focus:ring-1 focus:ring-forest-500/20 transition-colors w-64"
                >
                <i data-lucide="search" class="w-4 h-4 text-[#7A7A7A] absolute left-3 top-1/2 -translate-y-1/2"></i>
            </div>
            
            <!-- Filter Toggle -->
            <button 
                @click="filterOpen = !filterOpen"
                class="px-4 py-2.5 rounded-lg border border-[#E0E5E5] bg-white hover:bg-[#DFE5E5] transition-colors flex items-center gap-2"
            >
                <i data-lucide="filter" class="w-4 h-4 text-[#7A7A7A]"></i>
                <span class="text-sm font-medium text-[#4A4A4A] hidden sm:inline">Filter</span>
            </button>
            
            <!-- View Mode Toggle -->
            <button 
                @click="viewMode = viewMode === 'list' ? 'grid' : 'list'"
                class="px-4 py-2.5 rounded-lg border border-[#E0E5E5] bg-white hover:bg-[#DFE5E5] transition-colors hidden lg:block"
            >
                <i :data-lucide="viewMode === 'list' ? 'grid-3x3' : 'list'" class="w-4 h-4 text-[#7A7A7A]"></i>
            </button>
        </div>
    </div>

    <!-- Stats Cards -->
    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
        <!-- Inflow Card -->
        <div class="bg-white border border-[#E0E5E5] rounded-xl p-5">
            <div class="flex items-center gap-3 mb-2">
                <div class="w-9 h-9 rounded-lg bg-emerald-500/10 border border-emerald-500/20 flex items-center justify-center">
                    <i data-lucide="arrow-down-left" class="w-4 h-4 text-emerald-400"></i>
                </div>
                <span class="text-sm font-medium text-[#7A7A7A]">Total Inflow</span>
            </div>
            <p class="text-2xl font-semibold text-emerald-400">
                +<?= $currency ?><?= number_format($inflow, 2, '.', ',') ?>
            </p>
        </div>

        <!-- Outflow Card -->
        <div class="bg-white border border-[#E0E5E5] rounded-xl p-5">
            <div class="flex items-center gap-3 mb-2">
                <div class="w-9 h-9 rounded-lg bg-red-500/10 border border-red-500/20 flex items-center justify-center">
                    <i data-lucide="arrow-up-right" class="w-4 h-4 text-[#D55672]"></i>
                </div>
                <span class="text-sm font-medium text-[#7A7A7A]">Total Outflow</span>
            </div>
            <p class="text-2xl font-semibold text-[#D55672]">
                -<?= $currency ?><?= number_format($outflow, 2, '.', ',') ?>
            </p>
        </div>
    </div>

    <!-- Filter Panel -->
    <div 
        x-show="filterOpen" 
        x-transition:enter="transition ease-out duration-200"
        x-transition:enter-start="opacity-0 -translate-y-4"
        x-transition:enter-end="opacity-100 translate-y-0"
        class="bg-white border border-[#E0E5E5] rounded-xl p-4"
    >
        <div class="flex flex-wrap gap-2">
            <button 
                @click="selectedFilter = 'all'"
                :class="selectedFilter === 'all' ? 'bg-primary-500 text-white border-forest-500' : 'bg-white text-[#4A4A4A] border-[#C8D1D1] hover:bg-[#DFE5E5]'"
                class="px-4 py-2 rounded-lg text-sm font-medium transition-colors border"
            >
                All Transactions
            </button>
            <button 
                @click="selectedFilter = 'credit'"
                :class="selectedFilter === 'credit' ? 'bg-emerald-500/15 text-emerald-300 border-emerald-500/40' : 'bg-white text-[#4A4A4A] border-[#C8D1D1] hover:bg-[#DFE5E5]'"
                class="px-4 py-2 rounded-lg text-sm font-medium transition-colors border"
            >
                <i data-lucide="arrow-down-left" class="w-3.5 h-3.5 inline mr-1"></i>
                Credits
            </button>
            <button 
                @click="selectedFilter = 'debit'"
                :class="selectedFilter === 'debit' ? 'bg-red-500/15 text-[#D55672] border-red-500/40' : 'bg-white text-[#4A4A4A] border-[#C8D1D1] hover:bg-[#DFE5E5]'"
                class="px-4 py-2 rounded-lg text-sm font-medium transition-colors border"
            >
                <i data-lucide="arrow-up-right" class="w-3.5 h-3.5 inline mr-1"></i>
                Debits
            </button>
            <button 
                @click="selectedFilter = 'deposit'"
                :class="selectedFilter === 'deposit' ? 'bg-blue-500/15 text-blue-300 border-blue-500/40' : 'bg-white text-[#4A4A4A] border-[#C8D1D1] hover:bg-[#DFE5E5]'"
                class="px-4 py-2 rounded-lg text-sm font-medium transition-colors border"
            >
                <i data-lucide="plus-circle" class="w-3.5 h-3.5 inline mr-1"></i>
                Deposits
            </button>
            <button 
                @click="selectedFilter = 'pending'"
                :class="selectedFilter === 'pending' ? 'bg-amber-500/15 text-amber-300 border-amber-500/40' : 'bg-white text-[#4A4A4A] border-[#C8D1D1] hover:bg-[#DFE5E5]'"
                class="px-4 py-2 rounded-lg text-sm font-medium transition-colors border"
            >
                <i data-lucide="clock" class="w-3.5 h-3.5 inline mr-1"></i>
                Pending
            </button>
        </div>
    </div>

    <!-- Transactions List -->
    <div class="space-y-2" x-show="viewMode === 'list'">
        
        <?php if ($wire->rowCount() == 0) { ?>
            <!-- Empty State -->
            <div class="bg-white border border-[#E0E5E5] rounded-xl flex flex-col items-center justify-center py-16 px-4">
                <div class="w-16 h-16 rounded-full bg-[#DFE5E5] flex items-center justify-center mb-4">
                    <i data-lucide="file-text" class="w-7 h-7 text-[#7A7A7A]"></i>
                </div>
                <h3 class="text-lg font-medium text-[#0D1B23] mb-1">No Transactions Yet</h3>
                <p class="text-sm text-[#7A7A7A]">Your transaction history will appear here</p>
            </div>
        <?php } else { 
            while ($result = $wire->fetch(PDO::FETCH_ASSOC)) {
                $amount = $result['amount'];
                $isCredit = $result['transaction_type'] === 'credit';
                $trans_id = $result['trans_id'];
                $status = $result['status'] ?? 'completed';
        ?>
            <a href="/user/transaction-info.php?id=<?= $trans_id ?>" 
               class="bg-white border border-[#E0E5E5] rounded-lg p-4 md:p-5 hover:bg-[#DFE5E5] hover:border-[#C8D1D1] transition-colors block group"
               x-show="selectedFilter === 'all' || selectedFilter === '<?= $isCredit ? 'credit' : 'debit' ?>'<?= $status === 'pending' ? " || selectedFilter === 'pending'" : '' ?><?= strtolower($result['trans_type'] ?? '') === 'deposit' ? " || selectedFilter === 'deposit'" : '' ?>"
            >
                <div class="flex items-center gap-4">
                    <!-- Icon -->
                    <div class="flex-shrink-0 w-10 h-10 rounded-lg flex items-center justify-center
                        <?php if ($isCredit) { ?>
                            bg-emerald-500/10 border border-emerald-500/20
                        <?php } else { ?>
                            bg-red-500/10 border border-red-500/20
                        <?php } ?>
                    ">
                        <?php if ($isCredit) { ?>
                            <i data-lucide="arrow-down-left" class="w-4 h-4 text-emerald-400"></i>
                        <?php } else { ?>
                            <i data-lucide="arrow-up-right" class="w-4 h-4 text-[#D55672]"></i>
                        <?php } ?>
                    </div>
                    
                    <!-- Transaction Info -->
                    <div class="flex-1 min-w-0">
                        <div class="flex items-center gap-2 mb-1 flex-wrap">
                            <p class="font-medium text-[#0D1B23] text-sm">
                                <?= htmlspecialchars($result['trans_type']) ?>
                            </p>
                            
                            <!-- Status Badge -->
                            <?php if ($status === 'pending') { ?>
                                <span class="inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-semibold uppercase tracking-wider bg-amber-500/10 text-[#EBBC46] border border-amber-500/20">
                                    <i data-lucide="clock" class="w-3 h-3 mr-1"></i>
                                    Pending
                                </span>
                            <?php } elseif ($status === 'completed') { ?>
                                <span class="inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-semibold uppercase tracking-wider bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">
                                    <i data-lucide="check-circle" class="w-3 h-3 mr-1"></i>
                                    Completed
                                </span>
                            <?php } elseif ($status === 'failed') { ?>
                                <span class="inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-semibold uppercase tracking-wider bg-red-500/10 text-[#D55672] border border-red-500/20">
                                    <i data-lucide="x-circle" class="w-3 h-3 mr-1"></i>
                                    Failed
                                </span>
                            <?php } ?>
                        </div>
                        
                        <div class="flex items-center gap-2 text-xs text-[#7A7A7A]">
                            <i data-lucide="calendar" class="w-3 h-3"></i>
                            <span><?= date('M d, Y', strtotime($result['created_at'])) ?></span>
                            <span class="text-gray-700">·</span>
                            <i data-lucide="clock" class="w-3 h-3"></i>
                            <span><?= date('g:i A', strtotime($result['created_at'])) ?></span>
                        </div>
                    </div>
                    
                    <!-- Amount -->
                    <div class="flex-shrink-0 text-right">
                        <p class="font-semibold text-lg
                            <?= $isCredit ? 'text-emerald-400' : 'text-[#D55672]' ?>
                        ">
                            <?= $isCredit ? '+' : '-' ?><?= $currency ?><?= number_format($amount, 2, '.', ',') ?>
                        </p>
                        <p class="text-xs text-[#7A7A7A] mt-0.5">
                            <?php if ($status === 'pending') { ?>
                                Processing
                            <?php } elseif ($status === 'completed') { ?>
                                Completed
                            <?php } else { ?>
                                <?= ucfirst(htmlspecialchars($status)) ?>
                            <?php } ?>
                        </p>
                    </div>
                    
                    <!-- Arrow -->
                    <div class="flex-shrink-0 hidden md:block">
                        <i data-lucide="chevron-right" class="w-4 h-4 text-[#7A7A7A] group-hover:text-[#4A4A4A] transition-colors"></i>
                    </div>
                </div>
            </a>
        <?php 
            }
        } 
        ?>
    </div>

    <!-- Grid View -->
    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3" x-show="viewMode === 'grid'" style="display: none;">
        <?php 
        // Reset pointer for grid view
        $wire->execute();
        if ($wire->rowCount() > 0) {
            while ($result = $wire->fetch(PDO::FETCH_ASSOC)) {
                $amount = $result['amount'];
                $isCredit = $result['transaction_type'] === 'credit';
                $trans_id = $result['trans_id'];
                $status = $result['status'] ?? 'completed';
        ?>
            <a href="/user/transaction-info.php?id=<?= $trans_id ?>" 
               class="bg-white border border-[#E0E5E5] rounded-xl p-4 hover:bg-[#DFE5E5] hover:border-[#C8D1D1] transition-colors block"
               x-show="selectedFilter === 'all' || selectedFilter === '<?= $isCredit ? 'credit' : 'debit' ?>'"
            >
                <div class="flex items-center gap-3 mb-3">
                    <div class="w-9 h-9 rounded-lg flex items-center justify-center
                        <?= $isCredit ? 'bg-emerald-500/10 border border-emerald-500/20' : 'bg-red-500/10 border border-red-500/20' ?>
                    ">
                        <i data-lucide="<?= $isCredit ? 'arrow-down-left' : 'arrow-up-right' ?>" class="w-4 h-4 <?= $isCredit ? 'text-emerald-400' : 'text-[#D55672]' ?>"></i>
                    </div>
                    <div class="flex-1 min-w-0">
                        <p class="font-medium text-[#0D1B23] text-sm truncate"><?= htmlspecialchars($result['trans_type']) ?></p>
                        <p class="text-xs text-[#7A7A7A]"><?= date('M d, Y', strtotime($result['created_at'])) ?></p>
                    </div>
                </div>
                <p class="font-semibold text-lg <?= $isCredit ? 'text-emerald-400' : 'text-[#D55672]' ?>">
                    <?= $isCredit ? '+' : '-' ?><?= $currency ?><?= number_format($amount, 2, '.', ',') ?>
                </p>
            </a>
        <?php 
            }
        } 
        ?>
    </div>

    <!-- Pagination -->
    <?php if ($total_pages > 1) { ?>
    <div class="flex flex-col sm:flex-row items-center justify-between gap-4 bg-white border border-[#E0E5E5] rounded-xl p-4">
        <!-- Previous Button -->
        <div class="w-full sm:w-auto">
            <?php if ($page > 1) { ?>
                <a href="?page=<?= $page - 1 ?>" 
                   class="w-full sm:w-auto inline-flex items-center justify-center px-4 py-2.5 bg-primary-500 text-white font-medium text-sm rounded-lg hover:bg-primary-600 transition-colors">
                    <i data-lucide="chevron-left" class="w-4 h-4 mr-1.5"></i>
                    Previous
                </a>
            <?php } else { ?>
                <button disabled 
                        class="w-full sm:w-auto inline-flex items-center justify-center px-4 py-2.5 bg-[#DFE5E5] text-[#7A7A7A] font-medium text-sm rounded-lg cursor-not-allowed">
                    <i data-lucide="chevron-left" class="w-4 h-4 mr-1.5"></i>
                    Previous
                </button>
            <?php } ?>
        </div>

        <!-- Page Info -->
        <div class="text-center">
            <span class="text-sm font-medium text-[#4A4A4A]">
                Page <span class="font-semibold text-[#0D1B23]"><?= $page ?></span> of <span class="font-semibold text-[#0D1B23]"><?= $total_pages ?></span>
            </span>
            <p class="text-xs text-[#7A7A7A] mt-0.5">
                Showing <?= min($offset + 1, $total_records) ?>–<?= min($offset + $records_per_page, $total_records) ?> of <?= $total_records ?> transactions
            </p>
        </div>

        <!-- Next Button -->
        <div class="w-full sm:w-auto sm:text-right">
            <?php if ($page < $total_pages) { ?>
                <a href="?page=<?= $page + 1 ?>" 
                   class="w-full sm:w-auto inline-flex items-center justify-center px-4 py-2.5 bg-primary-500 text-white font-medium text-sm rounded-lg hover:bg-primary-600 transition-colors">
                    Next
                    <i data-lucide="chevron-right" class="w-4 h-4 ml-1.5"></i>
                </a>
            <?php } else { ?>
                <button disabled 
                        class="w-full sm:w-auto inline-flex items-center justify-center px-4 py-2.5 bg-[#DFE5E5] text-[#7A7A7A] font-medium text-sm rounded-lg cursor-not-allowed">
                    Next
                    <i data-lucide="chevron-right" class="w-4 h-4 ml-1.5"></i>
                </button>
            <?php } ?>
        </div>

        <!-- Page Numbers (desktop) -->
        <div class="hidden sm:flex items-center justify-center w-full mt-2 gap-1">
            <?php
            $start_page = max(1, $page - 2);
            $end_page = min($total_pages, $page + 2);
            
            if ($start_page > 1) {
                echo '<a href="?page=1" class="px-3 py-1.5 rounded-lg text-sm font-medium text-[#4A4A4A] hover:bg-[#DFE5E5] transition-colors">1</a>';
                if ($start_page > 2) {
                    echo '<span class="px-2 text-[#7A7A7A]">...</span>';
                }
            }
            
            for ($i = $start_page; $i <= $end_page; $i++) {
                if ($i == $page) {
                    echo '<span class="px-3 py-1.5 rounded-lg text-sm font-semibold bg-primary-500 text-white">' . $i . '</span>';
                } else {
                    echo '<a href="?page=' . $i . '" class="px-3 py-1.5 rounded-lg text-sm font-medium text-[#4A4A4A] hover:bg-[#DFE5E5] transition-colors">' . $i . '</a>';
                }
            }
            
            if ($end_page < $total_pages) {
                if ($end_page < $total_pages - 1) {
                    echo '<span class="px-2 text-[#7A7A7A]">...</span>';
                }
                echo '<a href="?page=' . $total_pages . '" class="px-3 py-1.5 rounded-lg text-sm font-medium text-[#4A4A4A] hover:bg-[#DFE5E5] transition-colors">' . $total_pages . '</a>';
            }
            ?>
        </div>
    </div>
    <?php } ?>

</div>
        </div>
    </main>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        lucide.createIcons();
    });
</script>

<?php
include($_SERVER['DOCUMENT_ROOT'] . "/user/layout/footer.php");
?>