<?php
session_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

require_once "include/db.php";
mysqli_set_charset($conn, "utf8mb4");

$userId = intval($_SESSION['user_id']);

// Fetch User Data for Theme and Balance
$sql = "SELECT * FROM users WHERE id = $userId LIMIT 1";
$result = mysqli_query($conn, $sql);
$currentUser = ($result && mysqli_num_rows($result) > 0) ? mysqli_fetch_assoc($result) : null;

if (!$currentUser) {
    header("Location: ../login.php");
    exit;
}

$dbTheme = $_SESSION['theme'] ?? ($currentUser['theme'] ?? '#3b82f6'); // Default Digital Blue
$userBalance = $currentUser['balance'] ?? 0;

// Fetch All Transactions
$txns = [];
$totalDeposits = 0;
$totalWithdrawals = 0;

$txnQuery = mysqli_query($conn, "SELECT * FROM transactions WHERE user_id = $userId ORDER BY created_at DESC");
while ($row = mysqli_fetch_assoc($txnQuery)) {
    // Calculate Stats for Completed TXNs
    if ($row['status'] === 'completed') {
        if ($row['type'] === 'deposit') $totalDeposits += $row['amount'];
        if ($row['type'] === 'withdrawal') $totalWithdrawals += $row['amount'];
    }
    
    $txns[] = [
        'id' => $row['id'],
        'ref' => $row['ref'],
        'type' => $row['type'], // 'deposit' or 'withdrawal'
        'amount' => (float)$row['amount'],
        'status' => $row['status'], // 'pending', 'completed', 'failed'
        'method' => $row['method'],
        'date' => date('M d, Y', strtotime($row['created_at'])),
        'time' => date('h:i A', strtotime($row['created_at']))
    ];
}
?>

<?php include "include/header.php"?>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>

<style>
    :root {
        --primary-theme: <?php echo htmlspecialchars($dbTheme, ENT_QUOTES, 'UTF-8'); ?>;
        --primary-rgb: <?php 
            $hex = ltrim($dbTheme, '#');
            $r = hexdec(substr($hex, 0, 2));
            $g = hexdec(substr($hex, 2, 2));
            $b = hexdec(substr($hex, 4, 2));
            echo "$r, $g, $b";
        ?>;
    }
    
    .text-theme { color: var(--primary-theme) !important; }
    .bg-theme { background-color: var(--primary-theme) !important; }
    .border-theme { border-color: var(--primary-theme) !important; }
    
    .glass-card {
        background: rgba(255, 255, 255, 0.8);
        backdrop-filter: blur(12px);
        border: 1px solid rgba(0, 0, 0, 0.05);
    }
    .dark .glass-card {
        background: rgba(15, 23, 42, 0.6);
        border: 1px solid rgba(255, 255, 255, 0.05);
    }

    .filter-btn {
        transition: all 0.3s ease;
    }
    .filter-btn.active {
        background: var(--primary-theme);
        color: white;
        box-shadow: 0 4px 15px -3px rgba(var(--primary-rgb), 0.4);
    }
    
    .txn-row {
        transition: all 0.2s ease;
    }
    .txn-row:hover {
        transform: translateX(4px);
        background: rgba(var(--primary-rgb), 0.03);
        border-color: rgba(var(--primary-rgb), 0.2);
    }
    
    @media print {
        .no-print { display: none !important; }
        body { background: white !important; color: black !important; }
        .glass-card { border: none !important; box-shadow: none !important; }
    }
</style>

<?php include "include/nav.php"?>

<div class="flex min-h-screen bg-slate-50 dark:bg-[#070b14] transition-colors duration-300" 
     x-data='{ 
        filter: "all", 
        currentPage: 1,
        itemsPerPage: 10,
        transactions: <?= json_encode($txns, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>,
        
        get filteredTxns() {
            if (this.filter === "all") return this.transactions;
            return this.transactions.filter(t => t.type === this.filter);
        },
        
        get totalPages() {
            return Math.max(1, Math.ceil(this.filteredTxns.length / this.itemsPerPage));
        },
        
        get paginatedTxns() {
            let start = (this.currentPage - 1) * this.itemsPerPage;
            let end = start + this.itemsPerPage;
            return this.filteredTxns.slice(start, end);
        },
        
        changeFilter(newFilter) {
            this.filter = newFilter;
            this.currentPage = 1; // Reset to page 1 when filter changes
        }
     }'>
  
  <?php include "include/sidebar.php"?>
  
  <main class="flex-1 min-w-0 md:ml-72 pb-24 md:pb-8">
    <div class="max-w-screen-xl mx-auto px-4 sm:px-6 py-8">

      <div class="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-8">
        <div>
          <h1 class="text-3xl font-black text-slate-900 dark:text-white tracking-tight">
            Account <span class="text-theme">History</span>
          </h1>
          <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">Review your incoming and outgoing transactions.</p>
        </div>
        <div class="no-print">
            <button onclick="window.print()" class="px-5 py-2.5 bg-slate-200 dark:bg-slate-800 text-slate-700 dark:text-slate-300 font-bold uppercase tracking-widest rounded-xl text-xs hover:bg-slate-300 dark:hover:bg-slate-700 transition-all flex items-center gap-2">
                <i data-lucide="download" class="w-4 h-4"></i> Export PDF
            </button>
        </div>
      </div>

      <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
        <div class="glass-card rounded-[2rem] p-6 shadow-sm relative overflow-hidden">
            <div class="absolute -right-4 -top-4 opacity-5">
                <i data-lucide="wallet" class="w-32 h-32 text-theme"></i>
            </div>
            <p class="text-[10px] font-black uppercase tracking-widest text-slate-400 mb-1">Available Ledger Balance</p>
            <h3 class="text-3xl font-black text-theme">$<?= number_format($userBalance, 2) ?></h3>
        </div>
        
        <div class="glass-card rounded-[2rem] p-6 shadow-sm border-l-4 border-l-emerald-500">
            <div class="flex justify-between items-start">
                <div>
                    <p class="text-[10px] font-black uppercase tracking-widest text-slate-400 mb-1">Total Inflow</p>
                    <h3 class="text-2xl font-black text-slate-900 dark:text-white">$<?= number_format($totalDeposits, 2) ?></h3>
                </div>
                <div class="w-10 h-10 rounded-full bg-emerald-500/10 flex items-center justify-center text-emerald-500">
                    <i data-lucide="arrow-down-left" class="w-5 h-5"></i>
                </div>
            </div>
        </div>

        <div class="glass-card rounded-[2rem] p-6 shadow-sm border-l-4 border-l-rose-500">
            <div class="flex justify-between items-start">
                <div>
                    <p class="text-[10px] font-black uppercase tracking-widest text-slate-400 mb-1">Total Outflow</p>
                    <h3 class="text-2xl font-black text-slate-900 dark:text-white">$<?= number_format($totalWithdrawals, 2) ?></h3>
                </div>
                <div class="w-10 h-10 rounded-full bg-rose-500/10 flex items-center justify-center text-rose-500">
                    <i data-lucide="arrow-up-right" class="w-5 h-5"></i>
                </div>
            </div>
        </div>
      </div>

      <div class="glass-card rounded-[2.5rem] border border-slate-200 dark:border-slate-800 shadow-xl overflow-hidden min-h-[500px]">
        
        <div class="p-6 border-b border-slate-200 dark:border-slate-800/50 flex flex-wrap gap-3 bg-slate-50/50 dark:bg-slate-900/20 no-print">
            <button @click="changeFilter('all')" :class="filter === 'all' ? 'active' : 'bg-slate-200 dark:bg-slate-800 text-slate-600 dark:text-slate-400'" class="filter-btn px-6 py-2.5 rounded-full text-[10px] font-black uppercase tracking-widest">
                All Activity
            </button>
            <button @click="changeFilter('deposit')" :class="filter === 'deposit' ? 'active' : 'bg-slate-200 dark:bg-slate-800 text-slate-600 dark:text-slate-400'" class="filter-btn px-6 py-2.5 rounded-full text-[10px] font-black uppercase tracking-widest">
                Deposits Only
            </button>
            <button @click="changeFilter('withdrawal')" :class="filter === 'withdrawal' ? 'active' : 'bg-slate-200 dark:bg-slate-800 text-slate-600 dark:text-slate-400'" class="filter-btn px-6 py-2.5 rounded-full text-[10px] font-black uppercase tracking-widest">
                Withdrawals Only
            </button>
        </div>

        <div class="p-6 md:p-8 space-y-4">
            
            <div x-show="filteredTxns.length === 0" style="display: none;" class="text-center py-20">
                <div class="w-20 h-20 bg-slate-100 dark:bg-slate-800 rounded-full flex items-center justify-center mx-auto mb-4 opacity-50">
                    <i data-lucide="search-x" class="w-10 h-10 text-slate-400"></i>
                </div>
                <h3 class="text-lg font-black text-slate-900 dark:text-white">No Transactions Found</h3>
                <p class="text-xs font-medium text-slate-500 mt-2">There are no records matching this filter.</p>
            </div>

            <template x-for="txn in paginatedTxns" :key="txn.id">
                <div class="txn-row flex flex-col md:flex-row md:items-center justify-between p-5 bg-white dark:bg-slate-900/50 rounded-2xl border border-slate-100 dark:border-slate-800 shadow-sm gap-4">
                    
                    <div class="flex items-center gap-4">
                        <div class="w-12 h-12 rounded-xl flex items-center justify-center flex-shrink-0"
                             :class="txn.type === 'deposit' ? 'bg-emerald-500/10 text-emerald-500' : 'bg-rose-500/10 text-rose-500'">
                             <i :data-lucide="txn.type === 'deposit' ? 'arrow-down-left' : 'arrow-up-right'" class="w-6 h-6"></i>
                        </div>
                        <div>
                            <h4 class="text-sm font-black text-slate-900 dark:text-white uppercase tracking-tight" 
                                x-text="txn.type === 'deposit' ? 'Account Credit' : 'Account Debit'"></h4>
                            <div class="flex items-center gap-2 mt-1">
                                <span class="text-[10px] font-bold text-slate-400" x-text="txn.method.toUpperCase()"></span>
                                <span class="text-slate-300 dark:text-slate-700">•</span>
                                <span class="text-[10px] font-bold text-slate-400" x-text="'REF: ' + txn.ref"></span>
                            </div>
                        </div>
                    </div>

                    <div class="flex flex-row md:flex-col items-center md:items-end justify-between w-full md:w-auto">
                        <div class="text-left md:text-right">
                            <h3 class="text-lg font-black"
                                :class="txn.type === 'deposit' ? 'text-emerald-500' : 'text-slate-900 dark:text-white'"
                                x-text="(txn.type === 'deposit' ? '+' : '-') + ' $' + txn.amount.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})">
                            </h3>
                            <p class="text-[9px] font-bold text-slate-400 tracking-widest mt-0.5" x-text="txn.date + ' • ' + txn.time"></p>
                        </div>
                        
                        <div class="mt-0 md:mt-2">
                            <span class="px-3 py-1 rounded-full text-[9px] font-black uppercase tracking-widest"
                                  :class="{
                                      'bg-emerald-500/10 text-emerald-500 border border-emerald-500/20': txn.status === 'completed',
                                      'bg-amber-500/10 text-amber-500 border border-amber-500/20': txn.status === 'pending',
                                      'bg-rose-500/10 text-rose-500 border border-rose-500/20': txn.status === 'failed',
                                  }"
                                  x-text="txn.status">
                            </span>
                        </div>
                    </div>

                </div>
            </template>
            
            <div x-show="totalPages > 1" style="display: none;" class="flex items-center justify-between pt-6 mt-6 border-t border-slate-200 dark:border-slate-800 no-print">
                <button @click="currentPage--" :disabled="currentPage === 1" 
                        class="px-4 py-2 rounded-xl text-xs font-bold bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400 disabled:opacity-50 disabled:cursor-not-allowed hover:bg-slate-200 dark:hover:bg-slate-700 transition-colors flex items-center gap-1">
                    <i data-lucide="chevron-left" class="w-4 h-4"></i> Prev
                </button>
                
                <span class="text-[10px] font-black tracking-widest uppercase text-slate-400">
                    Page <span x-text="currentPage" class="text-slate-900 dark:text-white"></span> of <span x-text="totalPages" class="text-slate-900 dark:text-white"></span>
                </span>

                <button @click="currentPage++" :disabled="currentPage === totalPages" 
                        class="px-4 py-2 rounded-xl text-xs font-bold bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400 disabled:opacity-50 disabled:cursor-not-allowed hover:bg-slate-200 dark:hover:bg-slate-700 transition-colors flex items-center gap-1">
                    Next <i data-lucide="chevron-right" class="w-4 h-4"></i>
                </button>
            </div>

        </div>
      </div>

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

<?php if(file_exists('include/footer.php')) include "include/footer.php"; ?>

<script src="https://unpkg.com/lucide@latest"></script>
<script>
    document.addEventListener('DOMContentLoaded', () => {
        lucide.createIcons();
    });

    // Re-initialize Lucide icons when Alpine paginates or filters
    document.addEventListener('alpine:initialized', () => {
        Alpine.effect(() => {
            setTimeout(() => {
                lucide.createIcons();
            }, 10);
        });
    });
</script>

</body>
</html>