<?php 
session_start();
include 'header.php'; 
$msg = "";

// Database connection (assuming $link is defined in header.php)
if(!isset($link)) {
    die("Database connection not established");
}

if(isset($_POST['delete'])){
    $uid = trim($_POST['userId']);
    
    $delete_query = mysqli_query($link, "DELETE FROM loan_plans WHERE id = '$uid'");
    if($delete_query) {
        echo '<script>alert("Loan plan was deleted successfully");window.location.href = "loanplan.php" </script>';
    } else {
        echo '<script>alert("Error deleting loan plan: '.mysqli_error($link).'");</script>';
    }
}

// Handle edit form submission
if(isset($_POST['update_plan'])){
    $id = mysqli_real_escape_string($link, $_POST['id']);
    $name = mysqli_real_escape_string($link, $_POST['name']);
    $min_deposit = mysqli_real_escape_string($link, $_POST['min_deposit']);
    $max_amount = mysqli_real_escape_string($link, $_POST['max_amount']);
    
    // Fixed SQL syntax error (removed comma before WHERE)
    $sql = "UPDATE loan_plans SET 
            name = '$name',
            min_deposit = '$min_deposit',
            max_amount = '$max_amount'
            WHERE id = '$id'";
            
    if(mysqli_query($link, $sql)){
        echo '<script>alert("Loan plan updated successfully");window.location.href = "loanplan.php"</script>';
    } else {
        echo '<script>alert("Error updating loan plan: '.mysqli_error($link).'");</script>';
    }
}

// Handle add new plan form submission
if(isset($_POST['add_plan'])){
    $name = mysqli_real_escape_string($link, $_POST['name']);
    $min_deposit = mysqli_real_escape_string($link, $_POST['min_deposit']);
    $max_amount = mysqli_real_escape_string($link, $_POST['max_amount']);
    
    // Fixed SQL syntax error (removed comma before VALUES)
    $sql = "INSERT INTO loan_plans (name, min_deposit, max_amount) 
            VALUES ('$name', '$min_deposit', '$max_amount')";
            
    if(mysqli_query($link, $sql)){
        echo '<script>alert("New loan plan added successfully");window.location.href = "loanplan.php"</script>';
    } else {
        echo '<script>alert("Error adding loan plan: '.mysqli_error($link).'");</script>';
    }
}
?>

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.jqueryui.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.5.6/css/buttons.jqueryui.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.5.6/css/buttons.bootstrap.min.css">

<script type="text/javascript" charset="utf8" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/dataTables.jqueryui.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/1.5.6/js/dataTables.buttons.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/1.5.6/js/buttons.jqueryui.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/1.5.6/js/buttons.html5.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/1.5.6/js/buttons.print.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/1.5.6/js/buttons.colVis.min.js"></script>

<style>
.table-responsive {
    overflow-x: hidden;
}
@media (max-width: 8000px) {
    .table-responsive {
        overflow-x: auto;
    }
}
.modal-lg {
    max-width: 800px;
}
</style>

<?php 
if ($msg != "") {
    echo "<div class='alert alert-success' style='padding:20px;background-color:#dce8f7;color:black'>$msg</div>"; 
}
?>

<div class="page-content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h4 class="card-title mb-0">Loan Plans</h4>
                        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addPlanModal">
                            Add New Plan
                        </button>
                    </div><!-- end card header -->

                    <div class="card-body">
                        <div id="customerList">
                            <div class="table-responsive table-card mt-3 mb-1">
                                <table id="myTable" class="table table-striped table-bordered" style="width:100%">  
                                    <thead class="table-light">
                                        <tr>
                                            <th>Plan Name</th>
                                            <th>Min Deposit</th>
                                            <th>Max Amount</th>
                                            <th>Action</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>  
                                        <?php 
                                        $sql = "SELECT * FROM loan_plans ORDER BY id DESC";
                                        $result = mysqli_query($link, $sql);
                                        if($result && mysqli_num_rows($result) > 0) {
                                            while($row = mysqli_fetch_assoc($result)) {  
                                        ?>
                                        <tr>
                                            <form method="post">
                                                <input type="hidden" name="userId" value="<?php echo $row['id']; ?>">
                                                <td><?php echo htmlspecialchars($row['name']); ?></td>
                                                <td><?php echo htmlspecialchars($row['min_deposit']); ?></td>
                                                <td><?php echo htmlspecialchars($row['max_amount']); ?></td>
                                                <td>
                                                    <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#editPlanModal<?php echo $row['id']; ?>">
                                                        Edit
                                                    </button>
                                                </td>
                                                <td>
                                                    <button type="submit" onclick="return confirm('Are you sure you want to delete this loan plan?')" name="delete" class="btn btn-danger">
                                                        Delete
                                                    </button>
                                                </td>
                                            </form>
                                        </tr>

                                        <!-- Edit Plan Modal for each row -->
                                        <div class="modal fade" id="editPlanModal<?php echo $row['id']; ?>" tabindex="-1" aria-labelledby="editPlanModalLabel<?php echo $row['id']; ?>" aria-hidden="true">
                                            <div class="modal-dialog modal-lg">
                                                <div class="modal-content">
                                                    <div class="modal-header">
                                                        <h5 class="modal-title" id="editPlanModalLabel<?php echo $row['id']; ?>">Edit Loan Plan</h5>
                                                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                    </div>
                                                    <form method="post">
                                                        <div class="modal-body">
                                                            <input type="hidden" name="id" value="<?php echo $row['id']; ?>">
                                                            
                                                            <div class="row mb-3">
                                                                <div class="col-md-6">
                                                                    <label for="name" class="form-label">Plan Name</label>
                                                                    <input type="text" class="form-control" id="name" name="name" value="<?php echo htmlspecialchars($row['name']); ?>" required>
                                                                </div>
                                                            </div>
                                                            
                                                            <div class="row mb-3">
                                                                <div class="col-md-6">
                                                                    <label for="min_deposit" class="form-label">Minimum Deposit</label>
                                                                    <input type="number" step="0.01" class="form-control" id="min_deposit" name="min_deposit" value="<?php echo htmlspecialchars($row['min_deposit']); ?>" required>
                                                                </div>
                                                                <div class="col-md-6">
                                                                    <label for="max_amount" class="form-label">Maximum Amount</label>
                                                                    <input type="number" step="0.01" class="form-control" id="max_amount" name="max_amount" value="<?php echo htmlspecialchars($row['max_amount']); ?>" required>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <div class="modal-footer">
                                                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                                            <button type="submit" name="update_plan" class="btn btn-primary">Save Changes</button>
                                                        </div>
                                                    </form>
                                                </div>
                                            </div>
                                        </div>
                                        <?php 
                                            }
                                        } else {
                                            echo "<tr><td colspan='5' class='text-center'>No loan plans found</td></tr>";
                                        }
                                        ?>
                                    </tbody>  
                                </table>
                            </div>
                        </div>
                    </div><!-- end card -->
                </div>
                <!-- end col -->
            </div>
            <!-- end col -->
        </div>
        <!-- end row -->
    </div>
</div>

<!-- Add New Plan Modal -->
<div class="modal fade" id="addPlanModal" tabindex="-1" aria-labelledby="addPlanModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addPlanModalLabel">Add New Loan Plan</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="post">
                <div class="modal-body">
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="new_name" class="form-label">Plan Name</label>
                            <input type="text" class="form-control" id="new_name" name="name" required>
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="new_min_deposit" class="form-label">Minimum Deposit</label>
                            <input type="number" step="0.01" class="form-control" id="new_min_deposit" name="min_deposit" required>
                        </div>
                        <div class="col-md-6">
                            <label for="new_max_amount" class="form-label">Maximum Amount</label>
                            <input type="number" step="0.01" class="form-control" id="new_max_amount" name="max_amount" required>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button type="submit" name="add_plan" class="btn btn-primary">Add Plan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
$(document).ready(function(){
    $('#myTable').DataTable({
        dom: 'Bfrtip',
        buttons: [
            'copy', 'csv', 'excel', 'pdf', 'print'
        ]
    });
});
</script>

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