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

// Fetch all loan transactions for this user
$sqlLoans = "SELECT * FROM transactions WHERE user_id = :user_id AND trans_type = 'Loan' ORDER BY trans_id DESC";
$stmtLoans = $conn->prepare($sqlLoans);
$stmtLoans->execute(['user_id' => $user_id]);
$loans = $stmtLoans->fetchAll(PDO::FETCH_ASSOC);

// Calculate stats
$totalApplications = count($loans);
$totalAmount = 0;
$pendingCount = 0;
$approvedCount = 0;

foreach ($loans as $loan) {
    $totalAmount += (float) $loan['amount'];
    $status = strtolower($loan['status'] ?? '');
    if ($status === 'pending') {
        $pendingCount++;
    } elseif ($status === 'processed' || $status === 'approved' || $status === 'yes') {
        $approvedCount++;
    }
}
?>
<!-- Main Content Area -->
<main class="pt-10 md:pt-14 pb-24 md:pb-8 min-h-screen lg:ml-80 bg-slate-50">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">

<div x-data="{
    showFilterModal: false,
    showExportModal: false,
    searchQuery: '',
    statusFilter: 'all',
    sortOrder: 'desc',
    perPage: 25,
    exportFormat: 'csv',
    exportMethod: 'download',
    isExporting: false,

    formatDuration(months) {
        if (!months) return 'N/A';
        months = parseInt(months);
        if (months < 12) {
            return months + (months === 1 ? ' Month' : ' Months');
        }
        const years = Math.floor(months / 12);
        const remainingMonths = months % 12;
        let result = years + (years === 1 ? ' Year' : ' Years');
        if (remainingMonths > 0) {
            result += ' ' + remainingMonths + (remainingMonths === 1 ? ' Month' : ' Months');
        }
        return result;
    },

    getStatusClasses(status) {
        const map = {
            'Processed': 'bg-green-50 text-green-700 border-green-200',
            'Pending':   'bg-amber-50 text-amber-700 border-amber-200',
            'yes':       'bg-primary-50 text-primary-700 border-primary-200',
            'No':        'bg-red-50 text-red-700 border-red-200'
        };
        return map[status] || 'bg-slate-100 text-slate-600 border-slate-200';
    },

    exportLoans() {
        if (!this.exportFormat || !this.exportMethod) {
            alert('Please select both file format and delivery method');
            return;
        }
        this.isExporting = true;
        this.$refs.exportForm.submit();
    }
}">

    <!-- Header Section -->
    <div class="bg-white/95 backdrop-blur-xl border-b border-slate-200 sticky top-0 z-40 -mx-4 sm:-mx-6 lg:-mx-8 px-4 sm:px-6 lg:px-8">
        <div class="max-w-7xl mx-auto py-6">
            <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
                <!-- Title & Breadcrumbs -->
                <div>
                    <div class="flex items-center space-x-3 mb-2">
                        <div class="w-10 h-10 rounded-xl bg-primary-50 flex items-center justify-center border border-primary-200">
                            <i data-lucide="receipt-text" class="w-5 h-5 text-primary-500"></i>
                        </div>
                        <h1 class="text-2xl md:text-3xl font-bold text-slate-900">Loan History</h1>
                    </div>
                    <nav class="flex items-center space-x-2 text-sm">
                        <a href="<?= $web_url ?>/user/dashboard.php" class="text-slate-500 hover:text-primary-600 transition-colors">Dashboard</a>
                        <i data-lucide="chevron-right" class="w-4 h-4 text-slate-300"></i>
                        <span class="text-slate-700 font-medium">Loan History</span>
                    </nav>
                </div>

                <!-- Action Buttons -->
                <div class="flex items-center space-x-3">
                    <button @click="showFilterModal = true"
                            class="px-5 py-2.5 rounded-xl flex items-center space-x-2 bg-transparent border-[1.5px] border-primary-300 text-primary-600 font-semibold hover:bg-primary-50 hover:border-primary-500 hover:text-primary-700 transition-all">
                        <i data-lucide="sliders-horizontal" class="w-4 h-4"></i>
                        <span>Filter</span>
                    </button>
                    <button @click="showExportModal = true"
                            class="px-5 py-2.5 rounded-xl flex items-center space-x-2 bg-gradient-to-br from-primary-500 to-primary-700 text-white font-semibold shadow-md hover:shadow-lg hover:-translate-y-0.5 transition-all">
                        <i data-lucide="download" class="w-4 h-4"></i>
                        <span>Export</span>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <div class="max-w-7xl mx-auto py-8">

        <!-- Balance Card with Quick Actions -->
        <div class="rounded-2xl p-6 md:p-8 mb-8 shadow-lg bg-gradient-to-br from-primary-500 to-primary-700 text-white">
            <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-6">
                <div>
                    <p class="text-white/70 text-sm font-medium mb-1">Available Loan Balance</p>
                    <h2 class="text-4xl md:text-5xl font-bold">
                        <?= $currency ?><?= number_format($loan_balance, 2, '.', ',') ?>
                    </h2>
                </div>

                <div class="grid grid-cols-3 gap-3 md:gap-4">
                    <a href="<?= $web_url ?>/user/loan-request.php"
                       class="rounded-xl p-3 md:p-4 text-center bg-white/10 backdrop-blur-md border border-white/20 hover:bg-white/20 hover:-translate-y-0.5 transition-all">
                        <div class="w-10 h-10 mx-auto mb-2 rounded-lg bg-white/20 flex items-center justify-center">
                            <i data-lucide="arrow-down" class="w-5 h-5 text-white"></i>
                        </div>
                        <span class="text-xs md:text-sm font-semibold text-white">New Loan</span>
                    </a>
                    <a href="<?= $web_url ?>/user/deposits.php"
                       class="rounded-xl p-3 md:p-4 text-center bg-white/10 backdrop-blur-md border border-white/20 hover:bg-white/20 hover:-translate-y-0.5 transition-all">
                        <div class="w-10 h-10 mx-auto mb-2 rounded-lg bg-white/20 flex items-center justify-center">
                            <i data-lucide="wallet" class="w-5 h-5 text-white"></i>
                        </div>
                        <span class="text-xs md:text-sm font-semibold text-white">Pay Loan</span>
                    </a>
                    <a href="<?= $web_url ?>/user/support.php"
                       class="rounded-xl p-3 md:p-4 text-center bg-white/10 backdrop-blur-md border border-white/20 hover:bg-white/20 hover:-translate-y-0.5 transition-all">
                        <div class="w-10 h-10 mx-auto mb-2 rounded-lg bg-white/20 flex items-center justify-center">
                            <i data-lucide="message-circle" class="w-5 h-5 text-white"></i>
                        </div>
                        <span class="text-xs md:text-sm font-semibold text-white">Support</span>
                    </a>
                </div>
            </div>
        </div>

        <!-- Stats Cards -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">

            <div class="bg-white border border-slate-200 rounded-2xl p-6 shadow-sm hover:border-primary-300 hover:-translate-y-0.5 hover:shadow-lg transition-all">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-slate-500 text-sm font-medium mb-1">Total Applications</p>
                        <h3 class="text-3xl font-bold text-slate-900"><?= $totalApplications ?></h3>
                    </div>
                    <div class="w-14 h-14 rounded-2xl bg-primary-50 flex items-center justify-center border border-primary-200">
                        <i data-lucide="file-text" class="w-7 h-7 text-primary-500"></i>
                    </div>
                </div>
            </div>

            <div class="bg-white border border-slate-200 rounded-2xl p-6 shadow-sm hover:border-primary-300 hover:-translate-y-0.5 hover:shadow-lg transition-all">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-slate-500 text-sm font-medium mb-1">Total Amount</p>
                        <h3 class="text-3xl font-bold text-slate-900">
                            <?= $currency ?><?= number_format($totalAmount, 2, '.', ',') ?>
                        </h3>
                    </div>
                   
                </div>
            </div>

            <div class="bg-white border border-slate-200 rounded-2xl p-6 shadow-sm hover:border-primary-300 hover:-translate-y-0.5 hover:shadow-lg transition-all">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-slate-500 text-sm font-medium mb-1">Status Overview</p>
                        <div class="flex items-center space-x-3 mt-2">
                            <span class="text-sm font-semibold text-amber-700"><?= $pendingCount ?> Pending</span>
                            <span class="text-slate-300">•</span>
                            <span class="text-sm font-semibold text-green-700"><?= $approvedCount ?> Approved</span>
                        </div>
                    </div>
                    <div class="w-14 h-14 rounded-2xl bg-amber-50 flex items-center justify-center border border-amber-200">
                        <i data-lucide="pie-chart" class="w-7 h-7 text-amber-600"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Search Bar -->
        <div class="mb-6">
            <div class="relative">
                <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                    <i data-lucide="search" class="w-5 h-5 text-slate-400"></i>
                </div>
                <input
                    type="text"
                    x-model="searchQuery"
                    placeholder="Search by loan purpose, amount, or type..."
                    class="w-full pl-12 pr-4 py-3.5 rounded-xl text-sm bg-white border border-slate-200 text-slate-900 placeholder-slate-400 focus:bg-white focus:border-primary-500 focus:ring-2 focus:ring-primary-100 focus:outline-none transition-all">
            </div>
        </div>

        <!-- Loans Table -->
        <div class="bg-white/95 backdrop-blur-xl border border-slate-200 rounded-2xl overflow-hidden">
            <div class="overflow-x-auto">
                <table class="w-full">
                    <thead>
                        <tr class="border-b border-slate-200">
                            <th class="px-6 py-4 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Type</th>
                            <th class="px-6 py-4 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Amount</th>
                            <th class="px-6 py-4 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Purpose</th>
                            <th class="px-6 py-4 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Duration</th>
                            <th class="px-6 py-4 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Status</th>
                            <th class="px-6 py-4 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Date Applied</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100">
                        <?php if (empty($loans)): ?>
                            <tr>
                                <td colspan="6" class="px-6 py-16 text-center">
                                    <div class="flex flex-col items-center">
                                        <div class="w-16 h-16 rounded-2xl bg-primary-50 flex items-center justify-center mb-4 border border-primary-200">
                                            <i data-lucide="inbox" class="w-8 h-8 text-primary-500"></i>
                                        </div>
                                        <h4 class="text-lg font-bold text-slate-900 mb-1">No loans yet</h4>
                                        <p class="text-sm text-slate-500 mb-4">You haven't applied for any loans.</p>
                                        <a href="<?= $web_url ?>/user/loan-request.php"
                                           class="px-5 py-2.5 rounded-xl text-sm inline-flex items-center space-x-2 bg-gradient-to-br from-primary-500 to-primary-700 text-white font-semibold shadow-md hover:shadow-lg hover:-translate-y-0.5 transition-all">
                                            <i data-lucide="plus" class="w-4 h-4"></i>
                                            <span>Apply for a Loan</span>
                                        </a>
                                    </div>
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($loans as $loan):
                                $amount       = (float) $loan['amount'];
                                $purpose      = !empty($loan['purpose']) ? $loan['purpose'] : (!empty($loan['description']) ? $loan['description'] : 'N/A');
                                $duration     = $loan['duration'] ?? ($loan['tenure'] ?? 0);
                                $statusRaw    = $loan['status'] ?? '';
                                $createdAt    = $loan['created_at'] ?? '';
                                $dateApplied  = $createdAt ? date('M d, Y', strtotime($createdAt)) : 'N/A';
                                $timeApplied  = $createdAt ? date('h:i A', strtotime($createdAt)) : '';
                                $transId      = $loan['trans_id'];
                            ?>
                                <tr class="cursor-pointer transition-all duration-200 hover:bg-primary-50/40 hover:translate-x-1"
                                    onclick="window.location.href='<?= $web_url ?>/user/transaction-info.php?id=<?= $transId ?>'">
                                    <td class="px-6 py-4">
                                        <div class="w-11 h-11 flex items-center justify-center rounded-xl bg-gradient-to-br from-primary-100 to-primary-50 border border-primary-200">
                                            <i data-lucide="landmark" class="w-5 h-5 text-primary-500"></i>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4">
                                        <span class="text-slate-900 font-semibold text-base">
                                            <?= $currency ?><?= number_format($amount, 2, '.', ',') ?>
                                        </span>
                                    </td>
                                    <td class="px-6 py-4">
                                        <div class="max-w-xs">
                                            <p class="text-slate-700 text-sm truncate" title="<?= htmlspecialchars($purpose) ?>">
                                                <?= htmlspecialchars($purpose) ?>
                                            </p>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4">
                                        <span class="inline-block px-3 py-1 rounded-lg text-[13px] font-semibold bg-amber-50 text-amber-800 border border-amber-200"
                                              x-text="formatDuration(<?= (int) $duration ?>)"></span>
                                    </td>
                                    <td class="px-6 py-4">
                                        <span
                                            class="inline-block px-4 py-1.5 rounded-full text-xs font-semibold uppercase tracking-wide border"
                                            :class="getStatusClasses('<?= htmlspecialchars($statusRaw) ?>')">
                                            <?= htmlspecialchars($statusRaw) ?>
                                        </span>
                                    </td>
                                    <td class="px-6 py-4">
                                        <div>
                                            <p class="text-slate-700 text-sm font-medium"><?= $dateApplied ?></p>
                                            <p class="text-slate-400 text-xs"><?= $timeApplied ?></p>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

    </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"
        style="display: none;">

        <div class="flex items-center justify-center min-h-screen px-4">
            <div @click="showFilterModal = false" class="fixed inset-0 bg-slate-900/50 backdrop-blur-sm"></div>

            <div
                x-show="showFilterModal"
                x-transition:enter="transition ease-out duration-300"
                x-transition:enter-start="opacity-0 transform scale-95"
                x-transition:enter-end="opacity-100 transform scale-100"
                x-transition:leave="transition ease-in duration-200"
                x-transition:leave-start="opacity-100 transform scale-100"
                x-transition:leave-end="opacity-0 transform scale-95"
                class="relative bg-white border border-slate-200 rounded-2xl p-6 w-full max-w-md z-10 shadow-2xl">

                <div class="flex items-center justify-between mb-6">
                    <h3 class="text-xl font-bold text-slate-900">Filter Loans</h3>
                    <button @click="showFilterModal = false" class="w-8 h-8 rounded-lg hover:bg-slate-100 flex items-center justify-center transition-colors">
                        <i data-lucide="x" class="w-5 h-5 text-slate-500"></i>
                    </button>
                </div>

                <form method="GET" action="">
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-semibold text-slate-700 mb-2">Date Range</label>
                            <input type="text" name="date_range" placeholder="Select date range"
                                   class="w-full px-4 py-2.5 rounded-xl text-sm bg-white border border-slate-200 focus:border-primary-500 focus:ring-2 focus:ring-primary-100 focus:outline-none transition-all">
                        </div>

                        <div>
                            <label class="block text-sm font-semibold text-slate-700 mb-2">Status</label>
                            <select name="status" x-model="statusFilter"
                                    class="w-full px-4 py-2.5 rounded-xl text-sm bg-white border border-slate-200 focus:border-primary-500 focus:ring-2 focus:ring-primary-100 focus:outline-none transition-all">
                                <option value="all">All statuses</option>
                                <option value="Processed">Processed</option>
                                <option value="Pending">Pending</option>
                                <option value="yes">Active</option>
                                <option value="No">Rejected</option>
                            </select>
                        </div>

                        <div>
                            <label class="block text-sm font-semibold text-slate-700 mb-2">Sort by</label>
                            <select name="sort" x-model="sortOrder"
                                    class="w-full px-4 py-2.5 rounded-xl text-sm bg-white border border-slate-200 focus:border-primary-500 focus:ring-2 focus:ring-primary-100 focus:outline-none transition-all">
                                <option value="desc">Newest first</option>
                                <option value="asc">Oldest first</option>
                            </select>
                        </div>

                        <div>
                            <label class="block text-sm font-semibold text-slate-700 mb-2">Items per page</label>
                            <select name="per_page" x-model="perPage"
                                    class="w-full px-4 py-2.5 rounded-xl text-sm bg-white border border-slate-200 focus:border-primary-500 focus:ring-2 focus:ring-primary-100 focus:outline-none transition-all">
                                <option value="10">10</option>
                                <option value="25">25</option>
                                <option value="50">50</option>
                                <option value="100">100</option>
                            </select>
                        </div>
                    </div>

                    <div class="flex space-x-3 mt-6">
                        <button type="button" @click="showFilterModal = false"
                                class="flex-1 px-4 py-2.5 rounded-xl text-sm bg-transparent border-[1.5px] border-primary-300 text-primary-600 font-semibold hover:bg-primary-50 hover:border-primary-500 transition-all">
                            Cancel
                        </button>
                        <button type="submit"
                                class="flex-1 px-4 py-2.5 rounded-xl text-sm bg-gradient-to-br from-primary-500 to-primary-700 text-white font-semibold shadow-md hover:shadow-lg hover:-translate-y-0.5 transition-all">
                            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"
        style="display: none;">

        <div class="flex items-center justify-center min-h-screen px-4">
            <div @click="showExportModal = false" class="fixed inset-0 bg-slate-900/50 backdrop-blur-sm"></div>

            <div
                x-show="showExportModal"
                x-transition:enter="transition ease-out duration-300"
                x-transition:enter-start="opacity-0 transform scale-95"
                x-transition:enter-end="opacity-100 transform scale-100"
                x-transition:leave="transition ease-in duration-200"
                x-transition:leave-start="opacity-100 transform scale-100"
                x-transition:leave-end="opacity-0 transform scale-95"
                class="relative bg-white border border-slate-200 rounded-2xl p-6 w-full max-w-md z-10 shadow-2xl">

                <div class="flex items-center justify-between mb-6">
                    <h3 class="text-xl font-bold text-slate-900">Export Loans</h3>
                    <button @click="showExportModal = false" class="w-8 h-8 rounded-lg hover:bg-slate-100 flex items-center justify-center transition-colors">
                        <i data-lucide="x" class="w-5 h-5 text-slate-500"></i>
                    </button>
                </div>

                <form action="<?= $web_url ?>/user/export-loans.php" method="POST" x-ref="exportForm">
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-semibold text-slate-700 mb-2">File Format</label>
                            <select name="format" x-model="exportFormat" required
                                    class="w-full px-4 py-2.5 rounded-xl text-sm bg-white border border-slate-200 focus:border-primary-500 focus:ring-2 focus:ring-primary-100 focus:outline-none transition-all">
                                <option value="">Select file type</option>
                                <option value="csv">CSV</option>
                                <option value="excel">Excel</option>
                            </select>
                        </div>

                        <div>
                            <label class="block text-sm font-semibold text-slate-700 mb-2">Delivery Method</label>
                            <select name="method" x-model="exportMethod" required
                                    class="w-full px-4 py-2.5 rounded-xl text-sm bg-white border border-slate-200 focus:border-primary-500 focus:ring-2 focus:ring-primary-100 focus:outline-none transition-all">
                                <option value="">How do you want to receive this file?</option>
                                <option value="download">Download file</option>
                                <option value="email">Send file to email</option>
                            </select>
                        </div>
                    </div>

                    <div class="mt-6">
                        <button
                            type="submit"
                            :disabled="isExporting"
                            class="w-full px-4 py-3 rounded-xl text-sm flex items-center justify-center space-x-2 bg-gradient-to-br from-primary-500 to-primary-700 text-white font-semibold shadow-md hover:shadow-lg hover:-translate-y-0.5 transition-all disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:translate-y-0">
                            <template x-if="!isExporting">
                                <i data-lucide="download" class="w-4 h-4"></i>
                            </template>
                            <template x-if="isExporting">
                                <svg class="animate-spin h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                </svg>
                            </template>
                            <span x-text="isExporting ? 'Exporting...' : 'Export Loans'"></span>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

</div>

<script>
    lucide.createIcons();
    document.addEventListener('alpine:init', () => {
        Alpine.effect(() => {
            setTimeout(() => lucide.createIcons(), 0);
        });
    });
</script>

    </div>
</main>

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