const db = require("../db/db");

const getAllPages = () => {
  const sql = `SELECT * FROM pagehide WHERE Status = 1`;
  return new Promise((resolve, reject) => {
    db.query(sql, (err, results) => {
      if (err) {
        reject(err);
      } else {
        resolve(results);
      }
    });
  });
};

const getallAdmin = () => {
  const sql = `SELECT * FROM pagehide`;
  return new Promise((resolve, reject) => {
    db.query(sql, (err, results) => {
      if (err) {
        reject(err);
      } else {
        resolve(results);
      }
    });
  });
};

const changeStatus = (idPagehide) => {
  const sql = `UPDATE pagehide SET Status = CASE 
    WHEN Status = 1 THEN 0
    ELSE 1
END
WHERE idPagehide = ?`;

  return new Promise((resolve, reject) => {
    db.query(sql, [idPagehide], (err, results) => {
      if (err) {
        reject(err);
      } else {
        resolve(results);
      }
    });
  });
};

const getAllPagesByLang = (lang) => {
  let nameField = "Page";

  if (["fr", "es", "gr"].includes(lang)) {
    nameField = `Page_${lang}`;
  }

  const sql = `SELECT  COALESCE(${nameField}) AS Page,idPagehide,link FROM pagehide WHERE Status = 1`;
  return new Promise((resolve, reject) => {
    db.query(sql, (err, results) => {
      if (err) {
        reject(err);
      } else {
        resolve(results);
      }
    });
  });
};

module.exports = {
  getAllPages,
  changeStatus,
  getallAdmin,
  getAllPagesByLang,
};
