<?php include 'master.php'; ?>
<?php
$_user_acc  = getUserDetails('acc_no', $_SESSION['email']);
$_per_page  = in_array((int)($_GET['per_page'] ?? 15), [15, 25, 50, 100]) ? (int)($_GET['per_page'] ?? 15) : 15;
$_order     = ($_GET['order'] ?? 'desc') === 'asc' ? 'ASC' : 'DESC';
$_page      = max(1, (int)($_GET['page'] ?? 1));
$_offset    = ($_page - 1) * $_per_page;
$_filter_status    = $_GET['status']    ?? '';
$_filter_date_from = $_GET['date_from'] ?? '';
$_filter_date_to   = $_GET['date_to']   ?? '';

$_where  = "WHERE account_number = ?";
$_params = [$_user_acc];
$_types  = "s";
if ($_filter_status) {
    $_where .= " AND status = ?"; $_params[] = $_filter_status; $_types .= "s";
}
if ($_filter_date_from) {
    $_where .= " AND DATE(date_added) >= ?"; $_params[] = $_filter_date_from; $_types .= "s";
}
if ($_filter_date_to) {
    $_where .= " AND DATE(date_added) <= ?"; $_params[] = $_filter_date_to; $_types .= "s";
}

$_ct = $connect->prepare("SELECT COUNT(*) FROM transactions $_where");
$_ct->bind_param($_types, ...$_params);
$_ct->execute();
$_total = (int)$_ct->get_result()->fetch_row()[0];
$_ct->close();
$_total_pages = (int)ceil($_total / $_per_page);

$_qt = $connect->prepare("SELECT * FROM transactions $_where ORDER BY date_added $_order LIMIT ? OFFSET ?");
$_qparams = array_merge($_params, [$_per_page, $_offset]);
$_qt->bind_param($_types . "ii", ...$_qparams);
$_qt->execute();
$_transactions = $_qt->get_result()->fetch_all(MYSQLI_ASSOC);
$_qt->close();

$_from_row = $_total > 0 ? $_offset + 1 : 0;
$_to_row   = min($_offset + $_per_page, $_total);

function _txnClasses(array $txn): array {
    $credit   = strtolower($txn['transaction_type']) === 'credit';
    $iconBg   = $credit
        ? 'bg-green-100 dark:bg-green-900/30 text-green-600 dark:text-green-400'
        : 'bg-red-100 dark:bg-red-900/30 text-red-500 dark:text-red-400';
    $amtColor = $credit ? 'text-green-600 dark:text-green-400' : 'text-red-500 dark:text-red-400';
    $statusMap = [
        'Success' => 'bg-green-100 dark:bg-green-900/40 text-green-700 dark:text-green-300',
        'Pending' => 'bg-yellow-100 dark:bg-yellow-900/40 text-yellow-700 dark:text-yellow-300',
        'Failed'  => 'bg-red-100 dark:bg-red-900/40 text-red-700 dark:text-red-300',
    ];
    $statusCls = $statusMap[$txn['status']] ?? 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300';
    $sym      = $GLOBALS['_curr_sym'] ?? currencySymbol($_SESSION['currency'] ?? 'USD');
    $isCrypto = (($txn['other_bank_name'] ?? '') === 'Cryptocurrency');
    $amtStr   = $isCrypto
        ? number_format((float)$txn['amount'], 8) . ' BTC'
        : $sym . number_format((float)$txn['amount'], 2);
    return [
        'icon'      => $credit ? 'fa-arrow-down' : 'fa-arrow-up',
        'icon_bg'   => $iconBg,
        'amt_color' => $amtColor,
        'prefix'    => $credit ? '+' : '-',
        'status'    => $statusCls,
        'amount'    => ($credit ? '+' : '-') . $amtStr,
        'date'      => date('M d, Y H:i', strtotime($txn['date_added'])),
    ];
}

function _paginationLinks(int $currentPage, int $totalPages): string {
    if ($totalPages <= 1) return '';
    $get  = $_GET ?? [];
    $html = '<nav class="flex space-x-1">';
    $base = 'px-3 py-1.5 text-sm rounded-lg transition-colors';
    $inact = "$base bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 text-gray-600 dark:text-gray-300 hover:bg-primary-50 dark:hover:bg-primary-900/30";
    $act   = "$base bg-primary-500 text-white shadow-sm";
    if ($currentPage > 1) {
        $q = http_build_query(array_merge($get, ['page' => $currentPage - 1]));
        $html .= "<a href='?$q' class='$inact'>&laquo;</a>";
    }
    for ($i = max(1, $currentPage - 2); $i <= min($totalPages, $currentPage + 2); $i++) {
        $q = http_build_query(array_merge($get, ['page' => $i]));
        $html .= "<a href='?$q' class='" . ($i === $currentPage ? $act : $inact) . "'>$i</a>";
    }
    if ($currentPage < $totalPages) {
        $q = http_build_query(array_merge($get, ['page' => $currentPage + 1]));
        $html .= "<a href='?$q' class='$inact'>&raquo;</a>";
    }
    return $html . '</nav>';
}
?>

       
                    
    

                <!-- Main Content -->
                <main class="flex-1 overflow-y-auto bg-gray-50 dark:bg-gray-900 min-h-0">
                    <div class="h-full overflow-y-auto">
                        
<div class="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-100 dark:from-slate-900 dark:via-slate-800 dark:to-slate-900 p-4 lg:p-6">
    <div class="max-w-8xl mx-auto" x-data="transactionApp()">
        <!-- Mobile Header -->
        <div class="lg:hidden" x-data="{ showMobileNotifications: false }">
    <!-- Header Section -->
    <div class="flex items-center justify-between mb-6">
        <div class="flex items-center space-x-2">
                            <!-- Back Button -->
                <a href="../dashboard" class="w-10 h-10 bg-gray-100 dark:bg-gray-800 rounded-full flex items-center justify-center backdrop-blur-sm transition-all duration-200 hover:bg-gray-200 dark:hover:bg-gray-700 mr-2">
                    <i class="fa-solid fa-arrow-left text-gray-700 dark:text-gray-300 text-base"></i>
                </a>
                        
            <div>
                                    <!-- Custom Title -->
                    <p class="text-gray-900 dark:text-white font-semibold text-base">Transactions</p>
                            </div>
        </div>
        
        <div class="flex items-center space-x-2">
              <!-- Dark Mode Toggle -->
             <!--   <button @click="toggleDarkMode()" 
                        class="w-10 h-10 bg-white/10 dark:bg-white/20 rounded-full flex items-center justify-center backdrop-blur-sm transition-all duration-200 hover:bg-white/20 dark:hover:bg-white/30">
                    <i x-show="!darkMode" class="fa-solid fa-moon text-white text-base"></i>
                    <i x-show="darkMode" class="fa-solid fa-sun text-yellow-400 text-base"></i>
                </button> 

                <!-- Notifications -->
             <!--   <div class="relative">
                    <button @click="showMobileNotifications = !showMobileNotifications" class="w-10 h-10 bg-white/10 dark:bg-white/20 rounded-full flex items-center justify-center backdrop-blur-sm transition-all duration-200 hover:bg-white/20 dark:hover:bg-white/30">
                        <i class="fa-solid fa-bell text-white text-base"></i>
                    </button>
                                                        </div>-->
                    </div>
    </div>

            <!-- Mobile Notifications Panel -->
        <div x-show="showMobileNotifications" 
             x-transition:enter="transition ease-out duration-300" 
             x-transition:enter-start="opacity-0 -translate-y-4" 
             x-transition:enter-end="opacity-100 translate-y-0"
             x-transition:leave="transition ease-in duration-200" 
             x-transition:leave-start="opacity-100 translate-y-0" 
             x-transition:leave-end="opacity-0 -translate-y-4"
             class="fixed inset-0 z-50 bg-black/20 backdrop-blur-sm" 
             @click="showMobileNotifications = false">
            
            <div @click.stop class="absolute top-0 left-0 right-0 bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 dark:from-slate-950 dark:via-slate-900 dark:to-slate-950 text-white rounded-b-3xl shadow-2xl dark:shadow-slate-900/50 max-h-[80vh] overflow-hidden">
                <!-- Header -->
                <div class="flex items-center justify-between p-4 border-b border-white/10 dark:border-white/20">
                    <div class="flex items-center space-x-3">
                        <div class="w-10 h-10 bg-white/10 dark:bg-white/20 rounded-2xl flex items-center justify-center">
                            <i class="fa-solid fa-bell text-white text-sm"></i>
                        </div>
                        <div>
                            <h3 class="text-lg font-bold text-white">Notifications</h3>
                                                                                        <p class="text-xs text-white/60">All caught up!</p>
                                                    </div>
                    </div>
                    <button @click="showMobileNotifications = false" class="w-8 h-8 bg-white/10 dark:bg-white/20 rounded-xl flex items-center justify-center hover:bg-white/20 dark:hover:bg-white/30 transition-colors">
                        <i class="fa-solid fa-times text-white text-sm"></i>
                    </button>
                </div>

                <!-- Notifications List -->
                <div class="overflow-y-auto max-h-96 custom-scrollbar">
                                        
                                        <div class="p-8 text-center">
                        <div class="w-16 h-16 bg-white/10 dark:bg-white/20 rounded-3xl flex items-center justify-center mx-auto mb-4">
                            <i class="fa-solid fa-bell-slash text-white/40 dark:text-white/60 text-2xl"></i>
                        </div>
                        <p class="text-white font-semibold mb-1">No notifications yet</p>
                        <p class="text-xs text-white/60 dark:text-white/70">We'll notify you when something happens</p>
                    </div>
                                    </div>
                
                <!-- Footer Actions -->
                            </div>
        </div>
    </div> 
        <!-- Alerts -->
                
    <!-- Desktop Header -->
    <div class="hidden lg:flex items-center justify-between mb-6">
        <h1 class="text-2xl font-bold text-gray-900 dark:text-white">Transactions</h1>
        <div class="flex space-x-3">
            <button 
                @click="showFilterModal = true" 
                class="inline-flex items-center px-4 py-2 bg-white/80 dark:bg-gray-800/80 backdrop-blur-xl border border-gray-200/50 dark:border-gray-700/50 shadow-sm text-sm font-medium rounded-xl text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700/50 focus:outline-none transition-all duration-200">
                <i class="fa-solid fa-filter text-sm mr-2"></i> Filter
            </button>
            <button 
                @click="showExportModal = true" 
                class="inline-flex items-center px-4 py-2 bg-gradient-to-r from-primary-500 to-primary-600 hover:from-primary-600 hover:to-primary-700 shadow-lg shadow-primary-500/25 dark:shadow-primary-900/50 text-sm font-medium rounded-xl text-white focus:outline-none transition-all duration-200 transform hover:scale-105">
                <i class="fa-solid fa-download text-sm mr-2"></i> Export
            </button>
        </div>
    </div>

    <!-- Mobile Action Buttons -->
    <div class="lg:hidden flex space-x-3 mb-6">
        <button 
            @click="showFilterModal = true" 
            class="flex-1 inline-flex items-center justify-center px-4 py-2.5 bg-white/80 dark:bg-gray-800/80 backdrop-blur-xl border border-gray-200/50 dark:border-gray-700/50 shadow-sm text-sm font-medium rounded-xl text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700/50 focus:outline-none transition-all duration-200">
            <i class="fa-solid fa-filter text-sm mr-2"></i> Filter
        </button>
        <button 
            @click="showExportModal = true" 
            class="flex-1 inline-flex items-center justify-center px-4 py-2.5 bg-gradient-to-r from-primary-500 to-primary-600 hover:from-primary-600 hover:to-primary-700 shadow-lg shadow-primary-500/25 dark:shadow-primary-900/50 text-sm font-medium rounded-xl text-white focus:outline-none transition-all duration-200">
            <i class="fa-solid fa-download text-sm mr-2"></i> Export
        </button>
    </div>

    <!-- Desktop Transactions Table -->
    <div class="hidden lg:block bg-white/80 dark:bg-gray-800/80 backdrop-blur-xl rounded-2xl shadow-lg dark:shadow-gray-900/50 border border-white/20 dark:border-gray-700/50 overflow-hidden">
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200/50 dark:divide-gray-700/50">
                <thead class="bg-gradient-to-r from-primary-50/80 to-primary-100/50 dark:from-primary-900/30 dark:to-primary-800/30">
                    <tr>
                        <th scope="col" class="px-4 py-3 text-left text-xs font-semibold text-primary-900 dark:text-primary-100 uppercase tracking-wider"></th>
                        <th scope="col" class="px-4 py-3 text-left text-xs font-semibold text-primary-900 dark:text-primary-100 uppercase tracking-wider">Amount</th>
                        <th scope="col" class="px-4 py-3 text-left text-xs font-semibold text-primary-900 dark:text-primary-100 uppercase tracking-wider">Type</th>
                        <th scope="col" class="px-4 py-3 text-left text-xs font-semibold text-primary-900 dark:text-primary-100 uppercase tracking-wider">Status</th>
                        <th scope="col" class="px-4 py-3 text-left text-xs font-semibold text-primary-900 dark:text-primary-100 uppercase tracking-wider">Reference</th>
                        <th scope="col" class="px-4 py-3 text-left text-xs font-semibold text-primary-900 dark:text-primary-100 uppercase tracking-wider">Description</th>
                        <th scope="col" class="px-4 py-3 text-left text-xs font-semibold text-primary-900 dark:text-primary-100 uppercase tracking-wider">Date</th>
                        <th scope="col" class="px-4 py-3 text-left text-xs font-semibold text-primary-900 dark:text-primary-100 uppercase tracking-wider">Action</th>
                    </tr>
                </thead>
                <tbody class="bg-white/50 dark:bg-gray-800/50 divide-y divide-gray-200/30 dark:divide-gray-700/30">
                <?php if (empty($_transactions)): ?>
                    <tr>
                        <td colspan="8" class="px-4 py-12 text-center">
                            <div class="flex flex-col items-center justify-center">
                                <div class="w-16 h-16 bg-primary-100 dark:bg-primary-900/50 rounded-2xl flex items-center justify-center mb-4">
                                    <i class="fa-solid fa-receipt text-primary-500 dark:text-primary-400 text-2xl"></i>
                                </div>
                                <p class="text-lg font-semibold text-gray-900 dark:text-white mb-1">No transactions found</p>
                                <p class="text-sm text-gray-500 dark:text-gray-400">Try adjusting your search or filter parameters</p>
                            </div>
                        </td>
                    </tr>
                <?php else: foreach ($_transactions as $_txn):
                    $_c = _txnClasses($_txn);
                ?>
                    <tr class="hover:bg-gray-50/80 dark:hover:bg-gray-700/50 transition-colors">
                        <td class="px-4 py-3">
                            <div class="w-9 h-9 rounded-full <?php echo $_c['icon_bg']; ?> flex items-center justify-center">
                                <i class="fa-solid <?php echo $_c['icon']; ?> text-xs"></i>
                            </div>
                        </td>
                        <td class="px-4 py-3">
                            <span class="text-sm font-bold <?php echo $_c['amt_color']; ?>"><?php echo $_c['amount']; ?></span>
                        </td>
                        <td class="px-4 py-3">
                            <span class="text-sm text-gray-900 dark:text-white"><?php echo htmlspecialchars($_txn['transaction_type']); ?></span>
                        </td>
                        <td class="px-4 py-3">
                            <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium <?php echo $_c['status']; ?>">
                                <?php echo htmlspecialchars($_txn['status']); ?>
                            </span>
                        </td>
                        <td class="px-4 py-3">
                            <span class="text-xs text-gray-500 dark:text-gray-400 font-mono"><?php echo htmlspecialchars($_txn['account_number']); ?></span>
                        </td>
                        <td class="px-4 py-3 max-w-xs">
                            <span class="text-sm text-gray-600 dark:text-gray-300 truncate block"><?php echo htmlspecialchars($_txn['transaction_details'] ?? '—'); ?></span>
                        </td>
                        <td class="px-4 py-3 whitespace-nowrap">
                            <span class="text-sm text-gray-500 dark:text-gray-400"><?php echo $_c['date']; ?></span>
                        </td>
                        <td class="px-4 py-3">
                            <span class="text-xs font-medium text-gray-500 dark:text-gray-400"><?php echo htmlspecialchars($_txn['account_type'] ?? '—'); ?></span>
                        </td>
                    </tr>
                <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>
        
        <!-- Desktop Pagination -->
        <div class="border-t border-gray-200/50 dark:border-gray-700/50 px-4 py-4 bg-gradient-to-r from-primary-50/30 to-primary-100/20 dark:from-primary-900/20 dark:to-primary-800/20">
            <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between">
                <div class="text-sm text-gray-600 dark:text-gray-400 mb-4 sm:mb-0">
                    Showing
                    <span class="font-semibold text-primary-900 dark:text-primary-100"><?php echo $_from_row; ?></span>
                    to
                    <span class="font-semibold text-primary-900 dark:text-primary-100"><?php echo $_to_row; ?></span>
                    of
                    <span class="font-semibold text-primary-900 dark:text-primary-100"><?php echo $_total; ?></span>
                    results
                </div>
                <div class="flex-1 flex justify-center sm:justify-end">
                    <?php echo _paginationLinks($_page, $_total_pages); ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Mobile Transactions List -->
    <div class="lg:hidden space-y-3">
        <?php if (empty($_transactions)): ?>
            <div class="bg-white/80 dark:bg-gray-800/80 backdrop-blur-xl rounded-2xl shadow-lg dark:shadow-gray-900/50 border border-white/20 dark:border-gray-700/50 py-12">
                <div class="flex flex-col items-center justify-center text-center">
                    <div class="w-16 h-16 bg-primary-100 dark:bg-primary-900/50 rounded-2xl flex items-center justify-center mb-4">
                        <i class="fa-solid fa-receipt text-primary-500 dark:text-primary-400 text-2xl"></i>
                    </div>
                    <p class="text-lg font-semibold text-gray-900 dark:text-white mb-1">No transactions found</p>
                    <p class="text-sm text-gray-500 dark:text-gray-400 max-w-xs">Try adjusting your search or filter parameters</p>
                </div>
            </div>
        <?php else: foreach ($_transactions as $_txn):
            $_c = _txnClasses($_txn);
        ?>
            <div class="bg-white/80 dark:bg-gray-800/80 backdrop-blur-xl rounded-2xl shadow-lg dark:shadow-gray-900/50 border border-white/20 dark:border-gray-700/50 p-4">
                <div class="flex items-center space-x-3">
                    <div class="w-10 h-10 rounded-full <?php echo $_c['icon_bg']; ?> flex items-center justify-center flex-shrink-0">
                        <i class="fa-solid <?php echo $_c['icon']; ?> text-xs"></i>
                    </div>
                    <div class="flex-1 min-w-0">
                        <div class="flex items-center justify-between">
                            <p class="text-sm font-semibold text-gray-900 dark:text-white"><?php echo htmlspecialchars($_txn['transaction_type']); ?></p>
                            <p class="text-sm font-bold <?php echo $_c['amt_color']; ?>"><?php echo $_c['amount']; ?></p>
                        </div>
                        <div class="flex items-center justify-between mt-1">
                            <p class="text-xs text-gray-500 dark:text-gray-400 truncate"><?php echo htmlspecialchars($_txn['transaction_details'] ?? '—'); ?></p>
                            <span class="ml-2 flex-shrink-0 inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium <?php echo $_c['status']; ?>">
                                <?php echo htmlspecialchars($_txn['status']); ?>
                            </span>
                        </div>
                        <p class="text-xs text-gray-400 dark:text-gray-500 mt-1"><?php echo $_c['date']; ?></p>
                    </div>
                </div>
            </div>
        <?php endforeach; endif; ?>

        <!-- Mobile Pagination -->
        <?php if ($_total_pages > 1): ?>
            <div class="flex justify-center pt-2">
                <?php echo _paginationLinks($_page, $_total_pages); ?>
            </div>
        <?php endif; ?>
    </div>

    <!-- Filter Modal -->
    <div 
        x-show="showFilterModal" 
        x-transition:enter="transition ease-out duration-300"
        x-transition:enter-start="opacity-0"
        x-transition:enter-end="opacity-100"
        x-transition:leave="transition ease-in duration-200"
        x-transition:leave-start="opacity-100"
        x-transition:leave-end="opacity-0"
        class="fixed inset-0 z-50 overflow-y-auto" 
        aria-labelledby="filter-title" 
        role="dialog" 
        aria-modal="true">
        <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div 
                x-show="showFilterModal" 
                x-transition:enter="transition ease-out duration-300"
                x-transition:enter-start="opacity-0"
                x-transition:enter-end="opacity-100"
                x-transition:leave="transition ease-in duration-200"
                x-transition:leave-start="opacity-100"
                x-transition:leave-end="opacity-0"
                class="fixed inset-0 bg-black/20 backdrop-blur-sm transition-opacity" 
                @click="showFilterModal = false" 
                aria-hidden="true">
            </div>
            
            <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
            
            <div 
                x-show="showFilterModal" 
                x-transition:enter="transition ease-out duration-300"
                x-transition:enter-start="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
                x-transition:enter-end="opacity-100 translate-y-0 sm:scale-100"
                x-transition:leave="transition ease-in duration-200"
                x-transition:leave-start="opacity-100 translate-y-0 sm:scale-100"
                x-transition:leave-end="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
                class="inline-block align-bottom bg-white/95 dark:bg-gray-800/95 backdrop-blur-xl rounded-2xl px-4 pt-5 pb-4 text-left overflow-hidden shadow-2xl dark:shadow-gray-900/50 border border-white/20 dark:border-gray-700/50 transform transition-all sm:my-8 sm:align-middle w-full max-w-md mx-auto sm:p-6">
                
                <div class="absolute top-0 right-0 pt-4 pr-4">
                    <button
                        @click="showFilterModal = false"
                        type="button"
                        class="bg-white/80 dark:bg-gray-800/80 backdrop-blur-sm rounded-xl text-gray-400 dark:text-gray-500 hover:text-gray-500 dark:hover:text-gray-400 focus:outline-none p-2 transition-colors">
                        <span class="sr-only">Close</span>
                        <i class="fa-solid fa-times text-sm"></i>
                    </button>
                </div>
                
                <div class="text-center mb-5">
                    <div class="mx-auto flex items-center justify-center h-16 w-16 rounded-2xl bg-primary-100 dark:bg-primary-900/50 mb-4">
                        <i class="fa-solid fa-filter text-2xl text-primary-600 dark:text-primary-400"></i>
                    </div>
                    <h3 class="text-lg font-semibold text-gray-900 dark:text-white" id="filter-title">Filter Transactions</h3>
                    <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">Customize your transaction view</p>
                </div>
                
                <form action="accounthistory" method="GET" id="filterForm">
                    <div class="mt-5 space-y-4">
                        <div>
                            <label for="date-range" class="block text-sm font-semibold text-gray-900 dark:text-white mb-2">Date Range</label>
                            <div class="grid grid-cols-2 gap-3">
                                <div>
                                    <label for="date-from" class="block text-xs text-gray-600 dark:text-gray-400 mb-1">From</label>
                                    <input 
                                        type="date" 
                                        id="date-from" 
                                        name="date_from"
                                        value="<?php echo htmlspecialchars($_filter_date_from); ?>"
                                        x-model="dateFrom"
                                        class="block w-full bg-white/80 dark:bg-gray-700/80 backdrop-blur-sm border border-gray-200/50 dark:border-gray-600/50 rounded-xl p-2.5 text-gray-900 dark:text-white focus:ring-2 focus:ring-primary-500/50 focus:border-primary-500 dark:focus:border-primary-400 transition-all duration-200"
                                    />
                                </div>
                                <div>
                                    <label for="date-to" class="block text-xs text-gray-600 dark:text-gray-400 mb-1">To</label>
                                    <input 
                                        type="date" 
                                        id="date-to" 
                                        name="date_to"
                                        value="<?php echo htmlspecialchars($_filter_date_to); ?>"
                                        x-model="dateTo"
                                        class="block w-full bg-white/80 dark:bg-gray-700/80 backdrop-blur-sm border border-gray-200/50 dark:border-gray-600/50 rounded-xl p-2.5 text-gray-900 dark:text-white focus:ring-2 focus:ring-primary-500/50 focus:border-primary-500 dark:focus:border-primary-400 transition-all duration-200"
                                    />
                                </div>
                            </div>
                        </div>
                        
                        <div>
                            <label for="status" class="block text-sm font-semibold text-gray-900 dark:text-white mb-2">Status</label>
                            <select 
                                id="status"
                                name="status"
                                x-model="status"
                                class="block w-full bg-white/80 dark:bg-gray-700/80 backdrop-blur-sm border border-gray-200/50 dark:border-gray-600/50 rounded-xl p-2.5 text-gray-900 dark:text-white focus:ring-2 focus:ring-primary-500/50 focus:border-primary-500 dark:focus:border-primary-400 transition-all duration-200">
                                <option value="">Select status</option>
                                <?php foreach (['Success','Pending','Failed','Completed','Processed','Rejected'] as $_s): ?>
                                <option value="<?php echo $_s; ?>" <?php echo $_filter_status === $_s ? 'selected' : ''; ?>><?php echo $_s; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div>
                            <label for="order" class="block text-sm font-semibold text-gray-900 dark:text-white mb-2">Sort by</label>
                            <select 
                                id="order"
                                name="order"
                                x-model="orderBy"
                                class="block w-full bg-white/80 dark:bg-gray-700/80 backdrop-blur-sm border border-gray-200/50 dark:border-gray-600/50 rounded-xl p-2.5 text-gray-900 dark:text-white focus:ring-2 focus:ring-primary-500/50 focus:border-primary-500 dark:focus:border-primary-400 transition-all duration-200">
                                <option value="asc"  <?php echo ($_GET['order'] ?? '') === 'asc'  ? 'selected' : ''; ?>>Oldest first (ASC)</option>
                                <option value="desc" <?php echo ($_GET['order'] ?? 'desc') !== 'asc' ? 'selected' : ''; ?>>Newest first (DESC)</option>
                            </select>
                        </div>
                        
                        <div>
                            <label for="per_page" class="block text-sm font-semibold text-gray-900 dark:text-white mb-2">Per page</label>
                            <select 
                                id="per_page"
                                name="per_page"
                                x-model="perPage"
                                class="block w-full bg-white/80 dark:bg-gray-700/80 backdrop-blur-sm border border-gray-200/50 dark:border-gray-600/50 rounded-xl p-2.5 text-gray-900 dark:text-white focus:ring-2 focus:ring-primary-500/50 focus:border-primary-500 dark:focus:border-primary-400 transition-all duration-200">
                                <?php foreach ([15, 25, 50, 100] as $_pp): ?>
                                <option value="<?php echo $_pp; ?>" <?php echo $_per_page === $_pp ? 'selected' : ''; ?>><?php echo $_pp; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <!-- Preserve search term if it exists -->
                                            </div>
                    
                    <div class="mt-6 flex justify-end space-x-3">
                        <button 
                            type="button"
                            @click="showFilterModal = false"
                            class="inline-flex items-center px-4 py-2 bg-white/80 dark:bg-gray-700/80 backdrop-blur-sm border border-gray-200/50 dark:border-gray-600/50 shadow-sm text-sm font-medium rounded-xl text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-600/50 focus:outline-none transition-all duration-200">
                            Cancel
                        </button>
                        <button 
                            type="submit"
                            class="inline-flex items-center px-4 py-2 bg-gradient-to-r from-primary-500 to-primary-600 hover:from-primary-600 hover:to-primary-700 shadow-lg shadow-primary-500/25 dark:shadow-primary-900/50 text-sm font-medium rounded-xl text-white focus:outline-none transition-all duration-200 transform hover:scale-105">
                            Apply Filters
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Export Modal -->
    <div 
        x-show="showExportModal" 
        x-transition:enter="transition ease-out duration-300"
        x-transition:enter-start="opacity-0"
        x-transition:enter-end="opacity-100"
        x-transition:leave="transition ease-in duration-200"
        x-transition:leave-start="opacity-100"
        x-transition:leave-end="opacity-0"
        class="fixed inset-0 z-50 overflow-y-auto" 
        aria-labelledby="export-title" 
        role="dialog" 
        aria-modal="true">
        <div class="flex items-center justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
            <div 
                x-show="showExportModal" 
                x-transition:enter="transition ease-out duration-300"
                x-transition:enter-start="opacity-0"
                x-transition:enter-end="opacity-100"
                x-transition:leave="transition ease-in duration-200"
                x-transition:leave-start="opacity-100"
                x-transition:leave-end="opacity-0"
                class="fixed inset-0 bg-black/20 backdrop-blur-sm transition-opacity" 
                @click="showExportModal = false" 
                aria-hidden="true">
            </div>
            
            <span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
            
            <div 
                x-show="showExportModal" 
                x-transition:enter="transition ease-out duration-300"
                x-transition:enter-start="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
                x-transition:enter-end="opacity-100 translate-y-0 sm:scale-100"
                x-transition:leave="transition ease-in duration-200"
                x-transition:leave-start="opacity-100 translate-y-0 sm:scale-100"
                x-transition:leave-end="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
                class="inline-block align-bottom bg-white/95 dark:bg-gray-800/95 backdrop-blur-xl rounded-2xl px-4 pt-5 pb-4 text-left overflow-hidden shadow-2xl dark:shadow-gray-900/50 border border-white/20 dark:border-gray-700/50 transform transition-all sm:my-8 sm:align-middle w-full max-w-md mx-auto sm:p-6">
                
                <div class="absolute top-0 right-0 pt-4 pr-4">
                    <button
                        @click="showExportModal = false"
                        type="button"
                        class="bg-white/80 dark:bg-gray-800/80 backdrop-blur-sm rounded-xl text-gray-400 dark:text-gray-500 hover:text-gray-500 dark:hover:text-gray-400 focus:outline-none p-2 transition-colors">
                        <span class="sr-only">Close</span>
                        <i class="fa-solid fa-times text-sm"></i>
                    </button>
                </div>
                
                <div class="text-center mb-5">
                    <div class="mx-auto flex items-center justify-center h-16 w-16 rounded-2xl bg-primary-100 dark:bg-primary-900/50 mb-4">
                        <i class="fa-solid fa-download text-2xl text-primary-600 dark:text-primary-400"></i>
                    </div>
                    <h3 class="text-lg font-semibold text-gray-900 dark:text-white" id="export-title">Export Transactions</h3>
                    <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">Download or receive your transaction data</p>
                </div>
                
                <div class="mt-5 space-y-4">
                    <div>
                        <label for="export-type" class="block text-sm font-semibold text-gray-900 dark:text-white mb-2">File Format</label>
                        <select 
                            id="export-type"
                            x-model="exportType"
                            class="block w-full bg-white/80 dark:bg-gray-700/80 backdrop-blur-sm border border-gray-200/50 dark:border-gray-600/50 rounded-xl p-2.5 text-gray-900 dark:text-white focus:ring-2 focus:ring-primary-500/50 focus:border-primary-500 dark:focus:border-primary-400 transition-all duration-200">
                            <option value="">Select file type</option>
                            <option value="pdf">PDF</option>
                        </select>
                    </div>
                    
                    <div>
                        <label for="export-as" class="block text-sm font-semibold text-gray-900 dark:text-white mb-2">Export as</label>
                        <select 
                            id="export-as"
                            x-model="exportAs"
                            class="block w-full bg-white/80 dark:bg-gray-700/80 backdrop-blur-sm border border-gray-200/50 dark:border-gray-600/50 rounded-xl p-2.5 text-gray-900 dark:text-white focus:ring-2 focus:ring-primary-500/50 focus:border-primary-500 dark:focus:border-primary-400 transition-all duration-200">
                            <option value="">How do you want to receive this file?</option>
                            <option value="view">Preview statement</option>
                            <option value="download">Download file</option>
                            <option value="email">Send file to email</option>
                        </select>
                    </div>
                    
                    <div>
                        <label for="statement-type" class="block text-sm font-semibold text-gray-900 dark:text-white mb-2">Statement Style</label>
                        <div class="grid grid-cols-2 gap-3 mt-2">
                            <div 
                                @click="statementStyle = 'modern'" 
                                :class="{'ring-2 ring-primary-500 bg-primary-50 dark:bg-primary-900/30': statementStyle === 'modern'}"
                                class="border border-gray-200/50 dark:border-gray-600/50 rounded-xl p-3 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-all duration-200">
                                <div class="text-xs font-semibold text-gray-900 dark:text-white mb-2">Modern</div>
                                <div class="h-12 bg-gray-200 dark:bg-gray-600 rounded-lg flex items-center justify-center">
                                    <i class="fa-solid fa-table-columns text-gray-500 dark:text-gray-400"></i>
                                </div>
                            </div>
                            <div 
                                @click="statementStyle = 'classic'" 
                                :class="{'ring-2 ring-primary-500 bg-primary-50 dark:bg-primary-900/30': statementStyle === 'classic'}"
                                class="border border-gray-200/50 dark:border-gray-600/50 rounded-xl p-3 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-all duration-200">
                                <div class="text-xs font-semibold text-gray-900 dark:text-white mb-2">Classic</div>
                                <div class="h-12 bg-gray-200 dark:bg-gray-600 rounded-lg flex items-center justify-center">
                                    <i class="fa-solid fa-file-lines text-gray-500 dark:text-gray-400"></i>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="mt-6 flex justify-end">
                    <button 
                        @click="exportData()"
                        type="button"
                        id="export-button"
                        class="w-full inline-flex items-center justify-center px-4 py-2.5 bg-gradient-to-r from-primary-500 to-primary-600 hover:from-primary-600 hover:to-primary-700 shadow-lg shadow-primary-500/25 dark:shadow-primary-900/50 text-sm font-medium rounded-xl text-white focus:outline-none transition-all duration-200 transform hover:scale-105">
                        <i class="fa-solid fa-download text-sm mr-2"></i>
                        <span>Export Transactions</span>
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>
</div>

<script>
   document.addEventListener('alpine:init', function() {
    Alpine.data('transactionApp', function() {
        return {
            showFilterModal: false,
            showExportModal: false,
            showDebug: false,
            dateFrom: '',
            dateTo: '',
            status: '',
            orderBy: 'desc',
            perPage: '15',
            exportType: '',
            exportAs: '',
            search: '',
            statementStyle: 'modern',
            
            // This method is now handled by the form submission
            applyFilters() {
                document.getElementById('filterForm').submit();
            },
            
            exportData() {
                // Check if both exportType and exportAs are selected
                if(!this.exportType || !this.exportAs) {
                    this.errorMessage = 'Please select both export type and delivery method';
                    this.showExportError('Please select both export type and delivery method');
                    return;
                }
                
                console.log('Export options:', this.exportType, this.exportAs, this.statementStyle);
                
                // Handle view option - open in new tab
                if (this.exportAs === 'view') {
                    const url = new URL("transactions/export", window.location.origin);
                    
                    // Add parameters
                    url.searchParams.append('exportType', this.exportType);
                    url.searchParams.append('exportAs', this.exportAs);
                    url.searchParams.append('statementStyle', this.statementStyle);
                    
                    // Add filters if they exist
                    if (this.dateFrom) url.searchParams.append('startDate', this.dateFrom);
                    if (this.dateTo) url.searchParams.append('endDate', this.dateTo);
                    if (this.status) url.searchParams.append('status', this.status);
                    if (this.orderBy) url.searchParams.append('orderBy', this.orderBy);
                    
                    // Open in new tab with specific dimensions
                    const windowFeatures = 'width=800,height=1000,resizable=yes,scrollbars=yes,status=yes';
                    window.open(url.toString(), '_blank', windowFeatures);
                    
                    // Close modal
                    this.showExportModal = false;
                    return;
                }
                
                // Disable the export button while processing
                const exportButton = document.querySelector('#export-button');
                exportButton.disabled = true;
                exportButton.innerHTML = '<i data-lucide="loader" class="h-4 w-4 mr-2 animate-spin"></i><span>Processing...</span>';
                lucide.createIcons();
                
                try {
                    // Get the CSRF token
                    const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
                    
                    // Prepare form data
                    const formData = new FormData();
                    formData.append('statementStyle', this.statementStyle);
                    
                    // Handle based on export method
                    if (this.exportAs === 'download') {
                        // For direct downloads, create a form and submit it directly
                        const form = document.createElement('form');
                        form.method = 'POST';
                        form.action = 'export-transactions';
                        form.style.display = 'none';
                        
                        // Add CSRF token
                        const csrfInput = document.createElement('input');
                        csrfInput.type = 'hidden';
                        csrfInput.name = '_token';
                        csrfInput.value = csrfToken;
                        form.appendChild(csrfInput);
                        
                        // Add form fields
                        for (const pair of formData.entries()) {
                            const input = document.createElement('input');
                            input.type = 'hidden';
                            input.name = pair[0];
                            input.value = pair[1];
                            form.appendChild(input);
                        }
                        
                        // Add form to body and submit
                        document.body.appendChild(form);
                        
                        // Submit the form and handle potential errors
                        try {
                            form.submit();
                            console.log('Form submitted successfully');
                        } catch (err) {
                            console.error('Form submission error:', err);
                            this.showExportError();
                        }
                        
                        // Clean up
                        setTimeout(() => {
                            document.body.removeChild(form);
                            this.showExportModal = false;
                            exportButton.disabled = false;
                            exportButton.innerHTML = '<i data-lucide="download" class="h-4 w-4 mr-2"></i><span>Export Transactions</span>';
                            lucide.createIcons(); // Reinitialize icons
                        }, 1000);
                    } else {
                        // For email exports, use fetch API
                        console.log('Sending email export request to:', 'export-transactions');
                        
                        fetch('export-transactions', {
                            method: 'POST',
                            headers: {
                                'X-CSRF-TOKEN': csrfToken,
                                'Accept': 'application/json',
                            },
                            body: formData
                        })
                        .then(response => {
                            console.log('Response status:', response.status);
                            if (!response.ok) {
                                throw new Error('Network response was not ok: ' + response.status);
                            }
                            return response.json();
                        })
                        .then(data => {
                            console.log('Export response:', data);
                            if (data.success) {
                                // Show success message
                                const successAlert = document.querySelector('.success-alert');
                                if (successAlert) {
                                    const alertMessage = successAlert.querySelector('.alert-message');
                                    if (alertMessage) {
                                        alertMessage.textContent = 'Your transaction export has been sent to your email.';
                                        successAlert.classList.remove('hidden');
                                        setTimeout(() => {
                                            successAlert.classList.add('hidden');
                                        }, 5000);
                                    }
                                } else {
                                    alert('Your transaction export has been sent to your email.');
                                }
                                this.showExportModal = false;
                            } else {
                                this.showExportError(data.message || 'An error occurred while exporting your transactions.');
                            }
                        })
                        .catch(error => {
                            console.error('Export error:', error);
                            this.showExportError();
                        })
                        .finally(() => {
                            // Re-enable the export button
                            exportButton.disabled = false;
                            exportButton.innerHTML = '<i data-lucide="download" class="h-4 w-4 mr-2"></i><span>Export Transactions</span>';
                            lucide.createIcons(); // Reinitialize icons
                        });
                    }
                } catch (error) {
                    console.error('Export functionality error:', error);
                    this.showExportError();
                    
                    // Re-enable the export button
                    exportButton.disabled = false;
                    exportButton.innerHTML = '<i data-lucide="download" class="h-4 w-4 mr-2"></i><span>Export Transactions</span>';
                    lucide.createIcons(); // Reinitialize icons
                }
            },
            
            showExportError(message = 'An error occurred while processing your export request.') {
                // Implement your error display logic here
                console.error(message);
                alert(message);
            }
        };
    });
});
                    </script>
                                                    </div>
              <?php include 'footer.php'; ?>