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

header('Content-Type: application/json');

// Check Admin Auth
if (!isset($_SESSION['admin_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

$action = $_POST['action'] ?? '';

try {
    switch ($action) {
        case 'create':
            $data = trim($_POST['message_data'] ?? '');
            if (empty($data)) {
                throw new Exception("Endpoint data is required");
            }
            $stmt = $pdo->prepare("INSERT INTO endpoints (message_data, status) VALUES (?, 1)");
            $stmt->execute([$data]);
            echo json_encode(['status' => 'success', 'message' => 'Endpoint created successfully']);
            break;

        case 'update':
            $id = $_POST['id'] ?? 0;
            $data = trim($_POST['message_data'] ?? '');
            if (empty($id) || empty($data)) {
                throw new Exception("ID and Data are required");
            }
            $stmt = $pdo->prepare("UPDATE endpoints SET message_data = ? WHERE id = ?");
            $stmt->execute([$data, $id]);
            echo json_encode(['status' => 'success', 'message' => 'Endpoint updated successfully']);
            break;

        case 'delete':
            $id = $_POST['id'] ?? 0;
            if (empty($id)) {
                throw new Exception("ID is required");
            }
            $stmt = $pdo->prepare("DELETE FROM endpoints WHERE id = ?");
            $stmt->execute([$id]);
            echo json_encode(['status' => 'success', 'message' => 'Endpoint deleted successfully']);
            break;

        case 'toggle':
            $id = $_POST['id'] ?? 0;
            $status = $_POST['status'] ?? 0; // 0 or 1
            if (empty($id)) {
                throw new Exception("ID is required");
            }
            $stmt = $pdo->prepare("UPDATE endpoints SET status = ? WHERE id = ?");
            $stmt->execute([$status, $id]);
            echo json_encode(['status' => 'success', 'message' => 'Status updated successfully']);
            break;

        default:
            throw new Exception("Invalid Action");
    }
} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>