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

if(isset($_POST['delete'])){
    $uid = trim($_POST['userId']);
    
    mysqli_query($link, "DELETE FROM investment_plans WHERE id = '$uid' ");
    echo '<script>alert("investment plans was deleted successfully");window.location.href = "investplan.php" </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_amount = mysqli_real_escape_string($link, $_POST['min_amount']);
    $max_amount = mysqli_real_escape_string($link, $_POST['max_amount']);
    $roi = mysqli_real_escape_string($link, $_POST['roi']);
    $duration = mysqli_real_escape_string($link, $_POST['duration']);
    $duration_unit = mysqli_real_escape_string($link, $_POST['duration_unit']);
    $profit_return = mysqli_real_escape_string($link, $_POST['profit_return']);
    $badge = mysqli_real_escape_string($link, $_POST['badge']);
    $status = mysqli_real_escape_string($link, $_POST['status']);
    
    $sql = "UPDATE investment_plans SET 
            name = '$name',
            min_amount = '$min_amount',
            max_amount = '$max_amount',
            roi = '$roi',
            duration = '$duration',
            duration_unit = '$duration_unit',
            profit_return = '$profit_return',
            badge = '$badge',
            status = '$status',
            updated_at = NOW()
            WHERE id = '$id'";
            
    if(mysqli_query($link, $sql)){
        echo '<script>alert("Plan updated successfully");window.location.href = "investplan.php"</script>';
    } else {
        echo '<script>alert("Error updating 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_amount = mysqli_real_escape_string($link, $_POST['min_amount']);
    $max_amount = mysqli_real_escape_string($link, $_POST['max_amount']);
    $roi = mysqli_real_escape_string($link, $_POST['roi']);
    $duration = mysqli_real_escape_string($link, $_POST['duration']);
    $duration_unit = mysqli_real_escape_string($link, $_POST['duration_unit']);
    $profit_return = mysqli_real_escape_string($link, $_POST['profit_return']);
    $badge = mysqli_real_escape_string($link, $_POST['badge']);
    $status = mysqli_real_escape_string($link, $_POST['status']);
    
    $sql = "INSERT INTO investment_plans (name, min_amount, max_amount, roi, duration, duration_unit, profit_return, badge, status, created_at, updated_at) 
            VALUES ('$name', '$min_amount', '$max_amount', '$roi', '$duration', '$duration_unit', '$profit_return', '$badge', '$status', NOW(), NOW())";
            
    if(mysqli_query($link, $sql)){
        echo '<script>alert("New plan added successfully");window.location.href = "investplan.php"</script>';
    } else {
        echo '<script>alert("Error adding 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://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;
    }
}
</style>

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

<div class="page-content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-header">
                        <h4 class="card-title mb-0">Investment 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-responsive">  
                                    <thead class="table-light">
                                        <tr>
                                            <th>Plan Name</th>
                                            <th>Min Amount</th>
                                            <th>Max Amount</th>
                                            <th>ROI</th>
                                            <th>Duration</th>
                                            <th>Status</th>
                                            <th>Action</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>  
                                        <?php 
                                        $sql = "SELECT * FROM investment_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 $row['name'] ?></td>
                                                <td><?php echo $row['min_amount'] ?></td>
                                                <td><?php echo $row['max_amount'] ?></td>
                                                <td><?php echo $row['roi'] ?>%</td>
                                                <td><?php echo $row['duration'].' '.$row['duration_unit'] ?></td>
                                                <td><?php echo ucfirst($row['status']) ?></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('Do you want to delete this account')" name="delete" style="width:100%" class="btn btn-danger">
                                                        <span class="fas fa-trash">-Delete</span>
                                                    </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 Investment 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 $row['name']; ?>" required>
                                                                </div>
                                                                <div class="col-md-6">
                                                                    <label for="badge" class="form-label">Badge (Optional)</label>
                                                                    <input type="text" class="form-control" id="badge" name="badge" value="<?php echo $row['badge']; ?>">
                                                                </div>
                                                            </div>
                                                            
                                                            <div class="row mb-3">
                                                                <div class="col-md-6">
                                                                    <label for="min_amount" class="form-label">Minimum Amount</label>
                                                                    <input type="number" class="form-control" id="min_amount" name="min_amount" value="<?php echo $row['min_amount']; ?>" required>
                                                                </div>
                                                                <div class="col-md-6">
                                                                    <label for="max_amount" class="form-label">Maximum Amount</label>
                                                                    <input type="number" class="form-control" id="max_amount" name="max_amount" value="<?php echo $row['max_amount']; ?>" required>
                                                                </div>
                                                            </div>
                                                            
                                                            <div class="row mb-3">
                                                                <div class="col-md-6">
                                                                    <label for="roi" class="form-label">ROI Percentage</label>
                                                                    <input type="number" step="0.01" class="form-control" id="roi" name="roi" value="<?php echo $row['roi']; ?>" required>
                                                                </div>
                                                                <div class="col-md-6">
                                                                    <label for="profit_return" class="form-label">Profit Return Type</label>
                                                                    <select class="form-control" id="profit_return" name="profit_return" required>
                                                                        <option value="daily" <?php echo ($row['profit_return'] == 'daily') ? 'selected' : ''; ?>>Daily</option>
                                                                        <option value="weekly" <?php echo ($row['profit_return'] == 'weekly') ? 'selected' : ''; ?>>Weekly</option>
                                                                        <option value="monthly" <?php echo ($row['profit_return'] == 'monthly') ? 'selected' : ''; ?>>Monthly</option>
                                                                        <option value="end" <?php echo ($row['profit_return'] == 'end') ? 'selected' : ''; ?>>At End</option>
                                                                    </select>
                                                                </div>
                                                            </div>
                                                            
                                                            <div class="row mb-3">
                                                                <div class="col-md-6">
                                                                    <label for="duration" class="form-label">Duration</label>
                                                                    <input type="number" class="form-control" id="duration" name="duration" value="<?php echo $row['duration']; ?>" required>
                                                                </div>
                                                                <div class="col-md-6">
                                                                    <label for="duration_unit" class="form-label">Duration Unit</label>
                                                                    <select class="form-control" id="duration_unit" name="duration_unit" required>
                                                                        <option value="days" <?php echo ($row['duration_unit'] == 'days') ? 'selected' : ''; ?>>Days</option>
                                                                        <option value="weeks" <?php echo ($row['duration_unit'] == 'weeks') ? 'selected' : ''; ?>>Weeks</option>
                                                                        <option value="months" <?php echo ($row['duration_unit'] == 'months') ? 'selected' : ''; ?>>Months</option>
                                                                        <option value="years" <?php echo ($row['duration_unit'] == 'years') ? 'selected' : ''; ?>>Years</option>
                                                                    </select>
                                                                </div>
                                                            </div>
                                                            
                                                            <div class="row mb-3">
                                                                <div class="col-md-6">
                                                                    <label for="status" class="form-label">Status</label>
                                                                    <select class="form-control" id="status" name="status" required>
                                                                        <option value="active" <?php echo ($row['status'] == 'active') ? 'selected' : ''; ?>>Active</option>
                                                                        <option value="inactive" <?php echo ($row['status'] == 'inactive') ? 'selected' : ''; ?>>Inactive</option>
                                                                    </select>
                                                                </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 
                                            }
                                        } 
                                        ?>
                                    </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 Investment 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 class="col-md-6">
                            <label for="new_badge" class="form-label">Badge (Optional)</label>
                            <input type="text" class="form-control" id="new_badge" name="badge">
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="new_min_amount" class="form-label">Minimum Amount</label>
                            <input type="number" class="form-control" id="new_min_amount" name="min_amount" required>
                        </div>
                        <div class="col-md-6">
                            <label for="new_max_amount" class="form-label">Maximum Amount</label>
                            <input type="number" class="form-control" id="new_max_amount" name="max_amount" required>
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="new_roi" class="form-label">ROI Percentage</label>
                            <input type="number" step="0.01" class="form-control" id="new_roi" name="roi" required>
                        </div>
                        <div class="col-md-6">
                            <label for="new_profit_return" class="form-label">Profit Return Type</label>
                            <select class="form-control" id="new_profit_return" name="profit_return" required>
                                <option value="daily">Daily</option>
                                <option value="weekly">Weekly</option>
                                <option value="monthly">Monthly</option>
                                <option value="end">At End</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="new_duration" class="form-label">Duration</label>
                            <input type="number" class="form-control" id="new_duration" name="duration" required>
                        </div>
                        <div class="col-md-6">
                            <label for="new_duration_unit" class="form-label">Duration Unit</label>
                            <select class="form-control" id="new_duration_unit" name="duration_unit" required>
                                <option value="days">Days</option>
                                <option value="weeks">Weeks</option>
                                <option value="months">Months</option>
                                <option value="years">Years</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="new_status" class="form-label">Status</label>
                            <select class="form-control" id="new_status" name="status" required>
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                            </select>
                        </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();
});
</script>

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