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

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

// Get loan ID from URL
$loan_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$loan_id) {
    $_SESSION['error'] = "Invalid loan ID.";
    header("Location: loans.php");
    exit();
}

// Get loan details with user information
$stmt = $db->prepare("
    SELECT l.*, u.first_name, u.last_name, u.email, u.account_number, u.phone, u.balance, u.currency
    FROM loans l
    JOIN users u ON l.user_id = u.id
    WHERE l.id = ?
");
$stmt->execute([$loan_id]);
$loan = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$loan) {
    $_SESSION['error'] = "Loan not found.";
    header("Location: loans.php");
    exit();
}

// Get loan payments
$stmt = $db->prepare("
    SELECT * FROM loan_payments
    WHERE loan_id = ?
    ORDER BY payment_date DESC
");
$stmt->execute([$loan_id]);
$payments = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Calculate loan metrics
$total_paid = 0;
foreach ($payments as $payment) {
    $total_paid += $payment['amount'];
}

$remaining_balance = $loan['total_amount'] - $total_paid;
$payment_progress = ($total_paid / $loan['total_amount']) * 100;

// Get loan documents
$stmt = $db->prepare("
    SELECT * FROM loan_documents
    WHERE loan_id = ?
    ORDER BY uploaded_at DESC
");
$stmt->execute([$loan_id]);
$documents = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get loan notes/history
$stmt = $db->prepare("
    SELECT ln.*, a.username as admin_name
    FROM loan_notes ln
    LEFT JOIN admin_users a ON ln.admin_id = a.id
    WHERE ln.loan_id = ?
    ORDER BY ln.created_at DESC
");
$stmt->execute([$loan_id]);
$notes = $stmt->fetchAll(PDO::FETCH_ASSOC);

include 'includes/header.php';
include 'includes/sidebar.php';
?>

<div class="content-wrapper">
    <div class="container-fluid">
        <!-- Page Heading -->
        <div class="d-sm-flex align-items-center justify-content-between mb-4">
            <h1 class="h3 mb-0 text-gray-800">Loan Details</h1>
            <div>
                <a href="loans.php" class="btn btn-sm btn-secondary shadow-sm">
                    <i class="fas fa-arrow-left fa-sm text-white-50"></i> Back to Loans
                </a>
                <a href="loan_edit.php?id=<?php echo $loan_id; ?>" class="btn btn-sm btn-primary shadow-sm">
                    <i class="fas fa-edit fa-sm text-white-50"></i> Edit Loan
                </a>
                <?php if ($loan['status'] == 'pending'): ?>
                    <button class="btn btn-sm btn-success shadow-sm approve-loan">
                        <i class="fas fa-check fa-sm text-white-50"></i> Approve
                    </button>
                    <button class="btn btn-sm btn-danger shadow-sm reject-loan">
                        <i class="fas fa-times fa-sm text-white-50"></i> Reject
                    </button>
                <?php endif; ?>
            </div>
        </div>

        <?php if (isset($_SESSION['success'])): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
        <?php endif; ?>

        <?php if (isset($_SESSION['error'])): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?php echo $_SESSION['error']; unset($_SESSION['error']); ?>
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
        <?php endif; ?>

        <div class="row">
            <!-- Loan Overview -->
            <div class="col-xl-4 col-md-6 mb-4">
                <div class="card shadow h-100">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">Loan Overview</h6>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <span class="badge badge-<?php 
                                switch ($loan['status']) {
                                    case 'pending': echo 'warning'; break;
                                    case 'active': echo 'success'; break;
                                    case 'paid_off': echo 'info'; break;
                                    case 'rejected': echo 'danger'; break;
                                    default: echo 'secondary';
                                }
                            ?> badge-pill px-3 py-2 mb-3">
                                <?php echo ucfirst($loan['status']); ?>
                            </span>
                        </div>
                        
                        <div class="mb-3">
                            <h5>Loan Amount</h5>
                            <h2 class="text-primary">$<?php echo number_format($loan['total_amount'], 2); ?></h2>
                        </div>
                        
                        <div class="mb-3">
                            <h6>Loan Type</h6>
                            <p class="mb-0"><?php echo htmlspecialchars($loan['loan_type']); ?></p>
                        </div>
                        
                        <div class="mb-3">
                            <h6>Interest Rate</h6>
                            <p class="mb-0"><?php echo $loan['interest_rate']; ?>%</p>
                        </div>
                        
                        <div class="mb-3">
                            <h6>Term</h6>
                            <p class="mb-0"><?php echo $loan['term_months']; ?> months</p>
                        </div>
                        
                        <div class="mb-3">
                            <h6>Monthly Payment</h6>
                            <p class="mb-0">$<?php echo number_format($loan['monthly_payment'], 2); ?></p>
                        </div>
                        
                        <div class="mb-3">
                            <h6>Start Date</h6>
                            <p class="mb-0"><?php echo $loan['start_date'] ? date('M d, Y', strtotime($loan['start_date'])) : 'Not started'; ?></p>
                        </div>
                        
                        <div class="mb-3">
                            <h6>End Date</h6>
                            <p class="mb-0"><?php echo $loan['end_date'] ? date('M d, Y', strtotime($loan['end_date'])) : 'Not determined'; ?></p>
                        </div>
                        
                        <div class="mb-3">
                            <h6>Created</h6>
                            <p class="mb-0"><?php echo date('M d, Y', strtotime($loan['created_at'])); ?></p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Borrower Information -->
            <div class="col-xl-4 col-md-6 mb-4">
                <div class="card shadow h-100">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">Borrower Information</h6>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <h5><?php echo htmlspecialchars($loan['first_name'] . ' ' . $loan['last_name']); ?></h5>
                            <p class="text-muted mb-0">Account #: <?php echo htmlspecialchars($loan['account_number']); ?></p>
                        </div>
                        
                        <div class="mb-3">
                            <h6>Contact Information</h6>
                            <p class="mb-1"><i class="fas fa-envelope mr-2"></i> <?php echo htmlspecialchars($loan['email']); ?></p>
                            <p class="mb-0"><i class="fas fa-phone mr-2"></i> <?php echo htmlspecialchars($loan['phone']); ?></p>
                        </div>
                        
                        <div class="mb-3">
                            <h6>Account Balance</h6>
                            <p class="mb-0"><?php echo htmlspecialchars($loan['currency']); ?> <?php echo number_format($loan['balance'], 2); ?></p>
                        </div>
                        
                        <div class="mb-3">
                            <h6>Purpose of Loan</h6>
                            <p class="mb-0"><?php echo htmlspecialchars($loan['purpose']); ?></p>
                        </div>
                        
                        <div class="mb-3">
                            <a href="user_details.php?id=<?php echo $loan['user_id']; ?>" class="btn btn-info btn-sm">
                                <i class="fas fa-user mr-1"></i> View Full Profile
                            </a>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Payment Progress -->
            <div class="col-xl-4 col-md-12 mb-4">
                <div class="card shadow h-100">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">Payment Progress</h6>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <h5>Repayment Status</h5>
                            <div class="progress mb-2" style="height: 20px;">
                                <div class="progress-bar bg-success" role="progressbar" style="width: <?php echo $payment_progress; ?>%;" 
                                    aria-valuenow="<?php echo $payment_progress; ?>" aria-valuemin="0" aria-valuemax="100">
                                    <?php echo round($payment_progress); ?>%
                                </div>
                            </div>
                            <div class="d-flex justify-content-between">
                                <small>Paid: $<?php echo number_format($total_paid, 2); ?></small>
                                <small>Total: $<?php echo number_format($loan['total_amount'], 2); ?></small>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <h6>Remaining Balance</h6>
                            <h3 class="text-<?php echo $remaining_balance > 0 ? 'danger' : 'success'; ?>">
                                $<?php echo number_format($remaining_balance, 2); ?>
                            </h3>
                        </div>
                        
                        <div class="mb-3">
                            <h6>Payments Made</h6>
                            <p class="mb-0"><?php echo count($payments); ?> of <?php echo $loan['term_months']; ?> monthly payments</p>
                        </div>
                        
                        <div class="mb-3">
                            <h6>Next Payment Due</h6>
                            <p class="mb-0">
                                <?php 
                                if ($loan['status'] == 'active') {
                                    $next_payment_date = date('M d, Y', strtotime('+1 month', strtotime($loan['last_payment_date'] ?? $loan['start_date'])));
                                    echo $next_payment_date;
                                } else {
                                    echo 'N/A';
                                }
                                ?>
                            </p>
                        </div>
                        
                        <?php if ($loan['status'] == 'active'): ?>
                            <div class="mb-3">
                                <button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#addPaymentModal">
                                    <i class="fas fa-plus mr-1"></i> Record Payment
                                </button>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Payment History -->
            <div class="col-lg-6 mb-4">
                <div class="card shadow mb-4">
                    <div class="card-header py-3">
                        <h6 class="m-0 font-weight-bold text-primary">Payment History</h6>
                    </div>
                    <div class="card-body">
                        <?php if (empty($payments)): ?>
                            <div class="text-center py-4">
                                <i class="fas fa-money-bill-wave fa-3x text-gray-300 mb-3"></i>
                                <p class="mb-0">No payments have been made yet.</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-bordered" width="100%" cellspacing="0">
                                    <thead>
                                        <tr>
                                            <th>Date</th>
                                            <th>Amount</th>
                                            <th>Method</th>
                                            <th>Reference</th>
                                            <th>Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($payments as $payment): ?>
                                            <tr>
                                                <td><?php echo date('M d, Y', strtotime($payment['payment_date'])); ?></td>
                                               
                                                <td>$<?php echo number_format($payment['amount'], 2); ?></td>
                                                <td><?php echo htmlspecialchars($payment['payment_method']); ?></td>
                                                <td><?php echo htmlspecialchars($payment['transaction_reference']); ?></td>
                                                <td><span class="badge badge-success">Completed</span></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Loan Notes & History -->
            <div class="col-lg-6 mb-4">
                <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">Loan Notes & History</h6>
                        <button class="btn btn-sm btn-primary" data-toggle="modal" data-target="#addNoteModal">
                            <i class="fas fa-plus fa-sm"></i> Add Note
                        </button>
                    </div>
                    <div class="card-body" style="max-height: 400px; overflow-y: auto;">
                        <?php if (empty($notes)): ?>
                            <div class="text-center py-4">
                                <i class="fas fa-sticky-note fa-3x text-gray-300 mb-3"></i>
                                <p class="mb-0">No notes have been added for this loan.</p>
                            </div>
                        <?php else: ?>
                            <ul class="list-group list-group-flush">
                                <?php foreach ($notes as $note): ?>
                                    <li class="list-group-item">
                                        <p class="mb-1"><?php echo htmlspecialchars($note['note']); ?></p>
                                        <small class="text-muted">
                                            By <?php echo htmlspecialchars($note['admin_name'] ?? 'Admin'); ?> 
                                            on <?php echo date('M d, Y, g:i A', strtotime($note['created_at'])); ?>
                                        </small>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Loan Documents -->
        <div class="row">
            <div class="col-lg-12">
                <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">Loan Documents</h6>
                        <button class="btn btn-sm btn-primary" data-toggle="modal" data-target="#uploadDocumentModal">
                            <i class="fas fa-upload fa-sm"></i> Upload Document
                        </button>
                    </div>
                    <div class="card-body">
                        <?php if (empty($documents)): ?>
                            <div class="text-center py-4">
                                <i class="fas fa-file-alt fa-3x text-gray-300 mb-3"></i>
                                <p class="mb-0">No documents have been uploaded for this loan.</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-bordered" width="100%" cellspacing="0">
                                    <thead>
                                        <tr>
                                            <th>Document Name</th>
                                            <th>Type</th>
                                            <th>Uploaded At</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($documents as $doc): ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($doc['document_name']); ?></td>
                                                <td><?php echo htmlspecialchars($doc['document_type']); ?></td>
                                                <td><?php echo date('M d, Y', strtotime($doc['uploaded_at'])); ?></td>
                                                <td>
                                                    <a href="../uploads/loan_documents/<?php echo htmlspecialchars($doc['file_path']); ?>" target="_blank" class="btn btn-sm btn-info">
                                                        <i class="fas fa-download"></i> View
                                                    </a>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Payment Modal -->
<div class="modal fade" id="addPaymentModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Record a Payment</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <form id="addPaymentForm">
                <div class="modal-body">
                    <input type="hidden" name="loan_id" value="<?php echo $loan_id; ?>">
                    <div class="form-group">
                        <label for="payment_amount">Payment Amount</label>
                        <input type="number" class="form-control" id="payment_amount" name="amount" step="0.01" required>
                    </div>
                    <div class="form-group">
                        <label for="payment_date">Payment Date</label>
                        <input type="date" class="form-control" id="payment_date" name="payment_date" value="<?php echo date('Y-m-d'); ?>" required>
                    </div>
                    <div class="form-group">
                        <label for="payment_method">Payment Method</label>
                        <select class="form-control" id="payment_method" name="payment_method" required>
                            <option value="Bank Transfer">Bank Transfer</option>
                            <option value="Internal Debit">Internal Debit</option>
                            <option value="Cash">Cash</option>
                            <option value="Other">Other</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="transaction_reference">Transaction Reference (Optional)</label>
                        <input type="text" class="form-control" id="transaction_reference" name="transaction_reference">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Add Payment</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Add Note Modal -->
<div class="modal fade" id="addNoteModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add a Note</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <form id="addNoteForm">
                <div class="modal-body">
                    <input type="hidden" name="loan_id" value="<?php echo $loan_id; ?>">
                    <div class="form-group">
                        <label for="note_text">Note</label>
                        <textarea class="form-control" id="note_text" name="note" rows="4" required></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save Note</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Upload Document Modal -->
<div class="modal fade" id="uploadDocumentModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Upload Document</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <form id="uploadDocumentForm" enctype="multipart/form-data">
                <div class="modal-body">
                    <input type="hidden" name="loan_id" value="<?php echo $loan_id; ?>">
                    <div class="form-group">
                        <label for="document_name">Document Name</label>
                        <input type="text" class="form-control" id="document_name" name="document_name" required>
                    </div>
                    <div class="form-group">
                        <label for="document_type">Document Type</label>
                        <input type="text" class="form-control" id="document_type" name="document_type" placeholder="e.g., ID, Payslip" required>
                    </div>
                    <div class="form-group">
                        <label for="document_file">File</label>
                        <input type="file" class="form-control-file" id="document_file" name="document_file" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Upload</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Approve Loan Modal -->
<div class="modal fade" id="approveLoanModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Approve Loan</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <form id="approveLoanForm">
                <div class="modal-body">
                    <input type="hidden" name="loan_id" value="<?php echo $loan_id; ?>">
                    <p>Are you sure you want to approve this loan? This will disburse funds to the customer's account.</p>
                    <div class="form-group">
                        <label for="approval_note">Note (Optional)</label>
                        <textarea class="form-control" id="approval_note" name="note" rows="3"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-success">Approve Loan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Reject Loan Modal -->
<div class="modal fade" id="rejectLoanModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Reject Loan</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <form id="rejectLoanForm">
                <div class="modal-body">
                    <input type="hidden" name="loan_id" value="<?php echo $loan_id; ?>">
                    <p>Are you sure you want to reject this loan application?</p>
                    <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></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Reject Loan</button>
                </div>
            </form>
        </div>
    </div>
</div>

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

<script>
$(document).ready(function() {
    // Approve loan button
    $('.approve-loan').click(function() {
        $('#approveLoanModal').modal('show');
    });

    // Reject loan button
    $('.reject-loan').click(function() {
        $('#rejectLoanModal').modal('show');
    });

    // Handle Add Payment Form
    $('#addPaymentForm').submit(function(e) {
        e.preventDefault();
        $.ajax({
            url: 'ajax/loan_actions.php',
            type: 'POST',
            data: $(this).serialize() + '&action=add_payment',
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    Swal.fire({
                        title: 'Success!',
                        text: 'Payment has been recorded.',
                        icon: 'success',
                        confirmButtonText: 'OK'
                    }).then(() => {
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        title: 'Error!',
                        text: response.message || 'An error occurred while processing your request.',
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                }
            },
            error: function() {
                Swal.fire({
                    title: 'Error!',
                    text: 'An error occurred while processing your request.',
                    icon: 'error',
                    confirmButtonText: 'OK'
                });
            }
        });
    });

    // Handle Add Note Form
    $('#addNoteForm').submit(function(e) {
        e.preventDefault();
        $.ajax({
            url: 'ajax/loan_actions.php',
            type: 'POST',
            data: $(this).serialize() + '&action=add_note',
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    Swal.fire({
                        title: 'Success!',
                        text: 'Note has been added.',
                        icon: 'success',
                        confirmButtonText: 'OK'
                    }).then(() => {
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        title: 'Error!',
                        text: response.message || 'An error occurred while processing your request.',
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                }
            },
            error: function() {
                Swal.fire({
                    title: 'Error!',
                    text: 'An error occurred while processing your request.',
                    icon: 'error',
                    confirmButtonText: 'OK'
                });
            }
        });
    });

    // Handle Upload Document Form
    $('#uploadDocumentForm').submit(function(e) {
        e.preventDefault();
        var formData = new FormData(this);
        formData.append('action', 'upload_document');

        $.ajax({
            url: 'ajax/loan_actions.php',
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    Swal.fire({
                        title: 'Success!',
                        text: 'Document has been uploaded.',
                        icon: 'success',
                        confirmButtonText: 'OK'
                    }).then(() => {
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        title: 'Error!',
                        text: response.message || 'An error occurred while processing your request.',
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                }
            },
            error: function() {
                Swal.fire({
                    title: 'Error!',
                    text: 'An error occurred while processing your request.',
                    icon: 'error',
                    confirmButtonText: 'OK'
                });
            }
        });
    });

    // Handle Approve Loan Form
    $('#approveLoanForm').submit(function(e) {
        e.preventDefault();
        $.ajax({
            url: 'ajax/loan_actions.php',
            type: 'POST',
            data: $(this).serialize() + '&action=approve',
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    Swal.fire({
                        title: 'Success!',
                        text: 'Loan has been approved.',
                        icon: 'success',
                        confirmButtonText: 'OK'
                    }).then(() => {
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        title: 'Error!',
                        text: response.message || 'An error occurred while processing your request.',
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                }
            },
            error: function() {
                Swal.fire({
                    title: 'Error!',
                    text: 'An error occurred while processing your request.',
                    icon: 'error',
                    confirmButtonText: 'OK'
                });
            }
        });
    });

    // Handle Reject Loan Form
    $('#rejectLoanForm').submit(function(e) {
        e.preventDefault();
        $.ajax({
            url: 'ajax/loan_actions.php',
            type: 'POST',
            data: $(this).serialize() + '&action=reject',
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    Swal.fire({
                        title: 'Success!',
                        text: 'Loan has been rejected.',
                        icon: 'success',
                        confirmButtonText: 'OK'
                    }).then(() => {
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        title: 'Error!',
                        text: response.message || 'An error occurred while processing your request.',
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                }
            },
            error: function() {
                Swal.fire({
                    title: 'Error!',
                    text: 'An error occurred while processing your request.',
                    icon: 'error',
                    confirmButtonText: 'OK'
                });
            }
        });
    });
});
</script>
