<?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
$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');
$balance = (float)($currentUser['balance'] ?? 0.00);
$fullName = htmlspecialchars($currentUser['full_name'] ?? $currentUser['username'] ?? 'User');

// ==========================================
// FETCH ADMIN LOAN SETTINGS
// ==========================================
$settingsQuery = mysqli_query($conn, "SELECT `setting_key`, `setting_value` FROM `admin_settings` WHERE `setting_key` IN ('min_loan_amount', 'max_loan_amount', 'interest_rate', 'max_duration_months', 'late_fee_percent')");
$loanSettings = [];
if ($settingsQuery) {
    while ($sRow = mysqli_fetch_assoc($settingsQuery)) {
        $loanSettings[$sRow['setting_key']] = $sRow['setting_value'];
    }
}
$interestRate = (float)($loanSettings['interest_rate'] ?? 12.5);

// ==========================================
// HANDLE AJAX REQUESTS
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    ini_set('display_errors', 0);
    header('Content-Type: application/json');
    ob_start();

    try {
        $action = $_POST['action'] ?? '';

        if ($action === 'get_loan_details') {
            $loanId = intval($_POST['loan_id'] ?? 0);
            if ($loanId <= 0) throw new Exception('Invalid loan ID.');

            // Fetch loan details using bind_result instead of get_result
            $loanStmt = mysqli_prepare($conn, "SELECT `id`, `user_id`, `amount`, `duration_months`, `interest_rate`, `monthly_payment`, `total_repayment`, `total_interest`, `purpose`, `status`, `applied_at`, `approved_at`, `remaining_balance` FROM `loan_applications` WHERE `id` = ? AND `user_id` = ?");
            mysqli_stmt_bind_param($loanStmt, "ii", $loanId, $userId);
            mysqli_stmt_execute($loanStmt);
            mysqli_stmt_bind_result($loanStmt, $lid, $luid, $lamount, $lduration, $lrate, $lmonthly, $ltotal, $linterest, $lpurpose, $lstatus, $lapplied, $lapproved, $lremaining);
            $found = mysqli_stmt_fetch($loanStmt);
            mysqli_stmt_close($loanStmt);

            if (!$found) throw new Exception('Loan not found.');

            $loan = [
                'id' => $lid,
                'user_id' => $luid,
                'amount' => $lamount,
                'duration_months' => $lduration,
                'interest_rate' => $lrate,
                'monthly_payment' => $lmonthly,
                'total_repayment' => $ltotal,
                'total_interest' => $linterest,
                'purpose' => $lpurpose,
                'status' => $lstatus,
                'applied_at' => $lapplied,
                'approved_at' => $lapproved,
                'remaining_balance' => $lremaining
            ];

            // Fetch repayment history using bind_result
            $repayStmt = mysqli_prepare($conn, "SELECT `id`, `amount`, `paid_at` FROM `loan_repayments` WHERE `loan_id` = ? ORDER BY `paid_at` DESC");
            mysqli_stmt_bind_param($repayStmt, "i", $loanId);
            mysqli_stmt_execute($repayStmt);
            mysqli_stmt_bind_result($repayStmt, $rid, $ramount, $rpaid);
            $repayments = [];
            while (mysqli_stmt_fetch($repayStmt)) {
                $repayments[] = [
                    'id' => $rid,
                    'amount' => (float)$ramount,
                    'paid_at' => $rpaid
                ];
            }
            mysqli_stmt_close($repayStmt);

            // Calculate amortization schedule
            $schedule = [];
            $monthlyInterest = ($loan['interest_rate'] / 100) / 12;
            $monthlyPayment = (float)$loan['monthly_payment'];
            $remainingBalance = (float)$loan['amount'];
            $approvedDate = strtotime($loan['approved_at'] ?? $loan['applied_at']);
            $duration = (int)$loan['duration_months'];

            $repaidResult = mysqli_query($conn, "SELECT COALESCE(SUM(`amount`), 0) as total FROM `loan_repayments` WHERE `loan_id` = $loanId");
            $totalRepaid = (float)mysqli_fetch_assoc($repaidResult)['total'];

            for ($i = 1; $i <= $duration; $i++) {
                $interestPayment = $remainingBalance * $monthlyInterest;
                $principalPayment = $monthlyPayment - $interestPayment;
                $remainingBalance -= $principalPayment;
                if ($remainingBalance < 0) $remainingBalance = 0;

                $dueDate = date('Y-m-d', strtotime("+$i months", $approvedDate));
                $cumulativeDue = $monthlyPayment * $i;
                $paidToDate = min($totalRepaid, $cumulativeDue);
                $status = $paidToDate >= $cumulativeDue ? 'paid' : ($remainingBalance > 0 ? 'pending' : 'upcoming');

                $schedule[] = [
                    'payment_no' => $i,
                    'due_date' => $dueDate,
                    'payment_amount' => round($monthlyPayment, 2),
                    'principal' => round($principalPayment, 2),
                    'interest' => round($interestPayment, 2),
                    'remaining_balance' => round($remainingBalance, 2),
                    'status' => $status
                ];
            }

            ob_end_clean();
            echo json_encode([
                'success' => true,
                'loan' => [
                    'id' => 'LN-' . str_pad($loan['id'], 6, '0', STR_PAD_LEFT),
                    'raw_id' => $loan['id'],
                    'amount' => (float)$loan['amount'],
                    'duration' => (int)$loan['duration_months'],
                    'interest_rate' => (float)$loan['interest_rate'],
                    'monthly_payment' => (float)$loan['monthly_payment'],
                    'total_repayment' => (float)$loan['total_repayment'],
                    'total_interest' => (float)$loan['total_interest'],
                    'purpose' => $loan['purpose'],
                    'status' => $loan['status'],
                    'applied_at' => $loan['applied_at'],
                    'approved_at' => $loan['approved_at'],
                    'remaining_balance' => (float)($loan['remaining_balance'] ?? $loan['total_repayment'])
                ],
                'repayments' => $repayments,
                'schedule' => $schedule,
                'total_repaid' => $totalRepaid
            ]);

        } elseif ($action === 'get_repayment_history') {
            $page = max(1, intval($_POST['page'] ?? 1));
            $perPage = 10;
            $offset = ($page - 1) * $perPage;

            $countResult = mysqli_query($conn, "SELECT COUNT(*) as total FROM `loan_repayments` lr JOIN `loan_applications` la ON lr.loan_id = la.id WHERE la.user_id = $userId");
            $totalRows = mysqli_fetch_assoc($countResult)['total'];
            $totalPages = ceil($totalRows / $perPage);

            // Use bind_result for history query
            $historyStmt = mysqli_prepare($conn, "
                SELECT lr.`id`, lr.`loan_id`, lr.`amount`, lr.`paid_at`, la.`purpose`, la.`duration_months` 
                FROM `loan_repayments` lr 
                JOIN `loan_applications` la ON lr.loan_id = la.id 
                WHERE la.user_id = ? 
                ORDER BY lr.paid_at DESC 
                LIMIT ? OFFSET ?
            ");
            mysqli_stmt_bind_param($historyStmt, "iii", $userId, $perPage, $offset);
            mysqli_stmt_execute($historyStmt);
            mysqli_stmt_bind_result($historyStmt, $hid, $hloanid, $hamount, $hpaid, $hpurpose, $hduration);
            
            $history = [];
            while (mysqli_stmt_fetch($historyStmt)) {
                $history[] = [
                    'id' => 'RP-' . str_pad($hid, 6, '0', STR_PAD_LEFT),
                    'loan_id' => 'LN-' . str_pad($hloanid, 6, '0', STR_PAD_LEFT),
                    'raw_loan_id' => $hloanid,
                    'amount' => (float)$hamount,
                    'purpose' => $hpurpose,
                    'paid_at' => $hpaid
                ];
            }
            mysqli_stmt_close($historyStmt);

            ob_end_clean();
            echo json_encode([
                'success' => true,
                'history' => $history,
                'pagination' => [
                    'current_page' => $page,
                    'total_pages' => $totalPages,
                    'total_records' => $totalRows,
                    'per_page' => $perPage
                ]
            ]);

        } else {
            throw new Exception('Invalid action.');
        }

    } catch (Throwable $e) {
        ob_end_clean();
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

// ==========================================
// FETCH USER'S LOANS FOR INITIAL DISPLAY
// ==========================================
$loans = [];
$loansQuery = mysqli_query($conn, "SELECT * FROM `loan_applications` WHERE `user_id` = $userId ORDER BY `applied_at` DESC");
if ($loansQuery) {
    while ($row = mysqli_fetch_assoc($loansQuery)) {
        $loanId = (int)$row['id'];
        
        $repaidResult = mysqli_query($conn, "SELECT COALESCE(SUM(`amount`), 0) as total_repaid FROM `loan_repayments` WHERE `loan_id` = $loanId");
        $repaidRow = mysqli_fetch_assoc($repaidResult);
        $totalRepaid = (float)$repaidRow['total_repaid'];
        
        $remaining = (float)($row['remaining_balance'] ?? $row['total_repayment']);
        $progress = $row['total_repayment'] > 0 ? (($row['total_repayment'] - $remaining) / $row['total_repayment']) * 100 : 0;

        $countResult = mysqli_query($conn, "SELECT COUNT(*) as count FROM `loan_repayments` WHERE `loan_id` = $loanId");
        $paymentCount = mysqli_fetch_assoc($countResult)['count'];

        $loans[] = [
            'id' => 'LN-' . str_pad($loanId, 6, '0', STR_PAD_LEFT),
            'raw_id' => $loanId,
            'amount' => (float)$row['amount'],
            'duration' => (int)$row['duration_months'],
            'interest_rate' => (float)$row['interest_rate'],
            'monthly_payment' => (float)$row['monthly_payment'],
            'total_repayment' => (float)$row['total_repayment'],
            'total_interest' => (float)$row['total_interest'],
            'remaining_balance' => $remaining,
            'total_repaid' => $totalRepaid,
            'progress' => round($progress, 1),
            'purpose' => $row['purpose'],
            'status' => $row['status'],
            'applied_at' => $row['applied_at'],
            'approved_at' => $row['approved_at'],
            'payment_count' => (int)$paymentCount
        ];
    }
}

// Calculate summary statistics
$totalBorrowed = array_sum(array_column($loans, 'amount'));
$totalRepaidAll = array_sum(array_column($loans, 'total_repaid'));
$totalInterestPaid = array_sum(array_column($loans, 'total_interest'));
$activeLoans = count(array_filter($loans, fn($l) => in_array($l['status'], ['approved', 'late'])));
$completedLoans = count(array_filter($loans, fn($l) => $l['status'] === 'completed'));

// Credit score calculation
function calculateCreditScore($conn, $userId) {
    $score = 650;
    $completedQuery = mysqli_query($conn, "SELECT COUNT(*) as completed FROM `loan_applications` WHERE `user_id` = $userId AND `status` = 'completed'");
    $completed = mysqli_fetch_assoc($completedQuery)['completed'] ?? 0;
    $score += $completed * 25;
    
    $lateQuery = mysqli_query($conn, "SELECT COUNT(*) as late FROM `loan_applications` WHERE `user_id` = $userId AND `status` = 'late'");
    $late = mysqli_fetch_assoc($lateQuery)['late'] ?? 0;
    $score -= $late * 50;
    
    return min(max($score, 300), 850);
}
$creditScore = calculateCreditScore($conn, $userId);
?>

<?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);
    }

    .loan-row {
        transition: all 0.2s ease;
    }
    .loan-row:hover {
        background: rgba(var(--primary-rgb), 0.03);
    }

    .status-pending { background: rgba(245, 158, 11, 0.1); color: #f59e0b; }
    .status-approved { background: rgba(16, 185, 129, 0.1); color: #10b981; }
    .status-rejected { background: rgba(244, 63, 94, 0.1); color: #f43f5e; }
    .status-completed { background: rgba(59, 130, 246, 0.1); color: #3b82f6; }
    .status-late { background: rgba(239, 68, 68, 0.1); color: #ef4444; }

    .progress-bar {
        height: 6px;
        border-radius: 3px;
        background: #e2e8f0;
        overflow: hidden;
    }
    .dark .progress-bar { background: #1e293b; }
    .progress-fill {
        height: 100%;
        border-radius: 3px;
        background: var(--primary-theme);
        transition: width 0.6s ease;
    }

    .timeline-line {
        position: absolute;
        left: 15px;
        top: 30px;
        bottom: 0;
        width: 2px;
        background: #e2e8f0;
    }
    .dark .timeline-line { background: #1e293b; }

    .modal-overlay {
        background: rgba(0, 0, 0, 0.5);
        backdrop-filter: blur(4px);
    }

    .tab-btn {
        transition: all 0.3s ease;
        position: relative;
    }
    .tab-btn.active::after {
        content: '';
        position: absolute;
        bottom: -1px;
        left: 0;
        right: 0;
        height: 2px;
        background: var(--primary-theme);
    }

    .amortization-row:nth-child(even) {
        background: rgba(0, 0, 0, 0.02);
    }
    .dark .amortization-row:nth-child(even) {
        background: rgba(255, 255, 255, 0.02);
    }

    .payment-status-paid { color: #10b981; }
    .payment-status-pending { color: #f59e0b; }
    .payment-status-upcoming { color: #94a3b8; }

    .stat-card {
        transition: transform 0.3s ease;
    }
    .stat-card:hover {
        transform: translateY(-2px);
    }
</style>

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

<div class="flex min-h-screen bg-slate-50 dark:bg-[#070b14] transition-colors duration-300"
     x-data='{
        balance: <?= $balance ?>,
        loans: <?= json_encode($loans, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>,
        creditScore: <?= $creditScore ?>,
        totalBorrowed: <?= $totalBorrowed ?>,
        totalRepaidAll: <?= $totalRepaidAll ?>,
        totalInterestPaid: <?= $totalInterestPaid ?>,
        activeLoans: <?= $activeLoans ?>,
        completedLoans: <?= $completedLoans ?>,
        
        activeTab: "loans",
        selectedLoan: null,
        loanDetails: null,
        repayments: [],
        schedule: [],
        repaymentHistory: [],
        historyPage: 1,
        totalHistoryPages: 1,
        isLoading: false,
        showDetailModal: false,
        
        formatCurrency(num) {
            return "$" + num.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        },
        
        formatDate(dateStr) {
            if (!dateStr) return "N/A";
            return new Date(dateStr).toLocaleDateString("en-US", { year: "numeric", month: "short", day: "numeric" });
        },
        
        formatDateTime(dateStr) {
            if (!dateStr) return "N/A";
            return new Date(dateStr).toLocaleString("en-US", { year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" });
        },
        
        getStatusColor(status) {
            const colors = {
                pending: "text-amber-500",
                approved: "text-emerald-500",
                rejected: "text-rose-500",
                completed: "text-blue-500",
                late: "text-red-500"
            };
            return colors[status] || "text-slate-500";
        },
        
        getCreditRating() {
            if (this.creditScore >= 750) return "Excellent";
            if (this.creditScore >= 670) return "Good";
            if (this.creditScore >= 580) return "Fair";
            return "Poor";
        },
        
        getCreditColor() {
            if (this.creditScore >= 750) return "text-emerald-500";
            if (this.creditScore >= 670) return "text-theme";
            if (this.creditScore >= 580) return "text-amber-500";
            return "text-rose-500";
        },
        
        async loadLoanDetails(loan) {
            this.isLoading = true;
            this.selectedLoan = loan;
            
            const params = new URLSearchParams();
            params.append("action", "get_loan_details");
            params.append("loan_id", loan.raw_id);
            
            try {
                const response = await fetch("LoanHistory.php", {
                    method: "POST",
                    headers: { "Content-Type": "application/x-www-form-urlencoded" },
                    body: params.toString()
                });
                const data = await response.json();
                
                if (data.success) {
                    this.loanDetails = data.loan;
                    this.repayments = data.repayments;
                    this.schedule = data.schedule;
                    this.showDetailModal = true;
                } else {
                    Swal.fire({ icon: "error", title: "Error", text: data.message, confirmButtonColor: "var(--primary-theme)" });
                }
            } catch (error) {
                Swal.fire({ icon: "error", title: "Error", text: "Failed to load loan details.", confirmButtonColor: "var(--primary-theme)" });
            } finally {
                this.isLoading = false;
            }
        },
        
        async loadRepaymentHistory(page = 1) {
            this.isLoading = true;
            this.historyPage = page;
            
            const params = new URLSearchParams();
            params.append("action", "get_repayment_history");
            params.append("page", page);
            
            try {
                const response = await fetch("LoanHistory.php", {
                    method: "POST",
                    headers: { "Content-Type": "application/x-www-form-urlencoded" },
                    body: params.toString()
                });
                const data = await response.json();
                
                if (data.success) {
                    this.repaymentHistory = data.history;
                    this.totalHistoryPages = data.pagination.total_pages;
                }
            } catch (error) {
                console.error("Failed to load history");
            } finally {
                this.isLoading = false;
            }
        },
        
        getPaymentStatusClass(status) {
            return "payment-status-" + status;
        }
     }'
     x-init="loadRepaymentHistory(1)">
  
  <?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-2xl mx-auto px-4 sm:px-6 py-8">

      <!-- Header -->
      <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">
            Loan <span class="text-theme">History</span>
          </h1>
          <p class="text-sm text-slate-500 dark:text-slate-400 mt-1">View complete loan records, repayment history, and amortization schedules.</p>
        </div>
        <div class="flex items-center gap-4">
            <div class="glass-card rounded-2xl px-5 py-3 flex items-center gap-3">
                <div class="w-2 h-2 rounded-full bg-emerald-500 animate-pulse"></div>
                <span class="text-xs font-black uppercase tracking-widest text-slate-600 dark:text-slate-300">Balance</span>
                <span class="text-lg font-black text-slate-900 dark:text-white" x-text="formatCurrency(balance)"></span>
            </div>
            <a href="Loan_Application.php" class="px-6 py-3 rounded-2xl bg-theme text-white font-black uppercase tracking-widest text-xs shadow-xl shadow-theme/30 hover:brightness-110 transition-all flex items-center gap-2">
                <i data-lucide="plus" class="w-4 h-4"></i> New Loan
            </a>
        </div>
      </div>

      <!-- Summary Stats -->
      <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
        <div class="stat-card glass-card rounded-[1.5rem] p-5 border border-slate-200 dark:border-slate-800">
            <div class="flex items-center justify-between mb-2">
                <span class="text-[9px] font-black uppercase tracking-widest text-slate-400">Total Borrowed</span>
                <div class="w-8 h-8 rounded-xl bg-theme/10 flex items-center justify-center text-theme">
                    <i data-lucide="banknote" class="w-4 h-4"></i>
                </div>
            </div>
            <p class="text-xl font-black text-slate-900 dark:text-white" x-text="formatCurrency(totalBorrowed)"></p>
            <p class="text-[10px] text-slate-400 mt-1" x-text="loans.length + ' total loans'"></p>
        </div>

        <div class="stat-card glass-card rounded-[1.5rem] p-5 border border-slate-200 dark:border-slate-800">
            <div class="flex items-center justify-between mb-2">
                <span class="text-[9px] font-black uppercase tracking-widest text-slate-400">Total Repaid</span>
                <div class="w-8 h-8 rounded-xl bg-emerald-500/10 flex items-center justify-center text-emerald-500">
                    <i data-lucide="check-circle" class="w-4 h-4"></i>
                </div>
            </div>
            <p class="text-xl font-black text-emerald-500" x-text="formatCurrency(totalRepaidAll)"></p>
            <p class="text-[10px] text-slate-400 mt-1" x-text="formatCurrency(totalInterestPaid) + ' interest'"></p>
        </div>

        <div class="stat-card glass-card rounded-[1.5rem] p-5 border border-slate-200 dark:border-slate-800">
            <div class="flex items-center justify-between mb-2">
                <span class="text-[9px] font-black uppercase tracking-widest text-slate-400">Active Loans</span>
                <div class="w-8 h-8 rounded-xl bg-amber-500/10 flex items-center justify-center text-amber-500">
                    <i data-lucide="activity" class="w-4 h-4"></i>
                </div>
            </div>
            <p class="text-xl font-black text-slate-900 dark:text-white" x-text="activeLoans"></p>
            <p class="text-[10px] text-slate-400 mt-1">Currently running</p>
        </div>

        <div class="stat-card glass-card rounded-[1.5rem] p-5 border border-slate-200 dark:border-slate-800">
            <div class="flex items-center justify-between mb-2">
                <span class="text-[9px] font-black uppercase tracking-widest text-slate-400">Credit Score</span>
                <div class="w-8 h-8 rounded-xl bg-purple-500/10 flex items-center justify-center text-purple-500">
                    <i data-lucide="trending-up" class="w-4 h-4"></i>
                </div>
            </div>
            <p class="text-xl font-black" :class="getCreditColor()" x-text="creditScore"></p>
            <p class="text-[10px] text-slate-400 mt-1" x-text="getCreditRating()"></p>
        </div>
      </div>

      <!-- Tabs -->
      <div class="glass-card rounded-t-[1.5rem] border-b-0 border border-slate-200 dark:border-slate-800 mb-0">
        <div class="flex items-center gap-1 p-2">
            <button @click="activeTab = 'loans'" 
                    :class="activeTab === 'loans' ? 'active bg-theme/10 text-theme' : 'text-slate-500 hover:text-slate-700 dark:hover:text-slate-300'"
                    class="tab-btn px-6 py-3 rounded-xl text-xs font-black uppercase tracking-widest transition-all">
                <span class="flex items-center gap-2"><i data-lucide="list" class="w-4 h-4"></i> All Loans</span>
            </button>
            <button @click="activeTab = 'repayments'" 
                    :class="activeTab === 'repayments' ? 'active bg-theme/10 text-theme' : 'text-slate-500 hover:text-slate-700 dark:hover:text-slate-300'"
                    class="tab-btn px-6 py-3 rounded-xl text-xs font-black uppercase tracking-widest transition-all">
                <span class="flex items-center gap-2"><i data-lucide="history" class="w-4 h-4"></i> Repayment History</span>
            </button>
        </div>
      </div>

      <!-- All Loans Tab -->
      <div x-show="activeTab === 'loans'" class="glass-card rounded-b-[1.5rem] rounded-tr-[1.5rem] border border-slate-200 dark:border-slate-800 border-t-0 overflow-hidden">
        <div x-show="loans.length === 0" class="p-12 text-center">
            <div class="w-16 h-16 rounded-2xl bg-theme/10 flex items-center justify-center text-theme mx-auto mb-4">
                <i data-lucide="banknote" class="w-8 h-8"></i>
            </div>
            <h3 class="text-lg font-black text-slate-900 dark:text-white mb-2">No Loan History</h3>
            <p class="text-sm text-slate-500 dark:text-slate-400 mb-6">You haven't applied for any loans yet.</p>
            <a href="Loan_Application.php" class="px-6 py-3 rounded-2xl bg-theme text-white font-black uppercase tracking-widest text-xs hover:brightness-110 transition-all inline-flex items-center gap-2">
                <i data-lucide="plus" class="w-4 h-4"></i> Apply for Loan
            </a>
        </div>

        <div x-show="loans.length > 0" class="overflow-x-auto">
            <table class="w-full">
                <thead>
                    <tr class="border-b border-slate-200 dark:border-slate-800">
                        <th class="text-left px-6 py-4 text-[9px] font-black uppercase tracking-widest text-slate-400">Loan ID</th>
                        <th class="text-left px-6 py-4 text-[9px] font-black uppercase tracking-widest text-slate-400">Amount</th>
                        <th class="text-left px-6 py-4 text-[9px] font-black uppercase tracking-widest text-slate-400">Purpose</th>
                        <th class="text-left px-6 py-4 text-[9px] font-black uppercase tracking-widest text-slate-400">Duration</th>
                        <th class="text-left px-6 py-4 text-[9px] font-black uppercase tracking-widest text-slate-400">Progress</th>
                        <th class="text-left px-6 py-4 text-[9px] font-black uppercase tracking-widest text-slate-400">Status</th>
                        <th class="text-left px-6 py-4 text-[9px] font-black uppercase tracking-widest text-slate-400">Applied</th>
                        <th class="text-right px-6 py-4 text-[9px] font-black uppercase tracking-widest text-slate-400">Action</th>
                    </tr>
                </thead>
                <tbody>
                    <template x-for="loan in loans" :key="loan.id">
                        <tr class="loan-row border-b border-slate-100 dark:border-slate-800/50 last:border-0">
                            <td class="px-6 py-4">
                                <span class="text-sm font-black text-slate-900 dark:text-white" x-text="loan.id"></span>
                            </td>
                            <td class="px-6 py-4">
                                <span class="text-sm font-black text-slate-900 dark:text-white" x-text="formatCurrency(loan.amount)"></span>
                                <p class="text-[10px] text-slate-400" x-text="formatCurrency(loan.monthly_payment) + '/mo'"></p>
                            </td>
                            <td class="px-6 py-4">
                                <span class="text-sm font-bold text-slate-700 dark:text-slate-300" x-text="loan.purpose"></span>
                            </td>
                            <td class="px-6 py-4">
                                <span class="text-sm font-bold text-slate-700 dark:text-slate-300" x-text="loan.duration + ' months'"></span>
                            </td>
                            <td class="px-6 py-4 w-48">
                                <div class="flex items-center gap-2">
                                    <div class="flex-1 progress-bar">
                                        <div class="progress-fill" :style="'width: ' + loan.progress + '%'"></div>
                                    </div>
                                    <span class="text-xs font-black text-theme w-10 text-right" x-text="loan.progress + '%'"></span>
                                </div>
                                <p class="text-[10px] text-slate-400 mt-1" x-text="formatCurrency(loan.total_repaid) + ' of ' + formatCurrency(loan.total_repayment)"></p>
                            </td>
                            <td class="px-6 py-4">
                                <span class="px-2 py-1 rounded text-[9px] font-black uppercase tracking-widest" :class="'status-' + loan.status" x-text="loan.status"></span>
                            </td>
                            <td class="px-6 py-4">
                                <span class="text-sm text-slate-500 dark:text-slate-400" x-text="formatDate(loan.applied_at)"></span>
                            </td>
                            <td class="px-6 py-4 text-right">
                                <button @click="loadLoanDetails(loan)" 
                                        :disabled="isLoading"
                                        class="px-4 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400 text-xs font-black uppercase tracking-widest hover:bg-theme hover:text-white transition-all flex items-center gap-2 ml-auto">
                                    <i data-lucide="eye" class="w-3 h-3"></i> Details
                                </button>
                            </td>
                        </tr>
                    </template>
                </tbody>
            </table>
        </div>
      </div>

      <!-- Repayment History Tab -->
      <div x-show="activeTab === 'repayments'" class="glass-card rounded-b-[1.5rem] rounded-tl-[1.5rem] border border-slate-200 dark:border-slate-800 border-t-0 overflow-hidden">
        <div x-show="repaymentHistory.length === 0 && !isLoading" class="p-12 text-center">
            <div class="w-16 h-16 rounded-2xl bg-slate-100 dark:bg-slate-800 flex items-center justify-center text-slate-400 mx-auto mb-4">
                <i data-lucide="history" class="w-8 h-8"></i>
            </div>
            <h3 class="text-lg font-black text-slate-900 dark:text-white mb-2">No Repayments Yet</h3>
            <p class="text-sm text-slate-500 dark:text-slate-400">Your repayment history will appear here.</p>
        </div>

        <div x-show="isLoading" class="p-12 text-center">
            <div class="animate-spin w-8 h-8 border-2 border-theme border-t-transparent rounded-full mx-auto"></div>
            <p class="text-sm text-slate-500 mt-4">Loading history...</p>
        </div>

        <div x-show="repaymentHistory.length > 0 && !isLoading" class="overflow-x-auto">
            <table class="w-full">
                <thead>
                    <tr class="border-b border-slate-200 dark:border-slate-800">
                        <th class="text-left px-6 py-4 text-[9px] font-black uppercase tracking-widest text-slate-400">Payment ID</th>
                        <th class="text-left px-6 py-4 text-[9px] font-black uppercase tracking-widest text-slate-400">Loan ID</th>
                        <th class="text-left px-6 py-4 text-[9px] font-black uppercase tracking-widest text-slate-400">Purpose</th>
                        <th class="text-right px-6 py-4 text-[9px] font-black uppercase tracking-widest text-slate-400">Amount</th>
                        <th class="text-right px-6 py-4 text-[9px] font-black uppercase tracking-widest text-slate-400">Date & Time</th>
                    </tr>
                </thead>
                <tbody>
                    <template x-for="payment in repaymentHistory" :key="payment.id">
                        <tr class="loan-row border-b border-slate-100 dark:border-slate-800/50 last:border-0">
                            <td class="px-6 py-4">
                                <span class="text-sm font-black text-slate-900 dark:text-white" x-text="payment.id"></span>
                            </td>
                            <td class="px-6 py-4">
                                <a :href="'Loan_Application.php?loan=' + payment.raw_loan_id" class="text-sm font-bold text-theme hover:underline" x-text="payment.loan_id"></a>
                            </td>
                            <td class="px-6 py-4">
                                <span class="text-sm text-slate-600 dark:text-slate-400" x-text="payment.purpose"></span>
                            </td>
                            <td class="px-6 py-4 text-right">
                                <span class="text-sm font-black text-emerald-500" x-text="'+' + formatCurrency(payment.amount)"></span>
                            </td>
                            <td class="px-6 py-4 text-right">
                                <span class="text-sm text-slate-500 dark:text-slate-400" x-text="formatDateTime(payment.paid_at)"></span>
                            </td>
                        </tr>
                    </template>
                </tbody>
            </table>

            <!-- Pagination -->
            <div class="flex items-center justify-between px-6 py-4 border-t border-slate-200 dark:border-slate-800" x-show="totalHistoryPages > 1">
                <span class="text-xs text-slate-500 dark:text-slate-400">Page <span x-text="historyPage"></span> of <span x-text="totalHistoryPages"></span></span>
                <div class="flex gap-2">
                    <button @click="loadRepaymentHistory(historyPage - 1)" 
                            :disabled="historyPage <= 1 || isLoading"
                            :class="historyPage <= 1 ? 'opacity-50 cursor-not-allowed' : 'hover:bg-theme hover:text-white'"
                            class="px-4 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400 text-xs font-black uppercase tracking-widest transition-all">
                        Previous
                    </button>
                    <button @click="loadRepaymentHistory(historyPage + 1)" 
                            :disabled="historyPage >= totalHistoryPages || isLoading"
                            :class="historyPage >= totalHistoryPages ? 'opacity-50 cursor-not-allowed' : 'hover:bg-theme hover:text-white'"
                            class="px-4 py-2 rounded-xl bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400 text-xs font-black uppercase tracking-widest transition-all">
                        Next
                    </button>
                </div>
            </div>
        </div>
      </div>

    </div>
  </main>

  <!-- Loan Detail Modal -->
  <div x-show="showDetailModal" style="display: none;" class="fixed inset-0 z-50 flex items-center justify-center modal-overlay p-4" x-transition>
    <div class="glass-card rounded-[2rem] max-w-4xl w-full max-h-[90vh] overflow-y-auto border border-slate-200 dark:border-slate-800 shadow-2xl relative" @click.away="showDetailModal = false">
        
        <button @click="showDetailModal = false" class="absolute top-6 right-6 w-10 h-10 rounded-full bg-slate-100 dark:bg-slate-800 flex items-center justify-center text-slate-400 hover:text-slate-600 transition-colors z-10">
            <i data-lucide="x" class="w-5 h-5"></i>
        </button>

        <div x-show="isLoading" class="p-12 text-center">
            <div class="animate-spin w-8 h-8 border-2 border-theme border-t-transparent rounded-full mx-auto"></div>
            <p class="text-sm text-slate-500 mt-4">Loading details...</p>
        </div>

        <template x-if="loanDetails && !isLoading">
            <div class="p-8">
                <!-- Modal Header -->
                <div class="flex items-start justify-between mb-8">
                    <div>
                        <div class="flex items-center gap-3 mb-2">
                            <h2 class="text-2xl font-black text-slate-900 dark:text-white" x-text="loanDetails.id"></h2>
                            <span class="px-3 py-1 rounded-lg text-[10px] font-black uppercase tracking-widest" :class="'status-' + loanDetails.status" x-text="loanDetails.status"></span>
                        </div>
                        <p class="text-sm text-slate-500 dark:text-slate-400" x-text="loanDetails.purpose + ' Loan'"></p>
                    </div>
                    <div class="text-right">
                        <p class="text-3xl font-black text-slate-900 dark:text-white" x-text="formatCurrency(loanDetails.amount)"></p>
                        <p class="text-xs text-slate-400" x-text="loanDetails.duration + ' months @ ' + loanDetails.interest_rate + '% APR'"></p>
                    </div>
                </div>

                <!-- Loan Summary Cards -->
                <div class="grid grid-cols-2 md:grid-cols-4 gap-3 mb-8">
                    <div class="p-4 rounded-xl bg-slate-50 dark:bg-slate-900/50 border border-slate-200 dark:border-slate-800">
                        <p class="text-[8px] font-black uppercase tracking-widest text-slate-400 mb-1">Monthly Payment</p>
                        <p class="text-lg font-black text-theme" x-text="formatCurrency(loanDetails.monthly_payment)"></p>
                    </div>
                    <div class="p-4 rounded-xl bg-slate-50 dark:bg-slate-900/50 border border-slate-200 dark:border-slate-800">
                        <p class="text-[8px] font-black uppercase tracking-widest text-slate-400 mb-1">Total Interest</p>
                        <p class="text-lg font-black text-rose-500" x-text="formatCurrency(loanDetails.total_interest)"></p>
                    </div>
                    <div class="p-4 rounded-xl bg-slate-50 dark:bg-slate-900/50 border border-slate-200 dark:border-slate-800">
                        <p class="text-[8px] font-black uppercase tracking-widest text-slate-400 mb-1">Total Repayment</p>
                        <p class="text-lg font-black text-slate-900 dark:text-white" x-text="formatCurrency(loanDetails.total_repayment)"></p>
                    </div>
                    <div class="p-4 rounded-xl bg-slate-50 dark:bg-slate-900/50 border border-slate-200 dark:border-slate-800">
                        <p class="text-[8px] font-black uppercase tracking-widest text-slate-400 mb-1">Remaining</p>
                        <p class="text-lg font-black" :class="loanDetails.remaining_balance > 0 ? 'text-amber-500' : 'text-emerald-500'" x-text="formatCurrency(loanDetails.remaining_balance)"></p>
                    </div>
                </div>

                <!-- Repayment Timeline -->
                <div class="mb-8" x-show="repayments.length > 0">
                    <h3 class="text-xs font-black uppercase tracking-widest text-slate-400 mb-4">Repayment Timeline</h3>
                    <div class="relative pl-8 space-y-4">
                        <div class="timeline-line"></div>
                        <template x-for="(repayment, index) in repayments" :key="repayment.id">
                            <div class="relative">
                                <div class="absolute -left-8 top-1 w-8 h-8 rounded-full bg-emerald-500/10 border-2 border-emerald-500 flex items-center justify-center">
                                    <i data-lucide="check" class="w-3 h-3 text-emerald-500"></i>
                                </div>
                                <div class="p-4 rounded-xl bg-slate-50 dark:bg-slate-900/50 border border-slate-200 dark:border-slate-800">
                                    <div class="flex items-center justify-between">
                                        <div>
                                            <p class="text-sm font-black text-slate-900 dark:text-white">Payment #<span x-text="repayments.length - index"></span></p>
                                            <p class="text-xs text-slate-500" x-text="formatDateTime(repayment.paid_at)"></p>
                                        </div>
                                        <span class="text-lg font-black text-emerald-500" x-text="formatCurrency(repayment.amount)"></span>
                                    </div>
                                </div>
                            </div>
                        </template>
                    </div>
                </div>

                <!-- Amortization Schedule -->
                <div x-show="schedule.length > 0">
                    <h3 class="text-xs font-black uppercase tracking-widest text-slate-400 mb-4">Amortization Schedule</h3>
                    <div class="overflow-x-auto rounded-xl border border-slate-200 dark:border-slate-800">
                        <table class="w-full">
                            <thead>
                                <tr class="bg-slate-50 dark:bg-slate-900/50 border-b border-slate-200 dark:border-slate-800">
                                    <th class="text-left px-4 py-3 text-[9px] font-black uppercase tracking-widest text-slate-400">#</th>
                                    <th class="text-left px-4 py-3 text-[9px] font-black uppercase tracking-widest text-slate-400">Due Date</th>
                                    <th class="text-right px-4 py-3 text-[9px] font-black uppercase tracking-widest text-slate-400">Payment</th>
                                    <th class="text-right px-4 py-3 text-[9px] font-black uppercase tracking-widest text-slate-400">Principal</th>
                                    <th class="text-right px-4 py-3 text-[9px] font-black uppercase tracking-widest text-slate-400">Interest</th>
                                    <th class="text-right px-4 py-3 text-[9px] font-black uppercase tracking-widest text-slate-400">Balance</th>
                                    <th class="text-center px-4 py-3 text-[9px] font-black uppercase tracking-widest text-slate-400">Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <template x-for="item in schedule" :key="item.payment_no">
                                    <tr class="amortization-row border-b border-slate-100 dark:border-slate-800/50 last:border-0">
                                        <td class="px-4 py-3 text-sm font-bold text-slate-700 dark:text-slate-300" x-text="item.payment_no"></td>
                                        <td class="px-4 py-3 text-sm text-slate-600 dark:text-slate-400" x-text="formatDate(item.due_date)"></td>
                                        <td class="px-4 py-3 text-sm font-black text-slate-900 dark:text-white text-right" x-text="formatCurrency(item.payment_amount)"></td>
                                        <td class="px-4 py-3 text-sm text-emerald-600 text-right" x-text="formatCurrency(item.principal)"></td>
                                        <td class="px-4 py-3 text-sm text-rose-500 text-right" x-text="formatCurrency(item.interest)"></td>
                                        <td class="px-4 py-3 text-sm font-bold text-slate-700 dark:text-slate-300 text-right" x-text="formatCurrency(item.remaining_balance)"></td>
                                        <td class="px-4 py-3 text-center">
                                            <span class="text-xs font-black uppercase" :class="getPaymentStatusClass(item.status)" x-text="item.status"></span>
                                        </td>
                                    </tr>
                                </template>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- Action Buttons -->
                <div class="flex gap-3 mt-8 pt-6 border-t border-slate-200 dark:border-slate-800" x-show="loanDetails.status === 'approved' || loanDetails.status === 'late'">
                    <a :href="'Loan_Application.php?repay=' + loanDetails.raw_id" class="flex-1 py-4 rounded-2xl bg-theme text-white font-black uppercase tracking-widest text-sm text-center hover:brightness-110 transition-all">
                        Make Payment
                    </a>
                </div>
            </div>
        </template>
    </div>
  </div>

</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();
    });
    
    document.addEventListener('alpine:initialized', () => {
        Alpine.effect(() => {
            setTimeout(() => { lucide.createIcons(); }, 50);
        });
    });
</script>

</body>
</html>