<?php
session_start();
require_once '../config/database.php';
require_once 'includes/auth_check.php';

$page = 'loans';
$database = new Database();
$db = $database->getConnection();

// Get loans with user information
$stmt = $db->prepare("
    SELECT l.*, u.first_name, u.last_name, u.email, u.account_number 
    FROM loans l
    JOIN users u ON l.user_id = u.id
    ORDER BY l.created_at DESC
");
$stmt->execute();
$loans = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get loan statistics
$stats = [
    'total' => 0,
    'active' => 0,
    'pending' => 0,
    'paid_off' => 0,
    'rejected' => 0,
    'total_amount' => 0,
    'active_amount' => 0
];

$stmt = $db->query("SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) as active,
    SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
    SUM(CASE WHEN status = 'paid_off' THEN 1 ELSE 0 END) as paid_off,
    SUM(CASE WHEN status = 'rejected' THEN 1 ELSE 0 END) as rejected,
    SUM(total_amount) as total_amount,
    SUM(CASE WHEN status = 'active' THEN total_amount - amount_paid ELSE 0 END) as active_amount
    FROM loans");
$result = $stmt->fetch(PDO::FETCH_ASSOC);

if ($result) {
    $stats = $result;
}

include 'includes/header.php';
?>

<div class="content-wrapper">
    <div class="container-fluid">
        <!-- Page Header -->
        <div class="page-header">
            <div class="row align-items-center">
                <div class="col">
                    <h1 class="page-header-title text-primary">
                        <i class="fas fa-landmark mr-2"></i> Loan Management
                    </h1>
                    <p class="text-muted">Manage customer loan applications and active loans</p>
                </div>
                <div class="col-auto">
                    <a href="loan_create.php" class="btn btn-primary btn-lg shadow-sm">
                        <i class="fas fa-plus fa-sm text-white-50 mr-1"></i> Create New Loan
                    </a>
                </div>
            </div>
        </div>

        <!-- Loan Statistics Cards -->
        <div class="row mb-4">
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card border-left-primary shadow h-100 py-2 dashboard-card">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Total Loans</div>
                                <div class="h3 mb-0 font-weight-bold text-gray-800 counter-value"><?php echo number_format($stats['total']); ?></div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-dollar-sign fa-2x text-primary-light"></i>
                            </div>
                        </div>
                        <div class="mt-3">
                            <div class="progress" style="height: 5px;">
                                <div class="progress-bar bg-primary" role="progressbar" style="width: 100%;" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card border-left-success shadow h-100 py-2 dashboard-card">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-success text-uppercase mb-1">Active Loans</div>
                                <div class="h3 mb-0 font-weight-bold text-gray-800 counter-value"><?php echo number_format($stats['active']); ?></div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-check-circle fa-2x text-success-light"></i>
                            </div>
                        </div>
                        <div class="mt-3">
                            <div class="progress" style="height: 5px;">
                                <div class="progress-bar bg-success" role="progressbar" 
                                    style="width: <?php echo $stats['total'] > 0 ? ($stats['active'] / $stats['total'] * 100) : 0; ?>%;" 
                                    aria-valuenow="<?php echo $stats['total'] > 0 ? ($stats['active'] / $stats['total'] * 100) : 0; ?>" 
                                    aria-valuemin="0" 
                                    aria-valuemax="100"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card border-left-warning shadow h-100 py-2 dashboard-card">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Pending Applications</div>
                                <div class="h3 mb-0 font-weight-bold text-gray-800 counter-value"><?php echo number_format($stats['pending']); ?></div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-clock fa-2x text-warning-light"></i>
                            </div>
                        </div>
                        <div class="mt-3">
                            <div class="progress" style="height: 5px;">
                                <div class="progress-bar bg-warning" role="progressbar" 
                                    style="width: <?php echo $stats['total'] > 0 ? ($stats['pending'] / $stats['total'] * 100) : 0; ?>%;" 
                                    aria-valuenow="<?php echo $stats['total'] > 0 ? ($stats['pending'] / $stats['total'] * 100) : 0; ?>" 
                                    aria-valuemin="0" 
                                    aria-valuemax="100"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card border-left-info shadow h-100 py-2 dashboard-card">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-info text-uppercase mb-1">Total Outstanding</div>
                                <div class="h3 mb-0 font-weight-bold text-gray-800">$<span class="counter-value"><?php echo number_format($stats['active_amount'], 2); ?></span></div>
                            </div>
                            <div class="col-auto">
                                <i class="fas fa-money-bill-wave fa-2x text-info-light"></i>
                            </div>
                        </div>
                        <div class="mt-3">
                            <div class="progress" style="height: 5px;">
                                <div class="progress-bar bg-info" role="progressbar" 
                                    style="width: <?php echo $stats['total_amount'] > 0 ? ($stats['active_amount'] / $stats['total_amount'] * 100) : 0; ?>%;" 
                                    aria-valuenow="<?php echo $stats['total_amount'] > 0 ? ($stats['active_amount'] / $stats['total_amount'] * 100) : 0; ?>" 
                                    aria-valuemin="0" 
                                    aria-valuemax="100"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Loan Status Distribution Chart -->
        <div class="row mb-4">
            <div class="col-xl-8 col-lg-7">
                <div class="card shadow mb-4">
                    <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                        <h6 class="m-0 font-weight-bold text-primary">Monthly Loan Distribution</h6>
                    </div>
                    <div class="card-body">
                        <div class="chart-area">
                            <canvas id="loanDistributionChart" height="300"></canvas>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xl-4 col-lg-5">
                <div class="card shadow mb-4">
                    <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                        <h6 class="m-0 font-weight-bold text-primary">Loan Status Distribution</h6>
                    </div>
                    <div class="card-body">
                        <div class="chart-pie pt-4 pb-2">
                            <canvas id="loanStatusChart"></canvas>
                        </div>
                        <div class="mt-4 text-center small">
                            <span class="mr-2">
                                <i class="fas fa-circle text-success"></i> Active
                            </span>
                            <span class="mr-2">
                                <i class="fas fa-circle text-warning"></i> Pending
                            </span>
                            <span class="mr-2">
                                <i class="fas fa-circle text-info"></i> Paid Off
                            </span>
                            <span class="mr-2">
                                <i class="fas fa-circle text-danger"></i> Rejected
                            </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Loans Table -->
        <div class="card shadow mb-4">
            <div class="card-header py-3 d-flex justify-content-between align-items-center">
                <h6 class="m-0 font-weight-bold text-primary">All Loans</h6>
                <div class="btn-group">
                    <button type="button" class="btn btn-outline-primary btn-sm dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                        <i class="fas fa-filter fa-sm"></i> Filter
                    </button>
                    <div class="dropdown-menu dropdown-menu-right">
                        <a class="dropdown-item filter-status" href="#" data-status="all">All Loans</a>
                        <a class="dropdown-item filter-status" href="#" data-status="active">Active Loans</a>
                        <a class="dropdown-item filter-status" href="#" data-status="pending">Pending Applications</a>
                        <a class="dropdown-item filter-status" href="#" data-status="paid_off">Paid Off Loans</a>
                        <a class="dropdown-item filter-status" href="#" data-status="rejected">Rejected Applications</a>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered table-hover" id="loansTable" width="100%" cellspacing="0">
                        <thead class="thead-light">
                            <tr>
                                <th>ID</th>
                                <th>Customer</th>
                                <th>Loan Type</th>
                                <th>Amount</th>
                                <th>Interest Rate</th>
                                <th>Term</th>
                                <th>Status</th>
                                <th>Created</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($loans as $loan): ?>
                                <tr class="loan-row" data-status="<?php echo $loan['status']; ?>">
                                    <td><?php echo $loan['id']; ?></td>
                                    <td>
                                        <div class="d-flex align-items-center">
                                            <div class="avatar avatar-sm mr-2 bg-primary text-white">
                                                <?php echo strtoupper(substr($loan['first_name'], 0, 1) . substr($loan['last_name'], 0, 1)); ?>
                                            </div>
                                            <div>
                                                <a href="user_details.php?id=<?php echo $loan['user_id']; ?>" class="font-weight-bold text-primary">
                                                    <?php echo htmlspecialchars($loan['first_name'] . ' ' . $loan['last_name']); ?>
                                                </a>
                                                <div class="small text-muted"><?php echo htmlspecialchars($loan['account_number']); ?></div>
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <span class="loan-type-badge badge badge-pill badge-light">
                                            <?php echo htmlspecialchars($loan['loan_type']); ?>
                                        </span>
                                    </td>
                                    <td class="font-weight-bold">$<?php echo number_format($loan['total_amount'], 2); ?></td>
                                    <td><?php echo $loan['interest_rate']; ?>%</td>
                                    <td>
                                        <?php 
                                        // Fix for undefined array key "term_months"
                                        echo isset($loan['term_months']) ? $loan['term_months'] . ' months' : 'N/A'; 
                                        ?>
                                    </td>
                                    <td>
                                        <?php 
                                        $statusClass = '';
                                        $statusIcon = '';
                                        switch ($loan['status']) {
                                            case 'pending':
                                                $statusClass = 'warning';
                                                $statusIcon = 'clock';
                                                break;
                                            case 'active':
                                                $statusClass = 'success';
                                                $statusIcon = 'check-circle';
                                                break;
                                            case 'paid_off':
                                                $statusClass = 'info';
                                                $statusIcon = 'check-double';
                                                break;
                                            case 'rejected':
                                                $statusClass = 'danger';
                                                $statusIcon = 'times-circle';
                                                break;
                                            default:
                                                $statusClass = 'secondary';
                                                $statusIcon = 'question-circle';
                                        }
                                        ?>
                                        <span class="badge badge-soft-<?php echo $statusClass; ?> px-3 py-2">
                                            <i class="fas fa-<?php echo $statusIcon; ?> mr-1"></i>
                                            <?php echo ucfirst($loan['status']); ?>
                                        </span>
                                    </td>
                                    <td><?php echo date('M d, Y', strtotime($loan['created_at'])); ?></td>
                                    <td>
                                        <div class="btn-group">
                                            <a href="loan_details.php?id=<?php echo $loan['id']; ?>" class="btn btn-sm btn-info" data-toggle="tooltip" title="View Details">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                            <a href="loan_edit.php?id=<?php echo $loan['id']; ?>" class="btn btn-sm btn-primary" data-toggle="tooltip" title="Edit Loan">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <?php if ($loan['status'] == 'pending'): ?>
                                                <button class="btn btn-sm btn-success approve-loan" data-id="<?php echo $loan['id']; ?>" data-toggle="tooltip" title="Approve Loan">
                                                    <i class="fas fa-check"></i>
                                                </button>
                                                <button class="btn btn-sm btn-danger reject-loan" data-id="<?php echo $loan['id']; ?>" data-toggle="tooltip" title="Reject Loan">
                                                    <i class="fas fa-times"></i>
                                                </button>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Approve Loan Modal -->
<div class="modal fade" id="approveLoanModal" tabindex="-1" role="dialog" aria-labelledby="approveLoanModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title" id="approveLoanModalLabel">
                    <i class="fas fa-check-circle mr-2"></i> Approve Loan
                </h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <form id="approveLoanForm">
                <div class="modal-body">
                    <input type="hidden" id="approve_loan_id" name="loan_id">
                    <div class="text-center mb-4">
                        <div class="avatar avatar-lg bg-success text-white mx-auto mb-3">
                            <i class="fas fa-check fa-2x"></i>
                        </div>
                        <h5>Confirm Loan Approval</h5>
                        <p class="text-muted">Are you sure you want to approve this loan? This will disburse funds to the customer's account.</p>
                    </div>
                    <div class="form-group">
                        <label for="approval_note">Note (Optional)</label>
                        <textarea class="form-control" id="approval_note" name="note" rows="3" placeholder="Add any notes regarding this approval..."></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-success">
                        <i class="fas fa-check mr-1"></i> Approve Loan
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Reject Loan Modal -->
<div class="modal fade" id="rejectLoanModal" tabindex="-1" role="dialog" aria-labelledby="rejectLoanModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title" id="rejectLoanModalLabel">
                    <i class="fas fa-times-circle mr-2"></i> Reject Loan
                </h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <form id="rejectLoanForm">
                <div class="modal-body">
                    <input type="hidden" id="reject_loan_id" name="loan_id">
                    <div class="text-center mb-4">
                        <div class="avatar avatar-lg bg-danger text-white mx-auto mb-3">
                            <i class="fas fa-times fa-2x"></i>
                        </div>
                        <h5>Confirm Loan Rejection</h5>
                        <p class="text-muted">Are you sure you want to reject this loan application?</p>
                    </div>
                    <div class="form-group">
                        <label for="rejection_reason">Reason for Rejection <span class="text-danger">*</span></label>
                        <textarea class="form-control" id="rejection_reason" name="reason" rows="3" required placeholder="Please provide a reason for rejecting this loan application..."></textarea>
                        <div class="invalid-feedback">Please provide a reason for rejection.</div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">
                        <i class="fas fa-times mr-1"></i> Reject Loan
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Add custom CSS for enhanced visuals -->
<style>
/* Custom Badge Styles */
.badge-soft-success {
    color: #10b981;
    background-color: rgba(16, 185, 129, 0.1);
}

.badge-soft-warning {
    color: #f59e0b;
    background-color: rgba(245, 158, 11, 0.1);
}

.badge-soft-info {
    color: #0ea5e9;
    background-color: rgba(14, 165, 233, 0.1);
}

.badge-soft-danger {
    color: #ef4444;
    background-color: rgba(239, 68, 68, 0.1);
}

.badge-soft-secondary {
    color: #6b7280;
    background-color: rgba(107, 114, 128, 0.1);
}

/* Avatar Styles */
.avatar {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 36px;
    height: 36px;
    border-radius: 50%;
    font-weight: 600;
}

.avatar-sm {
    width: 32px;
    height: 32px;
    font-size: 0.75rem;
}

.avatar-lg {
    width: 64px;
    height: 64px;
    font-size: 1.5rem;
}

/* Card Hover Effects */
.dashboard-card {
    transition: all 0.3s ease;
}

.dashboard-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15) !important;
}

/* Loan Type Badge */
.loan-type-badge {
    background-color: #f3f4f6;
    color: #4b5563;
    font-weight: 500;
}

/* Table Hover Effect */
#loansTable tbody tr {
    transition: all 0.2s ease;
}

#loansTable tbody tr:hover {
    background-color: #f8f9ff !important;
}

/* Custom Colors */
.text-primary-light {
    color: #818cf8;
}

.text-success-light {
    color: #34d399;
}

.text-warning-light {
    color: #fbbf24;
}

.text-info-light {
    color: #38bdf8;
}

/* Page Header */
.page-header {
    padding: 1.5rem 0;
    margin-bottom: 1.5rem;
    border-bottom: 1px solid #e5e7eb;
}

.page-header-title {
    font-size: 1.75rem;
    font-weight: 700;
    margin-bottom: 0.25rem;
}

/* Progress Bar Animation */
.progress-bar {
    transition: width 1s ease;
}

/* Counter Animation */
.counter-value {
    display: inline-block;
}
</style>

<?php include 'includes/footer.php'; ?>

<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/countup.js@2.0.7/dist/countUp.min.js"></script>

<script>
$(document).ready(function() {
    // Initialize DataTable with enhanced features
    var loansTable = $('#loansTable').DataTable({
        order: [[7, 'desc']], // Sort by created date by default
        responsive: true,
        pageLength: 10,
        lengthMenu: [[5, 10, 25, 50, -1], [5, 10, 25, 50, "All"]],
        language: {
            search: "<i class='fas fa-search'></i>",
            searchPlaceholder: "Search loans...",
            lengthMenu: "Show _MENU_ loans per page",
            info: "Showing _START_ to _END_ of _TOTAL_ loans",
            infoEmpty: "Showing 0 to 0 of 0 loans",
            infoFiltered: "(filtered from _MAX_ total loans)"
        },
        dom: '<"top"lf>rt<"bottom"ip><"clear">',
        initComplete: function() {
            // Add custom filter buttons styling
            $('.dataTables_length select').addClass('custom-select custom-select-sm');
            $('.dataTables_filter input').addClass('form-control-sm');
        }
    });

    // Initialize tooltips
    $('[data-toggle="tooltip"]').tooltip();

    // Filter by status
    $('.filter-status').click(function(e) {
        e.preventDefault();
        const status = $(this).data('status');
        
        if (status === 'all') {
            loansTable.column(6).search('').draw();
        } else {
            loansTable.column(6).search(status).draw();
        }
    });

    // Approve Loan
    $('.approve-loan').click(function() {
        const loanId = $(this).data('id');
        $('#approve_loan_id').val(loanId);
        $('#approveLoanModal').modal('show');
    });

    // Reject Loan
    $('.reject-loan').click(function() {
        const loanId = $(this).data('id');
        $('#reject_loan_id').val(loanId);
        $('#rejectLoanModal').modal('show');
    });

    // Handle Approve Form Submit
    $('#approveLoanForm').submit(function(e) {
        e.preventDefault();
        const loanId = $('#approve_loan_id').val();
        const note = $('#approval_note').val();

        $.ajax({
            url: 'ajax/loan_actions.php',
            type: 'POST',
            data: {
                action: 'approve',
                loan_id: loanId,
                note: note
            },
            dataType: 'json',
            beforeSend: function() {
                // Show loading state
                $('#approveLoanForm button[type="submit"]').html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Processing...');
                $('#approveLoanForm button[type="submit"]').prop('disabled', true);
            },
            success: function(response) {
                if (response.success) {
                    $('#approveLoanModal').modal('hide');
                    
                    Swal.fire({
                        title: 'Success!',
                        text: 'Loan has been approved and funds have been disbursed.',
                        icon: 'success',
                        confirmButtonText: 'OK',
                        confirmButtonColor: '#10b981'
                    }).then(() => {
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        title: 'Error!',
                        text: response.message || 'An error occurred while processing your request.',
                        icon: 'error',
                        confirmButtonText: 'OK',
                        confirmButtonColor: '#ef4444'
                    });
                    
                    // Reset button state
                    $('#approveLoanForm button[type="submit"]').html('<i class="fas fa-check mr-1"></i> Approve Loan');
                    $('#approveLoanForm button[type="submit"]').prop('disabled', false);
                }
            },
            error: function() {
                Swal.fire({
                    title: 'Error!',
                    text: 'An error occurred while processing your request.',
                    icon: 'error',
                    confirmButtonText: 'OK',
                    confirmButtonColor: '#ef4444'
                });
                
                // Reset button state
                $('#approveLoanForm button[type="submit"]').html('<i class="fas fa-check mr-1"></i> Approve Loan');
                $('#approveLoanForm button[type="submit"]').prop('disabled', false);
            }
        });
    });

    // Handle Reject Form Submit
    $('#rejectLoanForm').submit(function(e) {
        e.preventDefault();
        const loanId = $('#reject_loan_id').val();
        const reason = $('#rejection_reason').val();

        if (!reason.trim()) {
            $('#rejection_reason').addClass('is-invalid');
            return;
        }

        $.ajax({
            url: 'ajax/loan_actions.php',
            type: 'POST',
            data: {
                action: 'reject',
                loan_id: loanId,
                reason: reason
            },
            dataType: 'json',
            beforeSend: function() {
                // Show loading state
                $('#rejectLoanForm button[type="submit"]').html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Processing...');
                $('#rejectLoanForm button[type="submit"]').prop('disabled', true);
            },
            success: function(response) {
                if (response.success) {
                    $('#rejectLoanModal').modal('hide');
                    
                    Swal.fire({
                        title: 'Success!',
                        text: 'Loan application has been rejected.',
                        icon: 'success',
                        confirmButtonText: 'OK',
                        confirmButtonColor: '#10b981'
                    }).then(() => {
                        location.reload();
                    });
                } else {
                                     Swal.fire({
                        title: 'Error!',
                        text: response.message || 'An error occurred while processing your request.',
                        icon: 'error',
                        confirmButtonText: 'OK',
                        confirmButtonColor: '#ef4444'
                    });
                    
                    // Reset button state
                    $('#rejectLoanForm button[type="submit"]').html('<i class="fas fa-times mr-1"></i> Reject Loan');
                    $('#rejectLoanForm button[type="submit"]').prop('disabled', false);
                }
            },
            error: function() {
                Swal.fire({
                    title: 'Error!',
                    text: 'An error occurred while processing your request.',
                    icon: 'error',
                    confirmButtonText: 'OK',
                    confirmButtonColor: '#ef4444'
                });
                
                // Reset button state
                $('#rejectLoanForm button[type="submit"]').html('<i class="fas fa-times mr-1"></i> Reject Loan');
                $('#rejectLoanForm button[type="submit"]').prop('disabled', false);
            }
        });
    });

    // Initialize animated counters
    $('.counter-value').each(function() {
        const $this = $(this);
        const countTo = parseFloat($this.text().replace(/,/g, ''));
        
        const countUp = new CountUp($this[0], 0, countTo, 2, 2.5, {
            useEasing: true,
            useGrouping: true,
            separator: ',',
            decimal: '.'
        });
        
        if (!countUp.error) {
            countUp.start();
        } else {
            console.error(countUp.error);
        }
    });

    // Loan Status Distribution Chart
    const statusCtx = document.getElementById('loanStatusChart');
    if (statusCtx) {
        new Chart(statusCtx, {
            type: 'doughnut',
            data: {
                labels: ['Active', 'Pending', 'Paid Off', 'Rejected'],
                datasets: [{
                    data: [
                        <?php echo $stats['active']; ?>,
                        <?php echo $stats['pending']; ?>,
                        <?php echo $stats['paid_off']; ?>,
                        <?php echo $stats['rejected']; ?>
                    ],
                    backgroundColor: [
                        '#10b981', // success
                        '#f59e0b', // warning
                        '#0ea5e9', // info
                        '#ef4444'  // danger
                    ],
                    borderWidth: 0,
                    hoverOffset: 10
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                cutoutPercentage: 70,
                legend: {
                    display: false
                },
                tooltips: {
                    callbacks: {
                        label: function(tooltipItem, data) {
                            const dataset = data.datasets[tooltipItem.datasetIndex];
                            const total = dataset.data.reduce((previousValue, currentValue) => previousValue + currentValue);
                            const currentValue = dataset.data[tooltipItem.index];
                            const percentage = Math.round((currentValue/total) * 100);
                            return data.labels[tooltipItem.index] + ': ' + currentValue + ' (' + percentage + '%)';
                        }
                    }
                },
                animation: {
                    animateScale: true,
                    animateRotate: true,
                    duration: 2000,
                    easing: 'easeOutQuart'
                }
            }
        });
    }

    // Monthly Loan Distribution Chart
    const distributionCtx = document.getElementById('loanDistributionChart');
    if (distributionCtx) {
        // Get last 6 months for chart labels
        const months = [];
        const now = new Date();
        for (let i = 5; i >= 0; i--) {
            const month = new Date(now.getFullYear(), now.getMonth() - i, 1);
            months.push(month.toLocaleString('default', { month: 'short', year: 'numeric' }));
        }

        // Generate random data for demonstration
        // In a real application, this would come from your database
        const generateRandomData = (min, max, count) => {
            const data = [];
            for (let i = 0; i < count; i++) {
                data.push(Math.floor(Math.random() * (max - min + 1)) + min);
            }
            return data;
        };

        new Chart(distributionCtx, {
            type: 'bar',
            data: {
                labels: months,
                datasets: [
                    {
                        label: 'Active Loans',
                        backgroundColor: 'rgba(16, 185, 129, 0.7)',
                        borderColor: '#10b981',
                        borderWidth: 1,
                        data: generateRandomData(5, 20, 6)
                    },
                    {
                        label: 'Pending Applications',
                        backgroundColor: 'rgba(245, 158, 11, 0.7)',
                        borderColor: '#f59e0b',
                        borderWidth: 1,
                        data: generateRandomData(2, 15, 6)
                    },
                    {
                        label: 'Paid Off Loans',
                        backgroundColor: 'rgba(14, 165, 233, 0.7)',
                        borderColor: '#0ea5e9',
                        borderWidth: 1,
                        data: generateRandomData(1, 10, 6)
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    xAxes: [{
                        stacked: true,
                        gridLines: {
                            display: false
                        }
                    }],
                    yAxes: [{
                        stacked: true,
                        ticks: {
                            beginAtZero: true
                        }
                    }]
                },
                tooltips: {
                    mode: 'index',
                    intersect: false
                },
                animation: {
                    duration: 2000,
                    easing: 'easeOutQuart'
                }
            }
        });
    }

    // Input validation for rejection reason
    $('#rejection_reason').on('input', function() {
        if ($(this).val().trim()) {
            $(this).removeClass('is-invalid');
        } else {
            $(this).addClass('is-invalid');
        }
    });

    // Add hover effect to table rows
    $('#loansTable tbody tr').hover(
        function() {
            $(this).addClass('shadow-sm');
        },
        function() {
            $(this).removeClass('shadow-sm');
        }
    );

    // Add visual feedback when clicking action buttons
    $('.btn').on('click', function() {
        const $btn = $(this);
        $btn.addClass('pulse-animation');
        setTimeout(() => {
            $btn.removeClass('pulse-animation');
        }, 500);
    });

    // Add pulse animation
    $('<style>')
        .prop('type', 'text/css')
        .html(`
        @keyframes pulse-animation {
            0% {
                box-shadow: 0 0 0 0 rgba(79, 70, 229, 0.7);
            }
            70% {
                box-shadow: 0 0 0 10px rgba(79, 70, 229, 0);
            }
            100% {
                box-shadow: 0 0 0 0 rgba(79, 70, 229, 0);
            }
        }
        .pulse-animation {
            animation: pulse-animation 0.5s ease-out;
        }
        `)
        .appendTo('head');

    // Add color coding to loan types
    $('.loan-type-badge').each(function() {
        const loanType = $(this).text().trim().toLowerCase();
        let bgColor, textColor;
        
        switch(loanType) {
            case 'personal':
                bgColor = 'rgba(79, 70, 229, 0.1)';
                textColor = '#4f46e5';
                break;
            case 'business':
                bgColor = 'rgba(16, 185, 129, 0.1)';
                textColor = '#10b981';
                break;
            case 'mortgage':
                bgColor = 'rgba(245, 158, 11, 0.1)';
                textColor = '#f59e0b';
                break;
            case 'auto':
                bgColor = 'rgba(14, 165, 233, 0.1)';
                textColor = '#0ea5e9';
                break;
            case 'education':
                bgColor = 'rgba(236, 72, 153, 0.1)';
                textColor = '#ec4899';
                break;
            default:
                bgColor = 'rgba(107, 114, 128, 0.1)';
                textColor = '#6b7280';
        }
        
        $(this).css({
            'background-color': bgColor,
            'color': textColor
        });
    });
});
</script>

