const db = require("../../db");
const path = require("path");
const fs = require("fs");
const { Op } = require("sequelize");

const UPLOAD_DIR = path.join(__dirname, "../../public/uploads/landing-pages");
if (!fs.existsSync(UPLOAD_DIR)) {
  fs.mkdirSync(UPLOAD_DIR, { recursive: true });
}

const handleFileUpload = async (file, subfolder) => {
  const uploadPath = path.join(UPLOAD_DIR, subfolder);
  if (!fs.existsSync(uploadPath)) {
    fs.mkdirSync(uploadPath, { recursive: true });
  }

  const fileName = `${Date.now()}-${file.name.replace(/\s+/g, "-")}`;
  const filePath = path.join(uploadPath, fileName);
  await file.mv(filePath);
  return fileName;
};

// Helper function to remove non-Latin1 characters
const sanitizeForLatin1 = (str) => {
  if (!str) return str;
  return str.replace(/[^\x00-\xFF]/g, ""); // Remove any non-Latin1 characters
};

exports.createLandingPage = async (req, res) => {
  try {
    const {
      college_id,
      college_url,
      title_1,
      description_1,
      title_2,
      description_2,
      companies,
    } = req.body;

    if (!college_id) {
      return res.status(400).json({ error: "College ID is required" });
    }

    // Sanitize text fields to remove non-Latin1 characters
    const sanitizedData = {
      title_1: sanitizeForLatin1(title_1),
      description_1: sanitizeForLatin1(description_1),
      title_2: sanitizeForLatin1(title_2),
      description_2: sanitizeForLatin1(description_2),
    };

    // Handle file uploads (unchanged)
    let collegeLogoPath = "";
    if (req.files?.college_logo) {
      collegeLogoPath = await handleFileUpload(req.files.college_logo, "logos");
    }

    let collegeBannerPath = "";
    if (req.files?.college_banner) {
      collegeBannerPath = await handleFileUpload(
        req.files.college_banner,
        "banners"
      );
    }

    // Create landing page with sanitized data
    const landingPage = await db.LandingPage.create({
      college_id,
      college_url,
      college_logo: collegeLogoPath,
      college_banner: collegeBannerPath,
      title_1: sanitizedData.title_1,
      description_1: sanitizedData.description_1,
      title_2: sanitizedData.title_2,
      description_2: sanitizedData.description_2,
      companies: Array.isArray(companies)
        ? companies
        : JSON.parse(companies || "[]"),
    });

    res.status(201).json({
      success: true,
      message: "Landing page created successfully",
      data: landingPage,
    });
  } catch (err) {
    console.error("Error:", err);
    res.status(500).json({
      success: false,
      message: "Failed to create landing page",
      error: process.env.NODE_ENV === "development" ? err.message : undefined,
    });
  }
};

exports.getLandingPage = async (req, res) => {
  try {
    const { id, college_id, college_url } = req.query;

    const options = {
      include: [
        {
          model: db.College,
          as: "college",
        },
      ],
      raw: true,
      nest: true,
    };

    if (college_url) {
      options.where = { college_url };
      const landingPage = await db.LandingPage.findOne(options);
      if (!landingPage) {
        return res
          .status(404)
          .json({ error: "Landing page not found for this college URL" });
      }
      return res.json(landingPage);
    }

    if (id) {
      options.where = { id };
      const landingPage = await db.LandingPage.findOne(options);
      if (!landingPage) {
        return res.status(404).json({ error: "Landing page not found" });
      }
      return res.json(landingPage);
    }

    if (college_id) {
      options.where = { college_id };
      const landingPage = await db.LandingPage.findOne(options);
      if (!landingPage) {
        return res
          .status(404)
          .json({ error: "Landing page not found for this college" });
      }
      return res.json(landingPage);
    }

    // If no specific parameter is provided, return all landing pages
    const landingPages = await db.LandingPage.findAll({
      ...options,
      order: [["id", "DESC"]],
    });

    res.json(landingPages);
  } catch (err) {
    console.error("Error fetching landing page(s):", err);
    res.status(500).json({ error: "Failed to fetch landing page(s)" });
  }
};

exports.updateLandingPage = async (req, res) => {
  try {
    const landingPageId = req.params.id;
    const landingPage = await db.LandingPage.findByPk(landingPageId);

    if (!landingPage) {
      return res.status(404).json({
        status: false,
        message: "Landing page not found",
      });
    }

    // Handle file uploads
    if (req.files?.college_logo) {
      const collegeLogoPath = await handleFileUpload(
        req.files.college_logo,
        "logos"
      );
      landingPage.college_logo = collegeLogoPath;
    }

    if (req.files?.college_banner) {
      const collegeBannerPath = await handleFileUpload(
        req.files.college_banner,
        "banners"
      );
      landingPage.college_banner = collegeBannerPath;
    }

    // Update fields
    const updatableFields = [
      "college_id",
      "college_url",
      "title_1",
      "description_1",
      "title_2",
      "description_2",
      "companies",
    ];

    updatableFields.forEach((field) => {
      if (req.body[field] !== undefined) {
        // Special handling for companies
        if (field === "companies") {
          try {
            landingPage[field] =
              typeof req.body[field] === "string"
                ? JSON.parse(req.body[field])
                : req.body[field];
          } catch (e) {
            console.error("Error parsing companies:", e);
          }
        } else {
          landingPage[field] = req.body[field];
        }
      }
    });

    await landingPage.save();

    return res.status(200).json({
      status: true,
      message: "Landing page updated successfully",
      data: landingPage,
    });
  } catch (error) {
    console.error("Update error:", error);
    return res.status(500).json({
      status: false,
      message: "Failed to update landing page",
      error: error.message,
    });
  }
};

exports.deleteLandingPage = async (req, res) => {
  try {
    const landingPageId = req.params.id;

    if (!landingPageId) {
      return res.status(400).json({
        status: false,
        message: "Landing page id is required",
      });
    }

    const landingPage = await db.LandingPage.findByPk(landingPageId);
    if (!landingPage) {
      return res.status(404).json({
        status: false,
        message: "Landing page not found",
      });
    }

    // Optional: Delete associated files
    if (landingPage.college_logo) {
      const logoPath = path.join(
        __dirname,
        "../../public",
        landingPage.college_logo
      );
      if (fs.existsSync(logoPath)) fs.unlinkSync(logoPath);
    }

    if (landingPage.college_banner) {
      const bannerPath = path.join(
        __dirname,
        "../../public",
        landingPage.college_banner
      );
      if (fs.existsSync(bannerPath)) fs.unlinkSync(bannerPath);
    }

    await landingPage.destroy();

    return res.status(200).json({
      status: true,
      message: "Landing page deleted successfully",
    });
  } catch (error) {
    console.error("Delete error:", error);
    return res.status(500).json({
      status: false,
      message: "Failed to delete landing page",
      error: error.message,
    });
  }
};
// Company CRUD operations
exports.createCompany = async (req, res) => {
  try {
    const { company } = req.body;

    if (!company) {
      return res.status(400).json({ error: "Company name is required" });
    }

    let imagePath = "";
    if (req.files?.image) {
      imagePath = await handleFileUpload(req.files.image, "companies");
    }

    const companyData = {
      company,
      image: imagePath,
      status: 1,
    };

    const newCompany = await db.Company.create(companyData);

    res.status(201).json({
      success: true,
      message: "Company created successfully",
      data: newCompany,
    });
  } catch (err) {
    console.error("Error:", err);
    res.status(500).json({
      success: false,
      message: "Failed to create company",
      error: process.env.NODE_ENV === "development" ? err.message : undefined,
    });
  }
};

exports.getCompanies = async (req, res) => {
  try {
    const { search } = req.query;

    const where = {};
    if (search) {
      where.company = { [Op.like]: `%${search}%` };
    }

    const companies = await db.Company.findAll({
      where,
      order: [["company", "ASC"]],
    });

    res.json(companies);
  } catch (err) {
    console.error("Error fetching companies:", err);
    res.status(500).json({ error: "Failed to fetch companies" });
  }
};

exports.updateCompany = async (req, res) => {
  try {
    const companyId = req.params.id;
    const company = await db.Company.findByPk(companyId);

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

    // Handle image upload
    if (req.files?.image) {
      const imagePath = await handleFileUpload(req.files.image, "companies");
      company.image = imagePath;
    }

    // Update fields
    if (req.body.company !== undefined) {
      company.company = req.body.company;
    }
    if (req.body.status !== undefined) {
      company.status = req.body.status;
    }

    await company.save();

    return res.status(200).json({
      status: true,
      message: "Company updated successfully",
      data: company,
    });
  } catch (error) {
    console.error("Update error:", error);
    return res.status(500).json({
      status: false,
      message: "Failed to update company",
      error: error.message,
    });
  }
};

exports.deleteCompany = async (req, res) => {
  try {
    const companyId = req.params.id;

    if (!companyId) {
      return res.status(400).json({
        status: false,
        message: "Company id is required",
      });
    }

    const company = await db.Company.findByPk(companyId);
    if (!company) {
      return res.status(404).json({
        status: false,
        message: "Company not found",
      });
    }

    await company.destroy();

    return res.status(200).json({
      status: true,
      message: "Company deleted successfully",
    });
  } catch (error) {
    console.error("Delete error:", error);
    return res.status(500).json({
      status: false,
      message: "Failed to delete company",
      error: error.message,
    });
  }
};
