<?php
include("conn.php");
include("header.php");

if (!isset($_SESSION['admin'])) {
    header("Location: index.php");
    exit();
}

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_POST['add_plan'])) {
        $name = mysqli_real_escape_string($conn, $_POST['name']);
        $min_amount = floatval($_POST['min_amount']);
        $max_amount = floatval($_POST['max_amount']);
        $interest_rate = floatval($_POST['interest_rate']);
        $duration_days = intval($_POST['duration_days']);

        $sql = "INSERT INTO investment_plans (name, min_amount, max_amount, interest_rate, duration_days) VALUES (?, ?, ?, ?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("sdddd", $name, $min_amount, $max_amount, $interest_rate, $duration_days);
        $stmt->execute();
        $stmt->close();
        $success = "Plan added successfully!";
    } elseif (isset($_POST['edit_plan'])) {
        $id = intval($_POST['id']);
        $name = mysqli_real_escape_string($conn, $_POST['name']);
        $min_amount = floatval($_POST['min_amount']);
        $max_amount = floatval($_POST['max_amount']);
        $interest_rate = floatval($_POST['interest_rate']);
        $duration_days = intval($_POST['duration_days']);
        $status = intval($_POST['status']);

        $sql = "UPDATE investment_plans SET name=?, min_amount=?, max_amount=?, interest_rate=?, duration_days=?, status=? WHERE id=?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("sddddii", $name, $min_amount, $max_amount, $interest_rate, $duration_days, $status, $id);
        $stmt->execute();
        $stmt->close();
        $success = "Plan updated successfully!";
    } elseif (isset($_POST['delete_plan'])) {
        $id = intval($_POST['id']);
        $conn->query("UPDATE investment_plans SET status=0 WHERE id=$id");
        $success = "Plan deactivated successfully!";
    }
}

// Get all plans
$plans = $conn->query("SELECT * FROM investment_plans ORDER BY id DESC");
?>

<div class="container-fluid">
    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h4 class="card-title">Investment Plans Management</h4>
                </div>
                <div class="card-body">
                    <?php if (isset($success)): ?>
                        <div class="alert alert-success"><?php echo $success; ?></div>
                    <?php endif; ?>

                    <button class="btn btn-primary mb-3" data-toggle="modal" data-target="#addPlanModal">
                        <i class="fa fa-plus"></i> Add New Plan
                    </button>

                    <div class="table-responsive">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Name</th>
                                    <th>Min Amount</th>
                                    <th>Max Amount</th>
                                    <th>Interest Rate (%)</th>
                                    <th>Duration (Days)</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php while ($plan = $plans->fetch_assoc()): ?>
                                    <tr>
                                        <td><?php echo $plan['id']; ?></td>
                                        <td><?php echo htmlspecialchars($plan['name']); ?></td>
                                        <td><?php echo number_format($plan['min_amount'], 2); ?></td>
                                        <td><?php echo number_format($plan['max_amount'], 2); ?></td>
                                        <td><?php echo $plan['interest_rate']; ?>%</td>
                                        <td><?php echo $plan['duration_days']; ?></td>
                                        <td>
                                            <span class="badge badge-<?php echo $plan['status'] ? 'success' : 'danger'; ?>">
                                                <?php echo $plan['status'] ? 'Active' : 'Inactive'; ?>
                                            </span>
                                        </td>
                                        <td>
                                            <button class="btn btn-sm btn-warning" onclick="editPlan(<?php echo $plan['id']; ?>)">
                                                <i class="fa fa-edit"></i>
                                            </button>
                                            <button class="btn btn-sm btn-danger" onclick="deletePlan(<?php echo $plan['id']; ?>)">
                                                <i class="fa fa-trash"></i>
                                            </button>
                                        </td>
                                    </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Add Plan Modal -->
<div class="modal fade" id="addPlanModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add New Investment Plan</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <div class="form-group">
                        <label>Plan Name</label>
                        <input type="text" name="name" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Minimum Amount</label>
                        <input type="number" step="0.01" name="min_amount" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Maximum Amount</label>
                        <input type="number" step="0.01" name="max_amount" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Daily Interest Rate (%)</label>
                        <input type="number" step="0.01" name="interest_rate" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Duration (Days)</label>
                        <input type="number" name="duration_days" class="form-control" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="submit" name="add_plan" class="btn btn-primary">Add Plan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Plan Modal -->
<div class="modal fade" id="editPlanModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Investment Plan</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="id" id="edit_plan_id">
                    <div class="form-group">
                        <label>Plan Name</label>
                        <input type="text" name="name" id="edit_name" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Minimum Amount</label>
                        <input type="number" step="0.01" name="min_amount" id="edit_min_amount" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Maximum Amount</label>
                        <input type="number" step="0.01" name="max_amount" id="edit_max_amount" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Daily Interest Rate (%)</label>
                        <input type="number" step="0.01" name="interest_rate" id="edit_interest_rate" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Duration (Days)</label>
                        <input type="number" name="duration_days" id="edit_duration_days" class="form-control" required>
                    </div>
                    <div class="form-group">
                        <label>Status</label>
                        <select name="status" id="edit_status" class="form-control">
                            <option value="1">Active</option>
                            <option value="0">Inactive</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="submit" name="edit_plan" class="btn btn-primary">Update Plan</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function editPlan(id) {
    // Fetch plan data and populate modal
    fetch('get_plan.php?id=' + id)
        .then(response => response.json())
        .then(data => {
            document.getElementById('edit_plan_id').value = data.id;
            document.getElementById('edit_name').value = data.name;
            document.getElementById('edit_min_amount').value = data.min_amount;
            document.getElementById('edit_max_amount').value = data.max_amount;
            document.getElementById('edit_interest_rate').value = data.interest_rate;
            document.getElementById('edit_duration_days').value = data.duration_days;
            document.getElementById('edit_status').value = data.status;
            $('#editPlanModal').modal('show');
        });
}

function deletePlan(id) {
    if (confirm('Are you sure you want to deactivate this plan?')) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.innerHTML = '<input type="hidden" name="id" value="' + id + '"><input type="hidden" name="delete_plan" value="1">';
        document.body.appendChild(form);
        form.submit();
    }
}
</script>

<?php include("footer.php"); ?>
