// import { Op } from "sequelize";
// import { Hosting } from "../models/index.js";
// import { addDays, todayOnly } from "../utils/dateHelpers.js";
// import transporter from "../config/mail.js";
// import { buildHostingRenewalMailHtml } from "../templates/mailTemplates.js";
// import sanitizeHtml from "sanitize-html";

// // ======================
// // ALLOWED VALUES
// // ======================

// const allowedStatuses = [
//     "active",
//     "expiring",
//     "suspended",
//     "expired",
//     "pending"
// ];

// const allowedBillingCycles = [
//     "monthly",
//     "quarterly",
//     "half_yearly",
//     "yearly"
// ];

// // HELPERS
// // ======================

// // string => boolean
// const parseBoolean = (value) => {
//     if (value === true || value === "true" || value === 1 || value === "1") {
//         return true;
//     }

//     return false;
// };




// // const buildHostingRenewalMailHtml = (hosting) => {
// //     const daysLeft = getDaysLeft(hosting.renewal_date);
// //     const renewalText = daysLeft < 0
// //         ? "has expired"
// //         : `will renew in <strong style="color:#4f46e5;">${daysLeft} day${daysLeft === 1 ? "" : "s"}</strong>`;

// //     return `
// //         <div style="background:#f8fafc;padding:28px 14px;font-family:Segoe UI,Arial,sans-serif;color:#0f172a;">
// //             <div style="max-width:620px;margin:0 auto;background:#ffffff;border:1px solid #e2e8f0;border-radius:16px;overflow:hidden;">
// //                 <div style="background:#111827;color:#ffffff;padding:26px 30px;">
// //                     <h1 style="margin:0;font-size:22px;">Hosting Renewal Reminder</h1>
// //                     <p style="margin:8px 0 0;color:#cbd5e1;font-size:14px;">Deytal Technologies Pvt Ltd</p>
// //                 </div>
// //                 <div style="padding:30px;">
// //                     <p style="font-size:15px;line-height:1.7;color:#475569;margin:0 0 22px;">
// //                         Hi ${escapeHtml(hosting.client_name)}, your hosting for
// //                         <strong style="color:#4f46e5;">${escapeHtml(hosting.domain_name)}</strong>
// //                         ${renewalText}. Please renew it before the renewal date to avoid service interruption.
// //                     </p>
// //                     <table style="width:100%;border-collapse:collapse;border:1px solid #e2e8f0;border-radius:10px;overflow:hidden;">
// //                         <tbody>
// //                             <tr>
// //                                 <td style="padding:14px;border-bottom:1px solid #e2e8f0;font-weight:700;color:#334155;">Domain</td>
// //                                 <td style="padding:14px;border-bottom:1px solid #e2e8f0;color:#4f46e5;font-weight:700;">${escapeHtml(hosting.domain_name)}</td>
// //                             </tr>
// //                             <tr>
// //                                 <td style="padding:14px;border-bottom:1px solid #e2e8f0;font-weight:700;color:#334155;">Renewal Date</td>
// //                                 <td style="padding:14px;border-bottom:1px solid #e2e8f0;color:#475569;">${escapeHtml(hosting.renewal_date)}</td>
// //                             </tr>
// //                             <tr>
// //                                 <td style="padding:14px;border-bottom:1px solid #e2e8f0;font-weight:700;color:#334155;">Cost</td>
// //                                 <td style="padding:14px;border-bottom:1px solid #e2e8f0;color:#475569;">INR ${Number(hosting.cost || 0).toFixed(2)}</td>
// //                             </tr>
// //                             <tr>
// //                                 <td style="padding:14px;font-weight:700;color:#334155;">Status</td>
// //                                 <td style="padding:14px;color:#475569;text-transform:capitalize;">${escapeHtml(getComputedStatus(hosting))}</td>
// //                             </tr>
// //                         </tbody>
// //                     </table>
// //                     <p style="font-size:13px;color:#64748b;margin:24px 0 0;">Need help? Contact support@deytal.io.</p>
// //                 </div>
// //             </div>
// //         </div>
// //     `;
// // };





// // monthly cost calculate


// // const buildHostingRenewalMailHtml = (hosting, customMessageHtml = null) => {
// //     const daysLeft = getDaysLeft(hosting.renewal_date);
// //     const renewalText = daysLeft < 0
// //         ? "has expired"
// //         : `will renew in <strong style="color:#4f46e5;">${daysLeft} day${daysLeft === 1 ? "" : "s"}</strong>`;

// //     const defaultMessage = `
// //         Hi ${escapeHtml(hosting.client_name)}, your hosting for
// //         <strong style="color:#4f46e5;">${escapeHtml(hosting.domain_name)}</strong>
// //         ${renewalText}. Please renew it before the renewal date to avoid service interruption.
// //     `;

// //     const messageHtml = customMessageHtml ?? defaultMessage;

// //     return `
// //         <div style="background:#f8fafc;padding:28px 14px;font-family:Segoe UI,Arial,sans-serif;color:#0f172a;">
// //             <div style="max-width:620px;margin:0 auto;background:#ffffff;border:1px solid #e2e8f0;border-radius:16px;overflow:hidden;">
// //                 <div style="background:#111827;color:#ffffff;padding:26px 30px;">
// //                     <h1 style="margin:0;font-size:22px;">Hosting Renewal Reminder</h1>
// //                     <p style="margin:8px 0 0;color:#cbd5e1;font-size:14px;">Deytal Technologies Pvt Ltd</p>
// //                 </div>
// //                 <div style="padding:30px;">
// //                     <p style="font-size:15px;line-height:1.7;color:#475569;margin:0 0 22px;">
// //                         ${messageHtml}
// //                     </p>
// //                     <table style="width:100%;border-collapse:collapse;border:1px solid #e2e8f0;border-radius:10px;overflow:hidden;">
// //                         <tbody>
// //                             <tr>
// //                                 <td style="padding:14px;border-bottom:1px solid #e2e8f0;font-weight:700;color:#334155;">Domain</td>
// //                                 <td style="padding:14px;border-bottom:1px solid #e2e8f0;color:#4f46e5;font-weight:700;">${escapeHtml(hosting.domain_name)}</td>
// //                             </tr>
// //                             <tr>
// //                                 <td style="padding:14px;border-bottom:1px solid #e2e8f0;font-weight:700;color:#334155;">Renewal Date</td>
// //                                 <td style="padding:14px;border-bottom:1px solid #e2e8f0;color:#475569;">${escapeHtml(hosting.renewal_date)}</td>
// //                             </tr>
// //                             <tr>
// //                                 <td style="padding:14px;border-bottom:1px solid #e2e8f0;font-weight:700;color:#334155;">Cost</td>
// //                                 <td style="padding:14px;border-bottom:1px solid #e2e8f0;color:#475569;">INR ${Number(hosting.cost || 0).toFixed(2)}</td>
// //                             </tr>
// //                             <tr>
// //                                 <td style="padding:14px;font-weight:700;color:#334155;">Status</td>
// //                                 <td style="padding:14px;color:#475569;text-transform:capitalize;">${escapeHtml(getComputedStatus(hosting))}</td>
// //                             </tr>
// //                         </tbody>
// //                     </table>
// //                     <p style="font-size:13px;color:#64748b;margin:24px 0 0;">Need help? Contact support@deytal.io.</p>
// //                 </div>
// //             </div>
// //         </div>
// //     `;
// // };

// const getMonthlyCost = (hosting) => {

//     const cost = Number(hosting.cost);

//     if (hosting.billing_cycle === "monthly") {
//         return cost;
//     }

//     if (hosting.billing_cycle === "quarterly") {
//         return cost / 3;
//     }

//     if (hosting.billing_cycle === "half_yearly") {
//         return cost / 6;
//     }

//     if (hosting.billing_cycle === "yearly") {
//         return cost / 12;
//     }

//     return cost;
// };



// // final response format
// const formatHosting = (hosting) => {

//     const data = hosting.get
//         ? hosting.get({ plain: true })
//         : hosting;

//     return {
//         ...data,

//         hosting: data.domain_name,

//         cost: Number(data.cost),

//         monthly_cost: Number(
//             getMonthlyCost(data).toFixed(2)
//         ),

//         days_left: getDaysLeft(data.renewal_date),

//         computed_status: getComputedStatus(data)
//     };
// };


// // common error handler
// const handleError = (res, error) => {

//     console.log(error);

//     // duplicate
//     if (error.name === "SequelizeUniqueConstraintError") {

//         return res.status(409).json({
//             success: false,
//             message: "Hosting domain already exists"
//         });
//     }

//     // validation
//     if (error.name === "SequelizeValidationError") {

//         return res.status(400).json({
//             success: false,
//             message: error.errors[0].message
//         });
//     }

//     // server error
//     return res.status(500).json({
//         success: false,
//         message: "Internal server error"
//     });
// };

// // CREATE HOSTING

// export const createHosting = async (req, res) => {
//     try {
//         const {
//             client_name,
//             client_email,
//             domain_name,
//             cost,
//             start_date,
//             renewal_date,
//             status,
//             auto_renew,
//         } = req.body;
//         // required fields
//         if (
//             !client_name ||
//             !client_email ||
//             !domain_name ||
//             !cost ||
//             !renewal_date
//         ) {
//             return res.status(400).json({
//                 success: false,
//             message: "Required fields missing"
//             });
//         }
//         // duplicate check
//         const existingHosting = await Hosting.findOne({
//             where: {
//                 domain_name: domain_name.toLowerCase().trim()
//             }
//         });
//         if (existingHosting) {
//             return res.status(409).json({
//                 success: false,
//                 message: "Hosting domain already exists"
//             });
//         }
//         // create
//         const hosting = await Hosting.create({
//             client_name,
//             client_email,
//             domain_name: domain_name.toLowerCase().trim(),
//             cost,
//             start_date,
//             renewal_date,
//             status: status || "active",
//             auto_renew: parseBoolean(auto_renew)
//         });
//         return res.status(201).json({
//             success: true,
//             message: "Hosting created successfully",
//             hosting: formatHosting(hosting)
//         });

//     } catch (error) {
//         return handleError(res, error);
//     }
// };
// // GET ALL HOSTINGS
// // ======================

// export const getHostings = async (req, res) => {

//     try {
//         const {
//             search,
//             status,
//             billing_cycle
//         } = req.query;
//         let where = {};
//         // status filter
//         if (status && status !== "all") {
//             where.status = status;
//         }

//         // billing filter
//         if (billing_cycle) {
//             where.billing_cycle = billing_cycle;
//         }

//         // search
//         if (search) {

//             where[Op.or] = [

//                 {
//                     client_name: {
//                         [Op.like]: `%${search}%`
//                     }
//                 },

//                 {
//                     domain_name: {
//                         [Op.like]: `%${search}%`
//                     }
//                 }
//             ];
//         }


//         const hostings = await Hosting.findAll({
//             where,
//             order: [["renewal_date", "ASC"]]
//         });


//         return res.status(200).json({
//             success: true,
//             total: hostings.length,
//             hostings: hostings.map(formatHosting)
//         });

//     } catch (error) {

//         return handleError(res, error);
//     }
// };

// // ======================
// // GET SINGLE HOSTING
// // ======================

// export const getHostingById = async (req, res) => {

//     try {

//         const { id } = req.params;

//         const hosting = await Hosting.findByPk(id);

//         if (!hosting) {

//             return res.status(404).json({
//                 success: false,
//                 message: "Hosting not found"
//             });
//         }


//         return res.status(200).json({
//             success: true,
//             hosting: formatHosting(hosting)
//         });

//     } catch (error) {

//         return handleError(res, error);
//     }
// };

// // ======================
// // UPDATE HOSTING
// // ======================

// export const updateHosting = async (req, res) => {

//     try {

//         const { id } = req.params;

//         // find hosting
//         const hosting = await Hosting.findByPk(id);

//         if (!hosting) {

//             return res.status(404).json({
//                 success: false,
//                 message: "Hosting not found"
//             });
//         }


//         const {
//             domain_name,
//             status,
//             billing_cycle,
//             auto_renew
//         } = req.body;


//         // ======================
//         // STATUS VALIDATION
//         // ======================

//         if (
//             status &&
//             !allowedStatuses.includes(status)
//         ) {

//             return res.status(400).json({
//                 success: false,
//                 message: `Status must be one of: ${allowedStatuses.join(", ")}`
//             });
//         }


//         // ======================
//         // BILLING VALIDATION
//         // ======================

//         if (
//             billing_cycle &&
//             !allowedBillingCycles.includes(billing_cycle)
//         ) {

//             return res.status(400).json({
//                 success: false,
//                 message: `Billing cycle must be one of: ${allowedBillingCycles.join(", ")}`
//             });
//         }


//         // ======================
//         // DUPLICATE DOMAIN CHECK
//         // ======================

//         // only check if user changing domain
//         if (
//             domain_name &&
//             domain_name.trim().toLowerCase() !== hosting.domain_name
//         ) {

//             const existingHosting = await Hosting.findOne({

//                 where: {

//                     domain_name: domain_name.trim().toLowerCase(),

//                     // current id ignore
//                     id: {
//                         [Op.ne]: id
//                     }
//                 }
//             });


//             // if domain already exists
//             if (existingHosting) {

//                 return res.status(409).json({
//                     success: false,
//                     message: "Hosting domain already exists"
//                 });
//             }
//         }


//         // ======================
//         // UPDATE DATA
//         // ======================

//         await hosting.update({

//             ...req.body,

//             // keep old domain if not provided
//             domain_name: domain_name
//                 ? domain_name.trim().toLowerCase()
//                 : hosting.domain_name,

//             // boolean parse
//             auto_renew:
//                 auto_renew !== undefined
//                     ? parseBoolean(auto_renew)
//                     : hosting.auto_renew,

//             updated_at: new Date()
//         });


//         return res.status(200).json({

//             success: true,

//             message: "Hosting updated successfully",

//             hosting: formatHosting(hosting)
//         });

//     } catch (error) {

//         return handleError(res, error);
//     }
// };

// // ======================
// // DELETE HOSTING
// // ======================

// export const deleteHosting = async (req, res) => {

//     try {

//         const { id } = req.params;

//         const hosting = await Hosting.findByPk(id);

//         if (!hosting) {

//             return res.status(404).json({
//                 success: false,
//                 message: "Hosting not found"
//             });
//         }


//         await hosting.destroy();


//         return res.status(200).json({
//             success: true,
//             message: "Hosting deleted successfully"
//         });

//     } catch (error) {

//         return handleError(res, error);
//     }
// };

// export const sendRenewalAlertEmailToUser = async (req, res) => {
//     try {
//         const { id } = req.params;
//         const { customMessageHtml } = req.body; 
//         const hosting = await Hosting.findByPk(id);

//         if (!hosting) {
//             return res.status(404).json({
//                 success: false,
//                 message: "Hosting not found"
//             });
//         }

//         const recipient = (hosting.client_email || hosting.email || '').trim().toLowerCase();

//         if (!recipient) {
//             return res.status(400).json({
//                 success: false,
//                 message: "No email address found for this hosting"
//             });
//         }

//         await transporter.sendMail({
//             from: process.env.EMAIL_USER,
//             to: recipient,
//             subject: `Hosting renewal reminder: ${hosting.domain_name} ${getDaysLeft(hosting.renewal_date) < 0 ? 'has expired' : `renews in ${getDaysLeft(hosting.renewal_date)} day${getDaysLeft(hosting.renewal_date) === 1 ? '' : 's'}`}`,
//             html: buildHostingRenewalMailHtml(hosting)
//         });

//         await hosting.update({
//             reminder_sent_at: new Date(),
//             reminder_for_renewal: hosting.renewal_date
//         });

//         return res.status(200).json({
//             success: true,
//             message: "Hosting renewal email sent to user",
//             recipient
//         });
//     } catch (error) {
//         return handleError(res, error);
//     }
// };

// // ======================
// // RENEW HOSTING
// // ======================

// export const renewHosting = async (req, res) => {

//     try {

//         const { id } = req.params;

//         const { renewal_date } = req.body;

//         const hosting = await Hosting.findByPk(id);

//         if (!hosting) {

//             return res.status(404).json({
//                 success: false,
//                 message: "Hosting not found"
//             });
//         }


//         if (!renewal_date) {

//             return res.status(400).json({
//                 success: false,
//                 message: "Renewal date required"
//             });
//         }


//         await hosting.update({

//             renewal_date,

//             status: "active",

//             last_renewed_at: todayOnly(),

//             updated_at: new Date()
//         });


//         return res.status(200).json({
//             success: true,
//             message: "Hosting renewed successfully",
//             hosting: formatHosting(hosting)
//         });

//     } catch (error) {

//         return handleError(res, error);
//     }
// };

// // ======================
// // TOGGLE AUTO RENEW
// // ======================

// export const toggleAutoRenew = async (req, res) => {

//     try {

//         const { id } = req.params;

//         const hosting = await Hosting.findByPk(id);

//         if (!hosting) {

//             return res.status(404).json({
//                 success: false,
//                 message: "Hosting not found"
//             });
//         }


//         await hosting.update({

//             auto_renew: !hosting.auto_renew,

//             updated_at: new Date()
//         });


//         return res.status(200).json({
//             success: true,
//             message: "Auto renew updated successfully",
//             hosting: formatHosting(hosting)
//         });

//     } catch (error) {

//         return handleError(res, error);
//     }
// };

// // ======================
// // UPDATE HOSTING STATUS
// // ======================

// export const updateHostingStatus = async (req, res) => {

//     try {

//         const { id } = req.params;

//         const { status } = req.body;

//         const hosting = await Hosting.findByPk(id);

//         if (!hosting) {

//             return res.status(404).json({
//                 success: false,
//                 message: "Hosting not found"
//             });
//         }


//         if (!status || !allowedStatuses.includes(status)) {

//             return res.status(400).json({
//                 success: false,
//                 message: `Status must be one of: ${allowedStatuses.join(", ")}`
//             });
//         }


//         await hosting.update({

//             status,

//             updated_at: new Date()
//         });


//         return res.status(200).json({
//             success: true,
//             message: "Hosting status updated successfully",
//             hosting: formatHosting(hosting)
//         });

//     } catch (error) {

//         return handleError(res, error);
//     }
// };

// // ======================
// // HOSTING STATS
// // ======================

// export const getHostingStats = async (req, res) => {

//     try {

//         const today = todayOnly();

//         const next30Days = addDays(today, 30);


//         // counts
//         const totalHostingPlans = await Hosting.count();

//         const activeHostingPlans = await Hosting.count({
//             where: {
//                 status: "active"
//             }
//         });

//         const suspendedServices = await Hosting.count({
//             where: {
//                 status: "suspended"
//             }
//         });

//         const expiringServers = await Hosting.count({

//             where: {

//                 renewal_date: {
//                     [Op.between]: [today, next30Days]
//                 },

//                 status: {
//                     [Op.ne]: "suspended"
//                 }
//             }
//         });


//         // all hostings
//         const hostings = await Hosting.findAll();


//         // monthly cost
//         let monthlyHostingCost = 0;

//         hostings.forEach((hosting) => {

//             if (hosting.status !== "suspended") {

//                 monthlyHostingCost += getMonthlyCost(hosting);
//             }
//         });


//         return res.status(200).json({

//             success: true,

//             stats: {

//                 totalHostingPlans,

//                 activeHostingPlans,

//                 expiringServers,

//                 suspendedServices,

//                 monthlyHostingCost: Number(
//                     monthlyHostingCost.toFixed(2)
//                 ),

//                 averageMonthlyCost:
//                     activeHostingPlans > 0
//                         ? Number(
//                             (
//                                 monthlyHostingCost /
//                                 activeHostingPlans
//                             ).toFixed(2)
//                         )
//                         : 0
//             }
//         });

//     } catch (error) {

//         return handleError(res, error);
//     }
// };

// // ======================
// // RENEWAL REMINDERS
// // ======================

// export const getRenewalReminders = async (req, res) => {

//     try {
//         const days = Number(req.query.days || 30);
//         const today = todayOnly();
//         const endDate = addDays(today, days);
//         const hostings = await Hosting.findAll({
//             where: {
//                 renewal_date: {
//                     [Op.between]: [today, endDate]
//                 },
//                 status: {
//                     [Op.ne]: "suspended"
//                 }
//             },
//             order: [["renewal_date", "ASC"]]
//         });
//         return res.status(200).json({
//             success: true,
//             total: hostings.length,
//             reminders: hostings.map(formatHosting)
//         });
//     } catch (error) {
//         return handleError(res, error);
//     }
// };
// // RENEWAL ACTIVITY

// export const getRenewalActivity = async (req, res) => {

//     try {
//         const hostings = await Hosting.findAll({
//             where: {
//                 last_renewed_at: {
//                     [Op.ne]: null
//                 }
//             },
//             order: [["last_renewed_at", "DESC"]],
//             limit: 10
//         });
//         return res.status(200).json({
//             success: true,
//             total: hostings.length,
//             activity: hostings.map(formatHosting)
//         });
//     } catch (error) {
//         return handleError(res, error);
//     }
// };



import { Op } from "sequelize";
import { Hosting } from "../models/index.js";
import { addDays, todayOnly } from "../utils/dateHelpers.js";
import transporter from "../config/mail.js";
import { buildHostingRenewalMailHtml } from "../templates/mailTemplates.js";
import sanitizeHtml from "sanitize-html";
import { fileURLToPath } from "url";

const deytalLogoPath = fileURLToPath(new URL("../assets/DeytalLogo.png", import.meta.url));

// ======================
// ALLOWED VALUES
// ======================

const allowedStatuses = [
    "active",
    "expiring",
    "suspended",
    "expired",
    "pending"
];

const allowedBillingCycles = [
    "monthly",
    "quarterly",
    "half_yearly",
    "yearly"
];

// HELPERS
// ======================

// string => boolean
const parseBoolean = (value) => {
    if (value === true || value === "true" || value === 1 || value === "1") {
        return true;
    }

    return false;
};

// renewal date => days left (used by formatHosting + renewal email)
const getDaysLeft = (renewalDate) => {
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    const renewal = new Date(renewalDate);
    const diff = renewal - today;
    return Math.ceil(diff / (1000 * 60 * 60 * 24));
};

// derives status from days left (active/expiring/expired), respects manual suspended/pending
const getComputedStatus = (hosting) => {
    if (hosting.status === "suspended") return "suspended";
    if (hosting.status === "pending") return "pending";

    const daysLeft = getDaysLeft(hosting.renewal_date);
    if (daysLeft < 0) return "expired";
    if (daysLeft <= 30) return "expiring";
    return "active";
};





const getMonthlyCost = (hosting) => {

    const cost = Number(hosting.cost);

    if (hosting.billing_cycle === "monthly") {
        return cost;
    }

    if (hosting.billing_cycle === "quarterly") {
        return cost / 3;
    }

    if (hosting.billing_cycle === "half_yearly") {
        return cost / 6;
    }

    if (hosting.billing_cycle === "yearly") {
        return cost / 12;
    }

    return cost;
};



// final response format
const formatHosting = (hosting) => {

    const data = hosting.get
        ? hosting.get({ plain: true })
        : hosting;

    return {
        ...data,

        hosting: data.domain_name,

        cost: Number(data.cost),

        monthly_cost: Number(
            getMonthlyCost(data).toFixed(2)
        ),

        days_left: getDaysLeft(data.renewal_date),

        computed_status: getComputedStatus(data)
    };
};


// common error handler
const handleError = (res, error) => {

    console.log(error);

    // duplicate
    if (error.name === "SequelizeUniqueConstraintError") {

        return res.status(409).json({
            success: false,
            message: "Hosting domain already exists"
        });
    }

    // validation
    if (error.name === "SequelizeValidationError") {

        return res.status(400).json({
            success: false,
            message: error.errors[0].message
        });
    }

    // server error
    return res.status(500).json({
        success: false,
        message: "Internal server error"
    });
};

// CREATE HOSTING

export const createHosting = async (req, res) => {
    try {
        const {
            client_name,
            client_email,
            domain_name,
            cost,
            start_date,
            renewal_date,
            status,
            auto_renew,
        } = req.body;
        // required fields
        if (
            !client_name ||
            !client_email ||
            !domain_name ||
            !cost ||
            !renewal_date
        ) {
            return res.status(400).json({
                success: false,
            message: "Required fields missing"
            });
        }
        // duplicate check
        const existingHosting = await Hosting.findOne({
            where: {
                domain_name: domain_name.toLowerCase().trim()
            }
        });
        if (existingHosting) {
            return res.status(409).json({
                success: false,
                message: "Hosting domain already exists"
            });
        }
        // create
        const hosting = await Hosting.create({
            client_name,
            client_email,
            domain_name: domain_name.toLowerCase().trim(),
            cost,
            start_date,
            renewal_date,
            status: status || "active",
            auto_renew: parseBoolean(auto_renew)
        });
        return res.status(201).json({
            success: true,
            message: "Hosting created successfully",
            hosting: formatHosting(hosting)
        });

    } catch (error) {
        return handleError(res, error);
    }
};
// GET ALL HOSTINGS
// ======================

export const getHostings = async (req, res) => {

    try {
        const {
            search,
            status,
            billing_cycle
        } = req.query;
        let where = {};
        // status filter
        if (status && status !== "all") {
            where.status = status;
        }

        // billing filter
        if (billing_cycle) {
            where.billing_cycle = billing_cycle;
        }

        // search
        if (search) {

            where[Op.or] = [

                {
                    client_name: {
                        [Op.like]: `%${search}%`
                    }
                },

                {
                    domain_name: {
                        [Op.like]: `%${search}%`
                    }
                }
            ];
        }


        const hostings = await Hosting.findAll({
            where,
            order: [["renewal_date", "ASC"]]
        });


        return res.status(200).json({
            success: true,
            total: hostings.length,
            hostings: hostings.map(formatHosting)
        });

    } catch (error) {

        return handleError(res, error);
    }
};

// ======================
// GET SINGLE HOSTING
// ======================

export const getHostingById = async (req, res) => {

    try {

        const { id } = req.params;

        const hosting = await Hosting.findByPk(id);

        if (!hosting) {

            return res.status(404).json({
                success: false,
                message: "Hosting not found"
            });
        }


        return res.status(200).json({
            success: true,
            hosting: formatHosting(hosting)
        });

    } catch (error) {

        return handleError(res, error);
    }
};

// ======================
// UPDATE HOSTING
// ======================

export const updateHosting = async (req, res) => {

    try {

        const { id } = req.params;

        // find hosting
        const hosting = await Hosting.findByPk(id);

        if (!hosting) {

            return res.status(404).json({
                success: false,
                message: "Hosting not found"
            });
        }


        const {
            domain_name,
            status,
            billing_cycle,
            auto_renew
        } = req.body;


        // ======================
        // STATUS VALIDATION
        // ======================

        if (
            status &&
            !allowedStatuses.includes(status)
        ) {

            return res.status(400).json({
                success: false,
                message: `Status must be one of: ${allowedStatuses.join(", ")}`
            });
        }


        // ======================
        // BILLING VALIDATION
        // ======================

        if (
            billing_cycle &&
            !allowedBillingCycles.includes(billing_cycle)
        ) {

            return res.status(400).json({
                success: false,
                message: `Billing cycle must be one of: ${allowedBillingCycles.join(", ")}`
            });
        }


        // ======================
        // DUPLICATE DOMAIN CHECK
        // ======================

        // only check if user changing domain
        if (
            domain_name &&
            domain_name.trim().toLowerCase() !== hosting.domain_name
        ) {

            const existingHosting = await Hosting.findOne({

                where: {

                    domain_name: domain_name.trim().toLowerCase(),

                    // current id ignore
                    id: {
                        [Op.ne]: id
                    }
                }
            });


            // if domain already exists
            if (existingHosting) {

                return res.status(409).json({
                    success: false,
                    message: "Hosting domain already exists"
                });
            }
        }


        // ======================
        // UPDATE DATA
        // ======================

        await hosting.update({

            ...req.body,

            // keep old domain if not provided
            domain_name: domain_name
                ? domain_name.trim().toLowerCase()
                : hosting.domain_name,

            // boolean parse
            auto_renew:
                auto_renew !== undefined
                    ? parseBoolean(auto_renew)
                    : hosting.auto_renew,

            updated_at: new Date()
        });


        return res.status(200).json({

            success: true,

            message: "Hosting updated successfully",

            hosting: formatHosting(hosting)
        });

    } catch (error) {

        return handleError(res, error);
    }
};

// ======================
// DELETE HOSTING
// ======================

export const deleteHosting = async (req, res) => {

    try {

        const { id } = req.params;

        const hosting = await Hosting.findByPk(id);

        if (!hosting) {

            return res.status(404).json({
                success: false,
                message: "Hosting not found"
            });
        }


        await hosting.destroy();


        return res.status(200).json({
            success: true,
            message: "Hosting deleted successfully"
        });

    } catch (error) {

        return handleError(res, error);
    }
};

// ======================
// SEND RENEWAL ALERT EMAIL
// ======================

export const sendRenewalAlertEmailToUser = async (req, res) => {
    try {
        const { id } = req.params;
        const { customMessageHtml } = req.body;
        const hosting = await Hosting.findByPk(id);

        if (!hosting) {
            return res.status(404).json({
                success: false,
                message: "Hosting not found"
            });
        }

        const recipient = (hosting.client_email || hosting.email || '').trim().toLowerCase();

        if (!recipient) {
            return res.status(400).json({
                success: false,
                message: "No email address found for this hosting"
            });
        }

        const sanitizedHtml = customMessageHtml
            ? sanitizeHtml(customMessageHtml, {
                allowedTags: [
                    'div', 'p', 'span', 'strong', 'b', 'em', 'i', 'u',
                    'h1', 'h2', 'h3', 'h4', 'a', 'br', 'hr',
                    'table', 'thead', 'tbody', 'tr', 'th', 'td',
                    'ul', 'ol', 'li', 'img'
                ],
                allowedAttributes: {
                    '*': ['style', 'class'],
                    a: ['href', 'target', 'rel'],
                    img: ['src', 'alt', 'width', 'height']
                },
                allowedSchemes: ['http', 'https', 'mailto'],
                allowedStyles: {
                    '*': {
                        'color': [/^.*$/],
                        'background-color': [/^.*$/],
                        'background': [/^.*$/],
                        'text-align': [/^.*$/],
                        'font-size': [/^.*$/],
                        'font-weight': [/^.*$/],
                        'font-family': [/^.*$/],
                        'padding': [/^.*$/],
                        'margin': [/^.*$/],
                        'border': [/^.*$/],
                        'border-bottom': [/^.*$/],
                        'border-radius': [/^.*$/],
                        'border-collapse': [/^.*$/],
                        'width': [/^.*$/],
                        'max-width': [/^.*$/],
                        'overflow': [/^.*$/],
                        'line-height': [/^.*$/]
                    }
                }
            })
            : null;

            

        await transporter.sendMail({
            from: process.env.EMAIL_USER,
            to: recipient,
            subject: `Hosting renewal reminder: ${hosting.domain_name} ${getDaysLeft(hosting.renewal_date) < 0 ? 'has expired' : `renews in ${getDaysLeft(hosting.renewal_date)} day${getDaysLeft(hosting.renewal_date) === 1 ? '' : 's'}`}`,
            html: buildHostingRenewalMailHtml(hosting, sanitizedHtml),
            attachments: sanitizedHtml ? [] : [
                {
                    filename: "DeytalLogo.png",
                    path: deytalLogoPath,
                    cid: "deytal-logo"
                }
            ]
        });

        await hosting.update({
            reminder_sent_at: new Date(),
            reminder_for_renewal: hosting.renewal_date
        });

        return res.status(200).json({
            success: true,
            message: "Hosting renewal email sent to user",
            recipient
        });
    } catch (error) {
        return handleError(res, error);
    }
};

// ======================
// RENEW HOSTING
// ======================

export const renewHosting = async (req, res) => {

    try {

        const { id } = req.params;

        const { renewal_date } = req.body;

        const hosting = await Hosting.findByPk(id);

        if (!hosting) {

            return res.status(404).json({
                success: false,
                message: "Hosting not found"
            });
        }


        if (!renewal_date) {

            return res.status(400).json({
                success: false,
                message: "Renewal date required"
            });
        }


        await hosting.update({

            renewal_date,

            status: "active",

            last_renewed_at: todayOnly(),

            updated_at: new Date()
        });


        return res.status(200).json({
            success: true,
            message: "Hosting renewed successfully",
            hosting: formatHosting(hosting)
        });

    } catch (error) {

        return handleError(res, error);
    }
};

// ======================
// TOGGLE AUTO RENEW
// ======================

export const toggleAutoRenew = async (req, res) => {

    try {

        const { id } = req.params;

        const hosting = await Hosting.findByPk(id);

        if (!hosting) {

            return res.status(404).json({
                success: false,
                message: "Hosting not found"
            });
        }


        await hosting.update({

            auto_renew: !hosting.auto_renew,

            updated_at: new Date()
        });


        return res.status(200).json({
            success: true,
            message: "Auto renew updated successfully",
            hosting: formatHosting(hosting)
        });

    } catch (error) {

        return handleError(res, error);
    }
};

// ======================
// UPDATE HOSTING STATUS
// ======================

export const updateHostingStatus = async (req, res) => {

    try {

        const { id } = req.params;

        const { status } = req.body;

        const hosting = await Hosting.findByPk(id);

        if (!hosting) {

            return res.status(404).json({
                success: false,
                message: "Hosting not found"
            });
        }


        if (!status || !allowedStatuses.includes(status)) {

            return res.status(400).json({
                success: false,
                message: `Status must be one of: ${allowedStatuses.join(", ")}`
            });
        }


        await hosting.update({

            status,

            updated_at: new Date()
        });


        return res.status(200).json({
            success: true,
            message: "Hosting status updated successfully",
            hosting: formatHosting(hosting)
        });

    } catch (error) {

        return handleError(res, error);
    }
};

// ======================
// HOSTING STATS
// ======================

export const getHostingStats = async (req, res) => {

    try {

        const today = todayOnly();

        const next30Days = addDays(today, 30);


        // counts
        const totalHostingPlans = await Hosting.count();

        const activeHostingPlans = await Hosting.count({
            where: {
                status: "active"
            }
        });

        const suspendedServices = await Hosting.count({
            where: {
                status: "suspended"
            }
        });

        const expiringServers = await Hosting.count({

            where: {

                renewal_date: {
                    [Op.between]: [today, next30Days]
                },

                status: {
                    [Op.ne]: "suspended"
                }
            }
        });


        // all hostings
        const hostings = await Hosting.findAll();


        // monthly cost
        let monthlyHostingCost = 0;

        hostings.forEach((hosting) => {

            if (hosting.status !== "suspended") {

                monthlyHostingCost += getMonthlyCost(hosting);
            }
        });


        return res.status(200).json({

            success: true,

            stats: {

                totalHostingPlans,

                activeHostingPlans,

                expiringServers,

                suspendedServices,

                monthlyHostingCost: Number(
                    monthlyHostingCost.toFixed(2)
                ),

                averageMonthlyCost:
                    activeHostingPlans > 0
                        ? Number(
                            (
                                monthlyHostingCost /
                                activeHostingPlans
                            ).toFixed(2)
                        )
                        : 0
            }
        });

    } catch (error) {

        return handleError(res, error);
    }
};

// ======================
// RENEWAL REMINDERS
// ======================

export const getRenewalReminders = async (req, res) => {

    try {
        const days = Number(req.query.days || 30);
        const today = todayOnly();
        const endDate = addDays(today, days);
        const hostings = await Hosting.findAll({
            where: {
                renewal_date: {
                    [Op.between]: [today, endDate]
                },
                status: {
                    [Op.ne]: "suspended"
                }
            },
            order: [["renewal_date", "ASC"]]
        });
        return res.status(200).json({
            success: true,
            total: hostings.length,
            reminders: hostings.map(formatHosting)
        });
    } catch (error) {
        return handleError(res, error);
    }
};
// RENEWAL ACTIVITY

export const getRenewalActivity = async (req, res) => {

    try {
        const hostings = await Hosting.findAll({
            where: {
                last_renewed_at: {
                    [Op.ne]: null
                }
            },
            order: [["last_renewed_at", "DESC"]],
            limit: 10
        });
        return res.status(200).json({
            success: true,
            total: hostings.length,
            activity: hostings.map(formatHosting)
        });
    } catch (error) {
        return handleError(res, error);
    }
};
