<?php
require 'require/conn.php';
session_start();

// Fetch networks from the database
$network_query = "SELECT network_name FROM network WHERE status = 'On'";
$network_result = $conn->query($network_query);

// Fetch gifting status (data plans) from the database
$plan_query = "SELECT plan_name, network_name FROM data_status WHERE status = 'On'";
$plan_result = $conn->query($plan_query);

// Convert data plans to JSON for JavaScript
$data_plans = [];
while ($row = $plan_result->fetch_assoc()) {
    $data_plans[] = $row;
}
$data_plans_json = json_encode($data_plans);

// Handle form submission to add a new data plan
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_plan'])) {
    $network = $_POST['network'];
    $data_status = $_POST['data_status'];
    $data_name = $_POST['data_name'];
    $dataplan_id = $_POST['dataplan_id'];
    $user_price = $_POST['user_price'];
    $api_price = $_POST['api_price'];

    // Prepare statement to insert data securely
    $stmt = $conn->prepare("INSERT INTO data_plans (network, data_status, data_name, dataplan_id, user_price, api_price) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("ssssdd", $network, $data_status, $data_name, $dataplan_id, $user_price, $api_price);

    if ($stmt->execute()) {
        echo "<script>
            Swal.fire({
                icon: 'success',
                title: 'Success!',
                text: 'Data Plan Added Successfully!',
                timer: 2000,
                showConfirmButton: false
            });
        </script>";
    } else {
        echo "<script>
            Swal.fire({
                icon: 'error',
                title: 'Error!',
                text: 'Failed to add data plan!',
                timer: 2000,
                showConfirmButton: false
            });
        </script>";
    }
    $stmt->close();
}

// Handle deletion of a data plan
if (isset($_GET['delete_id'])) {
    $delete_id = $_GET['delete_id'];
    $stmt = $conn->prepare("DELETE FROM data_plans WHERE id = ?");
    $stmt->bind_param("i", $delete_id);

    if ($stmt->execute()) {
        echo "<script>
            Swal.fire({
                icon: 'success',
                title: 'Success!',
                text: 'Data Plan Deleted Successfully!',
                timer: 2000,
                showConfirmButton: false
            });
        </script>";
    } else {
        echo "<script>
            Swal.fire({
                icon: 'error',
                title: 'Error!',
                text: 'Failed to delete data plan!',
                timer: 2000,
                showConfirmButton: false
            });
        </script>";
    }
    $stmt->close();
}

// Fetch all data plans for display
$data_plans_query = "SELECT * FROM data_plans";
$data_plans_result = $conn->query($data_plans_query);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Add Data Plan</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        table, th, td {
            border: 1px solid black;
        }
        th, td {
            padding: 10px;
            text-align: left;
        }
        #add-form {
            display: none; /* Hide the form by default */
            margin-top: 20px;
        }
    </style>
    <script>
        // Move toggleAddForm outside of $(document).ready() to make it globally accessible
        function toggleAddForm() {
            const form = document.getElementById('add-form');
            if (form.style.display === 'none') {
                form.style.display = 'block'; // Show the form
            } else {
                form.style.display = 'none'; // Hide the form
            }
        }

        $(document).ready(function() {
            const dataPlans = <?php echo $data_plans_json; ?>;

            $('#network').change(function() {
                const selectedNetwork = $(this).val();
                const dataStatusSelect = $('#data_status');
                dataStatusSelect.empty();
                dataStatusSelect.append('<option value="">-- Select Data Plan --</option>');

                dataPlans.forEach(plan => {
                    if (plan.network_name === selectedNetwork) {
                        dataStatusSelect.append(`<option value="${plan.plan_name}">${plan.plan_name}</option>`);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <h1>Data Plans List</h1>
    <!-- Button to toggle the Add Data Plan form -->
    <button onclick="toggleAddForm()">Add New</button>

    <!-- Add Data Plan Form (hidden by default) -->
    <div id="add-form">
        <h2>Add Data Plan</h2>
        <form method="post">
            <label for="network">Select Network:</label>
            <select id="network" name="network" required>
                <option value="">-- Select Network --</option>
                <?php while ($row = $network_result->fetch_assoc()) { ?>
                    <option value="<?= htmlspecialchars($row['network_name']) ?>"><?= htmlspecialchars($row['network_name']) ?></option>
                <?php } ?>
            </select>
            <br>

            <label for="data_status">Select Data Plan:</label>
            <select id="data_status" name="data_status" required>
                <option value="">-- Select Data Plan --</option>
            </select>
            <br>

            <label for="data_name">Data Name:</label>
            <input type="text" id="data_name" name="data_name" required>
            <br>

            <label for="dataplan_id">Data Plan ID:</label>
            <input type="text" id="dataplan_id" name="dataplan_id" required>
            <br>

            <label for="user_price">User Price:</label>
            <input type="number" id="user_price" name="user_price" step="0.01" required>
            <br>

            <label for="api_price">API Price:</label>
            <input type="number" id="api_price" name="api_price" step="0.01" required>
            <br>

            <button type="submit" name="add_plan">Add Data Plan</button>
        </form>
    </div>

    <!-- Data Plans List -->
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>Network</th>
                <th>Data Status</th>
                <th>Data Name</th>
                <th>Data Plan ID</th>
                <th>User Price</th>
                <th>API Price</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php while ($row = $data_plans_result->fetch_assoc()) { ?>
                <tr>
                    <td><?= htmlspecialchars($row['id']) ?></td>
                    <td><?= htmlspecialchars($row['network']) ?></td>
                    <td><?= htmlspecialchars($row['data_status']) ?></td>
                    <td><?= htmlspecialchars($row['data_name']) ?></td>
                    <td><?= htmlspecialchars($row['dataplan_id']) ?></td>
                    <td><?= htmlspecialchars($row['user_price']) ?></td>
                    <td><?= htmlspecialchars($row['api_price']) ?></td>
                    <td>
                        <!-- Edit Button -->
                        <a href="edit_plan.php?id=<?= $row['id'] ?>">
                            <button>Edit</button>
                        </a>
                        <!-- Delete Button -->
                        <a href="?delete_id=<?= $row['id'] ?>" onclick="return confirm('Are you sure you want to delete this plan?');">
                            <button>Delete</button>
                        </a>
                    </td>
                </tr>
            <?php } ?> 
        </tbody>
    </table>
</body>
</html>