const express = require('express');
const router = express.Router();
const db = require('../db');

// Middleware
const isLoggedIn = (req, res, next) => {
  if (req.session.admin) return next();
  res.redirect('/admin/login');
};

// Login Page
router.get('/login', (req, res) => {
  res.render('admin-login');
});

router.post('/login', (req, res) => {
  const { username, password } = req.body;
  db.query('SELECT * FROM admin WHERE username = ? AND password = ?', [username, password], (err, result) => {
    if (err || result.length === 0) return res.send('Invalid credentials');
    req.session.admin = true;
    res.redirect('/admin/dashboard');
  });
});

// Logout
router.get('/logout', (req, res) => {
  req.session.destroy();
  res.redirect('/admin/login');
});

// Dashboard
router.get('/dashboard', isLoggedIn, (req, res) => {
  db.query('SELECT * FROM blogs', (err, blogs) => {
    res.render('admin-dashboard', { blogs });
  });
});

// Add blog
router.get('/add', isLoggedIn, (req, res) => {
  res.render('add-blog');
});


// ADD BLOG ROUTE
router.post('/add', isLoggedIn, (req, res) => {
  const {
    title,
    slug,
    Imgbg,
    pg1,
    pg2,
    Img1,
    Img2,
    Img3,
    tags,
    hed1,
    hpg1,
    hed2,
    hpg2,
    seo_title,
    seo_description,
    seo_canonical,
    seo_robots_index,
    seo_robots_follow,
    og_title,
    og_description,
    og_type,
    og_url,
    og_site_name,
    og_locale,
    og_image_url,
    og_image_width,
    og_image_height,
    og_image_type,
    article_modified_time,
    twitter_card,
    is_published,
    focus_keyphrase // ✅ make sure this exists in DB!
  } = req.body;

  const sql = `
    INSERT INTO blogs (
      title, slug, Imgbg, pg1, pg2,
      Img1, Img2, Img3, tags,
      hed1, hpg1, hed2, hpg2,
      seo_title, seo_description, seo_canonical,
      seo_robots_index, seo_robots_follow,
      og_title, og_description, og_type, og_url, og_site_name, og_locale,
      og_image_url, og_image_width, og_image_height, og_image_type,
      article_modified_time, twitter_card, is_published, focus_keyphrase
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `;

  const values = [
    title, slug, Imgbg, pg1, pg2,
    Img1, Img2, Img3, tags,
    hed1, hpg1, hed2, hpg2,
    seo_title, seo_description, seo_canonical,
    seo_robots_index, seo_robots_follow,
    og_title, og_description, og_type, og_url, og_site_name, og_locale,
    og_image_url, og_image_width, og_image_height, og_image_type,
    article_modified_time, twitter_card,
    is_published === '1' ? 1 : 0,
    focus_keyphrase
  ];

  db.query(sql, values, (err, result) => {
    if (err) {
      console.error('Error inserting blog:', err.sqlMessage || err);
      return res.send('Something went wrong while saving the blog.');
    }
    res.redirect('/admin/dashboard');
  });
});





// Edit blog - Form Page
router.get('/edit/:id', isLoggedIn, (req, res) => {
  db.query('SELECT * FROM blogs WHERE id = ?', [req.params.id], (err, result) => {
    if (err || result.length === 0) return res.send('Blog not found');
    res.render('edit-blog', { blog: result[0] });
  });
});


// Edit blog - Update DB
// Edit blog - Update DB
router.post('/edit/:id', isLoggedIn, (req, res) => {
  const blogId = req.params.id;

  const {
    title, slug, Imgbg, pg1, pg2,
    Img1, Img2, Img3, tags,
    hed1, hpg1, hed2, hpg2,
    seo_title, seo_description, seo_canonical,
    seo_robots_index, seo_robots_follow,
    og_title, og_description, og_type, og_url, og_site_name, og_locale,
    og_image_url, og_image_width, og_image_height, og_image_type,
    article_modified_time, twitter_card, is_published,
    focus_keyphrase
  } = req.body;


  const sql = `
    UPDATE blogs SET
      title = ?, slug = ?, Imgbg = ?, pg1 = ?, pg2 = ?,
      Img1 = ?, Img2 = ?, Img3 = ?, tags = ?,
      hed1 = ?, hpg1 = ?, hed2 = ?, hpg2 = ?,
      seo_title = ?, seo_description = ?, seo_canonical = ?,
      seo_robots_index = ?, seo_robots_follow = ?,
      og_title = ?, og_description = ?, og_type = ?,
      og_url = ?, og_site_name = ?, og_locale = ?,
      og_image_url = ?, og_image_width = ?, og_image_height = ?, og_image_type = ?,
      article_modified_time = ?, twitter_card = ?, is_published = ?, focus_keyphrase = ?
    WHERE id = ?
  `;

  const values = [
    title, slug, Imgbg, pg1, pg2,
    Img1, Img2, Img3, tags,
    hed1, hpg1, hed2, hpg2,
    seo_title, seo_description, seo_canonical,
    seo_robots_index, seo_robots_follow,
    og_title, og_description, og_type, og_url, og_site_name, og_locale,
    og_image_url, og_image_width, og_image_height, og_image_type,
    article_modified_time, twitter_card, is_published === '1' ? 1 : 0, focus_keyphrase,
    blogId
  ];



  db.query(sql, values, err => {
    if (err) {
      console.error('SQL Error:', err.sqlMessage || err.message || err);
      return res.send(`Error: ${err.sqlMessage || err.message || err}`);
    }

    res.redirect('/admin/dashboard');
  });
});











// Delete blog
// Delete a blog post by slug
router.post('/delete/:slug', (req, res) => {
  const slug = req.params.slug;

  if (!slug) {
    return res.status(400).send('Slug is required');
  }

  db.query('DELETE FROM blogs WHERE slug = ?', [slug], (err, result) => {
    if (err) {
      console.error('Error deleting blog by slug:', err);
      return res.status(500).send('Database error');
    }

    if (result.affectedRows === 0) {
      return res.status(404).send('Blog not found');
    }

    console.log(`Blog with slug "${slug}" deleted successfully`);
    res.redirect('/admin/dashboard');
  });
});



module.exports = router;
