<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Web.Script.Serialization" %>
<%@ Import Namespace="System.IO" %>
<%
Response.ContentType = "application/json";
Response.AddHeader("Access-Control-Allow-Origin", "*");
Response.AddHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
Response.AddHeader("Access-Control-Allow-Headers", "Content-Type");

if (Request.HttpMethod == "OPTIONS") {
    Response.StatusCode = 200;
    return;
}

var serializer = new JavaScriptSerializer();
var result = new Dictionary<string, object>();

try {
    string requestBody;
    using (var reader = new StreamReader(Request.InputStream)) {
        requestBody = reader.ReadToEnd();
    }

    var data = serializer.Deserialize<Dictionary<string, object>>(requestBody);
    var servers = data.ContainsKey("servers") ? (ArrayList)data["servers"] : new ArrayList();
    var notes = data.ContainsKey("notes") ? data["notes"].ToString() : "";
    var createdBy = data.ContainsKey("createdBy") ? data["createdBy"].ToString() : "Dashboard";

    string connStr = "Server=YOURSERVER;Database=JBRhoylleRepository;User Id=your_service_account;Password=YOUR_PASSWORD_HERE;TrustServerCertificate=true";
    int scheduled = 0;
    var errors = new List<string>();

    using (var conn = new SqlConnection(connStr)) {
        conn.Open();
        foreach (var server in servers) {
            string serverName = server.ToString();
            try {
                using (var cmd = new SqlCommand("Patching.usp_SchedulePatch", conn)) {
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@ServerName", serverName);
                    cmd.Parameters.AddWithValue("@Notes", notes);
                    cmd.Parameters.AddWithValue("@CreatedBy", createdBy);
                    cmd.ExecuteNonQuery();
                    scheduled++;
                }
            } catch (Exception ex) {
                errors.Add(serverName + ": " + ex.Message);
            }
        }
    }

    result["success"] = errors.Count == 0;
    result["scheduled"] = scheduled;
    result["errors"] = errors;
    result["message"] = scheduled + " server(s) scheduled for patching";
    Response.StatusCode = 200;
} catch (Exception ex) {
    result["success"] = false;
    result["error"] = ex.Message;
    Response.StatusCode = 500;
}

Response.Write(serializer.Serialize(result));
%>
