var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));

// server.ts
var import_express = __toESM(require("express"), 1);
var import_path = __toESM(require("path"), 1);
var import_fs = __toESM(require("fs"), 1);
var import_vite = require("vite");
var import_dotenv = __toESM(require("dotenv"), 1);
import_dotenv.default.config();
async function startServer() {
  const app = (0, import_express.default)();
  const PORT = Number(process.env.PORT) || 3e3;
  app.use(import_express.default.json());
  app.use(import_express.default.urlencoded({ extended: true }));
  const DATA_DIR = import_path.default.join(process.cwd(), "data");
  if (!import_fs.default.existsSync(DATA_DIR)) {
    import_fs.default.mkdirSync(DATA_DIR, { recursive: true });
  }
  const ADMISSIONS_FILE = import_path.default.join(DATA_DIR, "admissions.json");
  const MESSAGES_FILE = import_path.default.join(DATA_DIR, "messages.json");
  const NOTICES_FILE = import_path.default.join(DATA_DIR, "notices.json");
  const SETTINGS_FILE = import_path.default.join(DATA_DIR, "settings.json");
  const readData = (filePath, defaultData) => {
    try {
      if (!import_fs.default.existsSync(filePath)) {
        import_fs.default.writeFileSync(filePath, JSON.stringify(defaultData, null, 2));
        return defaultData;
      }
      const raw = import_fs.default.readFileSync(filePath, "utf-8");
      return JSON.parse(raw);
    } catch (e) {
      console.error(`Error reading ${filePath}:`, e);
      return defaultData;
    }
  };
  const writeData = (filePath, data) => {
    try {
      import_fs.default.writeFileSync(filePath, JSON.stringify(data, null, 2), "utf-8");
      return true;
    } catch (e) {
      console.error(`Error writing ${filePath}:`, e);
      return false;
    }
  };
  const defaultNotices = [
    {
      id: "notice-1",
      title: "Admissions Open for Session 2026-2027",
      date: "2026-05-18",
      category: "Admission",
      content: "Centuria School & College System announces open admissions for Pre-School, Primary, High School (Matriculation), and College (Intermediate FSc Pre-Medical, Pre-Engineering, ICS). Register online today to secure your children's future with 'A Century Ahead in Global Education'. Interviews and admissions tests schedule is available on portal registration.",
      important: true
    },
    {
      id: "notice-2",
      title: "Summer Vacation Schedule Circular 2026",
      date: "2026-05-15",
      category: "Academic",
      content: "The summer vacations for Primary and Middle School levels will commence of June 1st, 2026, and re-open on August 15th, 2026. High School classes and College classes will follow special coaching timetables starting June 15th.",
      important: false
    },
    {
      id: "notice-3",
      title: "Inauguration Board Meeting and Academic Council Setup",
      date: "2026-05-10",
      category: "Event",
      content: "We are pleased to announce the inauguration of our state-of-the-art campus. Our Academic Council, chaired by highly seasoned educational professionals, has designed a modern curriculum integrating Islamic Ethos and Global Standards.",
      important: false
    }
  ];
  const defaultSettings = {
    schoolName: process.env.SCHOOL_NAME || "Centuria School System",
    tagline: process.env.TAGLINE || "A Century Ahead in Global Education",
    contactEmail: process.env.CONTACT_EMAIL || "info@centuriaschool.edu.pk",
    contactPhone: process.env.CONTACT_PHONE || "+92 336 1012727",
    address: process.env.ADDRESS || "Main Road Kanju Swat, Pakistan",
    admissionStatus: process.env.ADMISSION_STATUS || "Open",
    principalName: process.env.PRINCIPAL_NAME || "Irfan Ali",
    ceoName: process.env.CEO_NAME || "Irfan Ali",
    // Set to Irfan Ali
    ceoMessage: process.env.CEO_MESSAGE || "Welcome to Centuria School System. Our focus is to engineer global thinkers, leaders, and scientists. Grounded in moral values, our systems deliver world-class infrastructure and a digitally connected ecosystem to empower students. We welcome you to experience elite training and education."
  };
  const defaultAdmissions = [
    {
      id: "cscs-ref-1002",
      registrationNumber: "CSCS-2026-8942",
      studentName: "Hamza Malik",
      fatherName: "Zahid Malik",
      dateOfBirth: "2015-08-12",
      gender: "Male",
      classRequested: "Class 5",
      parentPhone: "+92 312 4567890",
      parentEmail: "zahid@gmail.com",
      address: "Supply Area, Abbottabad",
      previousSchool: "Peshawar Model School",
      status: "Approved",
      submissionDate: "2026-05-15T12:30:00Z",
      reviewNotes: "Strong academic record. Admission test cleared. Fee deposit verification complete."
    },
    {
      id: "cscs-ref-1003",
      registrationNumber: "CSCS-2026-6132",
      studentName: "Ayesha Bibi",
      fatherName: "Muhammad Irfan",
      dateOfBirth: "2010-04-20",
      gender: "Female",
      classRequested: "Class 9",
      parentPhone: "+92 333 5551234",
      parentEmail: "irfan@gmail.com",
      address: "Mansehra Road, Abbottabad",
      previousSchool: "Army Public School",
      status: "Pending",
      submissionDate: "2026-05-19T08:15:00Z",
      reviewNotes: ""
    }
  ];
  const defaultMessages = [
    {
      id: "msg-1",
      name: "Sajid Khan",
      email: "sajid.khan@gmail.com",
      phone: "+92 321 9876543",
      subject: "Fee Discount Queries",
      message: "Are there any sibling tuition discount programs available? I have three children seeking admission to primary and college boards.",
      date: "2026-05-19T14:22:00Z",
      read: false
    }
  ];
  readData(NOTICES_FILE, defaultNotices);
  readData(SETTINGS_FILE, defaultSettings);
  readData(ADMISSIONS_FILE, defaultAdmissions);
  readData(MESSAGES_FILE, defaultMessages);
  app.get("/api/notices", (req, res) => {
    const list = readData(NOTICES_FILE, defaultNotices);
    res.json(list);
  });
  app.post("/api/notices", (req, res) => {
    const { title, date, category, content, important, audience, author } = req.body;
    if (!title || !content) {
      return res.status(400).json({ error: "Title and content are required." });
    }
    const list = readData(NOTICES_FILE, defaultNotices);
    const newNotice = {
      id: "notice-" + Date.now(),
      title,
      date: date || (/* @__PURE__ */ new Date()).toISOString().split("T")[0],
      category: category || "General",
      content,
      important: !!important,
      audience: audience || "All",
      author: author || "Admin"
    };
    list.unshift(newNotice);
    writeData(NOTICES_FILE, list);
    res.status(201).json({ message: "Notice added successfully", notice: newNotice });
  });
  app.post("/api/notices/delete", (req, res) => {
    const { id } = req.body;
    if (!id) return res.status(400).json({ error: "Notice ID required" });
    let list = readData(NOTICES_FILE, defaultNotices);
    list = list.filter((n) => n.id !== id);
    writeData(NOTICES_FILE, list);
    res.json({ success: true, message: "Notice deleted" });
  });
  app.get("/api/settings", (req, res) => {
    const settings = readData(SETTINGS_FILE, defaultSettings);
    res.json(settings);
  });
  app.post("/api/settings", (req, res) => {
    const info = req.body;
    const current = readData(SETTINGS_FILE, defaultSettings);
    const updated = { ...current, ...info };
    writeData(SETTINGS_FILE, updated);
    res.json({ message: "Settings updated successfully", settings: updated });
  });
  app.get("/api/admissions", (req, res) => {
    const list = readData(ADMISSIONS_FILE, defaultAdmissions);
    res.json(list);
  });
  app.post("/api/admissions/apply", (req, res) => {
    const {
      studentName,
      fatherName,
      dateOfBirth,
      gender,
      classRequested,
      parentPhone,
      parentEmail,
      address,
      previousSchool
    } = req.body;
    if (!studentName || !fatherName || !classRequested || !parentPhone) {
      return res.status(400).json({ error: "Missing required student details." });
    }
    const regNum = "CSCS-2026-" + Math.floor(1e3 + Math.random() * 9e3);
    const list = readData(ADMISSIONS_FILE, defaultAdmissions);
    const newApp = {
      id: "cscs-ref-" + Date.now(),
      registrationNumber: regNum,
      studentName,
      fatherName,
      dateOfBirth: dateOfBirth || "",
      gender: gender || "Not Specified",
      classRequested,
      parentPhone,
      parentEmail: parentEmail || "",
      address: address || "",
      previousSchool: previousSchool || "None",
      status: "Pending",
      submissionDate: (/* @__PURE__ */ new Date()).toISOString(),
      reviewNotes: ""
    };
    list.unshift(newApp);
    writeData(ADMISSIONS_FILE, list);
    if (previousSchool === "Centuria Virtual AI Assistant" || fatherName.includes("ChatBot")) {
      try {
        const messagesList = readData(MESSAGES_FILE, defaultMessages);
        const chatLeadMessage = {
          id: "msg-lead-" + Date.now(),
          name: studentName,
          email: parentEmail || "chatbot-lead@centuria.edu.pk",
          phone: parentPhone,
          subject: `[ChatBot Lead] Callback - ${classRequested}`,
          message: address || "Requested call back regarding admissions and fee streams.",
          date: (/* @__PURE__ */ new Date()).toISOString(),
          read: false
        };
        messagesList.unshift(chatLeadMessage);
        writeData(MESSAGES_FILE, messagesList);
      } catch (err) {
        console.error("[LEAD REPLICATION ERROR]", err);
      }
    }
    res.status(201).json({
      message: "Application submitted successfully",
      registrationNumber: regNum,
      application: newApp
    });
  });
  app.get("/api/admissions/track/:regNum", (req, res) => {
    const { regNum } = req.params;
    const list = readData(ADMISSIONS_FILE, defaultAdmissions);
    const matched = list.find(
      (app2) => app2.registrationNumber.toLowerCase() === regNum.trim().toLowerCase()
    );
    if (!matched || matched.previousSchool === "Centuria Virtual AI Assistant" || matched.fatherName.includes("ChatBot")) {
      return res.status(404).json({ error: "Registration number not found." });
    }
    res.json(matched);
  });
  app.post("/api/admissions/update-status", (req, res) => {
    const { id, status, reviewNotes } = req.body;
    if (!id || !status) {
      return res.status(400).json({ error: "ID and Status are required." });
    }
    const list = readData(ADMISSIONS_FILE, defaultAdmissions);
    const matchedIndex = list.findIndex((app2) => app2.id === id);
    if (matchedIndex === -1) {
      return res.status(404).json({ error: "Application not found." });
    }
    list[matchedIndex].status = status;
    if (reviewNotes !== void 0) {
      list[matchedIndex].reviewNotes = reviewNotes;
    }
    writeData(ADMISSIONS_FILE, list);
    res.json({ message: "Status updated", application: list[matchedIndex] });
  });
  app.post("/api/admissions/delete", (req, res) => {
    const { id } = req.body;
    if (!id) {
      return res.status(400).json({ error: "ID is required." });
    }
    const list = readData(ADMISSIONS_FILE, defaultAdmissions);
    const filtered = list.filter((app2) => app2.id !== id);
    writeData(ADMISSIONS_FILE, filtered);
    res.json({ message: "Admission request deleted successfully", id });
  });
  app.get("/api/messages", (req, res) => {
    const list = readData(MESSAGES_FILE, defaultMessages);
    res.json(list);
  });
  app.post("/api/messages/submit", (req, res) => {
    const { name, email, phone, subject, message } = req.body;
    if (!name || !message || !email && !phone) {
      return res.status(400).json({ error: "Name, Message and Contact Info (Email or Phone) are required." });
    }
    const list = readData(MESSAGES_FILE, defaultMessages);
    const newMsg = {
      id: "msg-" + Date.now(),
      name,
      email: email || "",
      phone: phone || "",
      subject: subject || "General Contact Enquiry",
      message,
      date: (/* @__PURE__ */ new Date()).toISOString(),
      read: false
    };
    list.unshift(newMsg);
    writeData(MESSAGES_FILE, list);
    res.status(201).json({ message: "Inquiry received. Thank you!", inquiry: newMsg });
  });
  app.post("/api/messages/mark-read", (req, res) => {
    const { id } = req.body;
    if (!id) return res.status(400).json({ error: "Message ID required" });
    const list = readData(MESSAGES_FILE, defaultMessages);
    const item = list.find((m) => m.id === id);
    if (item) {
      item.read = true;
      writeData(MESSAGES_FILE, list);
    }
    res.json({ success: true, message: "Marked message as read" });
  });
  app.post("/api/chat", async (req, res) => {
    const { message, history } = req.body;
    if (!message) {
      return res.status(400).json({ error: "Message is required." });
    }
    const GEMINI_API_KEY = process.env.GEMINI_API_KEY;
    const hasValidKey = GEMINI_API_KEY && GEMINI_API_KEY !== "MY_GEMINI_API_KEY" && GEMINI_API_KEY.trim() !== "";
    if (hasValidKey) {
      try {
        const systemPrompt = `You are "Centuria Bot", the official elite virtual assistant for Centuria School & College System, Swat Campus, Pakistan.
Motto: "A Century Ahead in Global Education".
CEO & Principal: Irfan Ali.
Campus Location: Main Road Kanju Swat, Khyber Pakhtunkhwa, Pakistan. Contact: +92 336 1012727, info@centuriaschool.edu.pk.
Admissions: Currently OPEN for Montessori, Pre-School, Primary, High School (Matriculation Science), and College (FSc Pre-Medical, Pre-Engineering, ICS).
Infrastructure: Digital classrooms, advanced labs, library, modern sports fields, boys/girls separate blocks.
Portal/LMS: Under "Student Portal" or "Portal Logins" tab. Credentials for testing: Admin (username: admin, password: admin1010), Student (username: CS-2026-101, password: student123), Teacher (username: TR-2026-01, password: teacher123).

Guidelines:
1. Be professional, warm, encouraging, and supportive. Use "Assalam-o-Alaikum" where appropriate.
2. Keep responses brief (under 3-4 sentences) and highly structured.
3. Suggest interactive actions. Offer to help them register, track admissions, or contact support.
4. If they ask about admission fees, tell them FSc and Matric levels have competitive structures, and recommend submitting a callback query.`;
        const contents = [];
        if (history && Array.isArray(history)) {
          history.forEach((h) => {
            contents.push({
              role: h.sender === "user" ? "user" : "model",
              parts: [{ text: h.text }]
            });
          });
        }
        contents.push({
          role: "user",
          parts: [{ text: message }]
        });
        const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${GEMINI_API_KEY}`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            contents,
            systemInstruction: {
              parts: [{ text: systemPrompt }]
            },
            generationConfig: {
              temperature: 0.7,
              maxOutputTokens: 350
            }
          })
        });
        if (response.ok) {
          const data = await response.json();
          const replyText2 = data.candidates?.[0]?.content?.parts?.[0]?.text || "I am here to assist you with admissions, portal logins, and school info. Please let me know how I can help!";
          return res.json({ text: replyText2, isAi: true });
        } else {
          console.warn("[GEMINI API] Failed request:", response.statusText);
        }
      } catch (err) {
        console.error("[GEMINI CHAT ERROR]", err);
      }
    }
    const txt = message.toLowerCase().trim();
    let replyText = "";
    let actions = [];
    if (txt.includes("admission") || txt.includes("apply") || txt.includes("register") || txt.includes("join")) {
      replyText = "Admissions are currently OPEN at Centuria Swat Campus! You can apply online by completing the digital admission form on our Portal, or download the brochure. Would you like to launch the Admissions Form directly or submit a callback request?";
      actions = [
        { type: "link", label: "Apply Online Now", action: "admissions" },
        { type: "message", label: "Request Callback", action: "I want to request a callback for admissions" }
      ];
    } else if (txt.includes("fee") || txt.includes("cost") || txt.includes("tuition") || txt.includes("payment")) {
      replyText = "Centuria offers highly competitive, value-focused fee plans across Montessori, Primary, Matriculation, and Intermediate College boards. We also offer sibling discounts and academic merit scholarships. Would you like to view detailed academics or talk to our admissions officer?";
      actions = [
        { type: "link", label: "View Curriculums", action: "academics" },
        { type: "message", label: "Inquire About Scholarships", action: "What are the scholarship criteria?" }
      ];
    } else if (txt.includes("timing") || txt.includes("hour") || txt.includes("schedule") || txt.includes("days")) {
      replyText = "Our regular academic timings are:\n\u2022 Pre-School & Primary: 08:00 AM - 01:30 PM (Mon-Fri)\n\u2022 High School & College: 08:00 AM - 02:00 PM (Mon-Fri)\n\u2022 Admin Office Hours: 08:00 AM - 03:00 PM (Mon-Sat)";
      actions = [
        { type: "link", label: "View Contact Page", action: "contact" }
      ];
    } else if (txt.includes("lms") || txt.includes("portal") || txt.includes("login") || txt.includes("student portal")) {
      replyText = "The Centuria LMS Digital Portal empowers students, parents, and teachers to access schedules, track attendance, download assignments, and view grades. For testing:\n\u2022 Student Portal: CS-2026-101 / student123\n\u2022 Teacher Portal: TR-2026-01 / teacher123\n\u2022 Admin Portal: admin / admin1010";
      actions = [
        { type: "link", label: "Go to Portal Page", action: "portal" }
      ];
    } else if (txt.includes("contact") || txt.includes("phone") || txt.includes("email") || txt.includes("call") || txt.includes("address") || txt.includes("location")) {
      replyText = "The Centuria Swat Campus is located at:\n\u{1F4CD} Main Road Kanju Swat, Khyber Pakhtunkhwa, Pakistan.\n\u2022 Phone: +92 336 1012727\n\u2022 Email: info@centuriaschool.edu.pk\n\nYou can also submit an inquiry directly through our website contact form!";
      actions = [
        { type: "link", label: "Open Contact Form", action: "contact" }
      ];
    } else if (txt.includes("scholarship") || txt.includes("discount") || txt.includes("concession")) {
      replyText = "Yes! Centuria Swat Campus provides extensive financial aid:\n1. Academic Merit Scholarships (up to 100% tuition coverage for top board performers).\n2. Co-curricular Talent Concessions.\n3. Sibling Discounts (15% off for second child, 25% off for third child).\n4. Need-based concessions upon application review.";
      actions = [
        { type: "message", label: "Request Fee Roster", action: "Please send me the scholarship application details" }
      ];
    } else if (txt.includes("callback") || txt.includes("call back") || txt.includes("talk to") || txt.includes("registrar") || txt.includes("representative")) {
      replyText = "I would be happy to schedule a callback for you! Please provide your name, phone number, and query, and our admissions coordinator will call you back within 24 hours. Alternatively, click 'Book Callback' to launch the callback form.";
      actions = [
        { type: "form", label: "Book Callback Form", action: "callback_form" }
      ];
    } else if (txt.includes("hello") || txt.includes("hi") || txt.includes("salam") || txt.includes("hey")) {
      replyText = "Assalam-o-Alaikum! Welcome to Centuria School & College System Swat Campus. \u{1F393} I am your virtual school assistant. You can ask me about admissions, fees, LMS login details, or campus facilities. How can I help you today?";
    } else {
      replyText = "Thank you for reaching out to Centuria Swat Campus! I can assist you with enrollment requirements, fee catalogs, class timings, contact channels, or LMS logins. Please try selecting one of the quick options or specify your request.";
    }
    res.json({ text: replyText, isAi: false, actions });
  });
  app.post("/api/chat/feedback", (req, res) => {
    const { messageText, isHelpful } = req.body;
    console.log(`[CHAT FEEDBACK] Msg: "${messageText}" | Helpful: ${isHelpful ? "YES \u{1F44D}" : "NO \u{1F44E}"}`);
    res.json({ success: true, message: "Feedback recorded" });
  });
  app.get("/input_file_0.png", (req, res) => {
    const filePath = import_path.default.join(process.cwd(), "input_file_0.png");
    if (import_fs.default.existsSync(filePath)) {
      res.sendFile(filePath);
    } else {
      res.status(404).send("File not found");
    }
  });
  app.get("/input_file_1.png", (req, res) => {
    const filePath = import_path.default.join(process.cwd(), "input_file_1.png");
    if (import_fs.default.existsSync(filePath)) {
      res.sendFile(filePath);
    } else {
      res.status(404).send("File not found");
    }
  });
  app.get("/input_file_2.png", (req, res) => {
    const filePath = import_path.default.join(process.cwd(), "input_file_2.png");
    if (import_fs.default.existsSync(filePath)) {
      res.sendFile(filePath);
    } else {
      res.status(404).send("File not found");
    }
  });
  app.get("/input_file_3.png", (req, res) => {
    const filePath = import_path.default.join(process.cwd(), "input_file_3.png");
    if (import_fs.default.existsSync(filePath)) {
      res.sendFile(filePath);
    } else {
      res.status(404).send("File not found");
    }
  });
  const isDev = process.env.NODE_ENV !== "production" && !(process.argv[1] && (process.argv[1].endsWith("server.cjs") || process.argv[1].includes("dist")));
  if (isDev) {
    const vite = await (0, import_vite.createServer)({
      server: {
        middlewareMode: true,
        watch: {
          ignored: ["**/data/**"]
        }
      },
      appType: "spa"
    });
    app.use(vite.middlewares);
  } else {
    const distPath = import_path.default.join(process.cwd(), "dist");
    app.use(import_express.default.static(distPath));
    app.get("*", (req, res) => {
      res.sendFile(import_path.default.join(distPath, "index.html"));
    });
  }
  app.listen(PORT, "0.0.0.0", () => {
    console.log(`[CSCS BACKEND] Server listening on http://0.0.0.0:${PORT}`);
  });
}
startServer();
//# sourceMappingURL=server.cjs.map
