<?php
require_once '../../config.php';
require_once '../../functions.php';

check_admin_auth();

// Fetch Endpoints
$endpoints = [];
try {
    $stmt = $pdo->query("SELECT * FROM endpoints ORDER BY id DESC");
    $endpoints = $stmt->fetchAll();
} catch (PDOException $e) {
    // Table might not exist yet
}

$pageTitle = "Endpoints - Admin Panel";
include '../includes/header.php';
?>

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

<!--app-content open-->
<div class="main-content  mt-0">
    <div class="side-app">

        <!-- CONTAINER -->
        <div class="main-container container-fluid">

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

            <!-- PAGE-HEADER -->
            <div class="page-header">
                <h1 class="page-title">Endpoints</h1>
                <div>
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a href="javascript:void(0)">Management</a></li>
                        <li class="breadcrumb-item active" aria-current="page">Endpoints</li>
                    </ol>
                </div>
            </div>
            <!-- PAGE-HEADER END -->

            <!-- ROW-1 -->
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Manage Endpoints</h3>
                            <div class="card-options">
                                <button type="button" class="btn btn-primary" data-bs-toggle="modal"
                                    data-bs-target="#addEndpointModal">
                                    <i class="fe fe-plus me-2"></i>Create Endpoint
                                </button>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-bordered border-bottom" id="responsive-datatable">
                                    <thead>
                                        <tr>
                                            <th class="wd-5p border-bottom-0">ID</th>
                                            <th class="wd-50p border-bottom-0">Data</th>
                                            <th class="wd-15p border-bottom-0">Status</th>
                                            <th class="wd-25p border-bottom-0">Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php if (empty($endpoints)): ?>
                                            <tr>
                                                <td colspan="4" class="text-center">No endpoints found.</td>
                                            </tr>
                                        <?php else: ?>
                                            <?php foreach ($endpoints as $ep): ?>
                                                <tr>
                                                    <td><?php echo $ep['id']; ?></td>
                                                    <td class="text-break"><?php echo htmlspecialchars($ep['message_data']); ?>
                                                    </td>
                                                    <td>
                                                        <?php if ($ep['status'] == 1): ?>
                                                            <span class="badge bg-success">Active</span>
                                                        <?php else: ?>
                                                            <span class="badge bg-danger">Inactive</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <button class="btn btn-sm btn-info"
                                                            onclick="editEndpoint(<?php echo $ep['id']; ?>, '<?php echo addslashes($ep['message_data']); ?>')">
                                                            <i class="fe fe-edit"></i> Edit
                                                        </button>

                                                        <button class="btn btn-sm btn-warning"
                                                            onclick="toggleStatus(<?php echo $ep['id']; ?>, <?php echo $ep['status']; ?>)">
                                                            <i class="fe fe-refresh-cw"></i>
                                                            <?php echo ($ep['status'] == 1) ? 'Deactivate' : 'Activate'; ?>
                                                        </button>

                                                        <button class="btn btn-sm btn-danger"
                                                            onclick="deleteEndpoint(<?php echo $ep['id']; ?>)">
                                                            <i class="fe fe-trash"></i> Delete
                                                        </button>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- ROW-1 END -->

        </div>
        <!-- CONTAINER END -->
    </div>
</div>
<!--app-content close-->

<!-- Add/Edit Modal -->
<div class="modal fade" id="addEndpointModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitle">Create Endpoint</h5>
                <button class="btn-close" data-bs-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="endpointForm">
                    <input type="hidden" name="action" id="formAction" value="create">
                    <input type="hidden" name="id" id="endpointId">
                    <div class="form-group">
                        <label class="form-label">Endpoint Data</label>
                        <input type="text" class="form-control" name="message_data" id="messageData" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" onclick="saveEndpoint()">Save</button>
            </div>
        </div>
    </div>
</div>

<?php
$extra_scripts = '
<script>
    function saveEndpoint() {
        var formData = $("#endpointForm").serialize();
        $.post("' . base_url('public/api/endpoint_action.php') . '", formData, function(response) {
            if(response.status === "success") {
                location.reload();
            } else {
                alert(response.message);
            }
        }, "json");
    }

    function editEndpoint(id, data) {
        $("#modalTitle").text("Edit Endpoint");
        $("#formAction").val("update");
        $("#endpointId").val(id);
        $("#messageData").val(data);
        $("#addEndpointModal").modal("show");
    }

    function toggleStatus(id, currentStatus) {
        var newStatus = (currentStatus == 1) ? 0 : 1;
        $.post("' . base_url('public/api/endpoint_action.php') . '", {action: "toggle", id: id, status: newStatus}, function(response) {
            if(response.status === "success") {
                location.reload();
            } else {
                alert(response.message);
            }
        }, "json");
    }

    function deleteEndpoint(id) {
        if(confirm("Are you sure you want to delete this endpoint?")) {
            $.post("' . base_url('public/api/endpoint_action.php') . '", {action: "delete", id: id}, function(response) {
                if(response.status === "success") {
                    location.reload();
                } else {
                    alert(response.message);
                }
            }, "json");
        }
    }
    
    // Reset modal on close
    $("#addEndpointModal").on("hidden.bs.modal", function () {
        $("#modalTitle").text("Create Endpoint");
        $("#formAction").val("create");
        $("#endpointId").val("");
        $("#messageData").val("");
    });
</script>
';
include '../includes/footer.php';
?>