const db = require('../db/config');

// Roles
exports.getRoles = async (req, res) => {
  const [rows] = await db.query('SELECT * FROM roles');
  res.json(rows);
};

exports.createRole = async (req, res) => {
  const { name } = req.body;
  await db.query('INSERT INTO roles (name) VALUES (?)', [name]);
  res.json({ message: 'Role created' });
};

exports.updateRole = async (req, res) => {
  const { name } = req.body;
  await db.query('UPDATE roles SET name = ? WHERE id = ?', [name, req.params.id]);
  res.json({ message: 'Role updated' });
};

exports.deleteRole = async (req, res) => {
  await db.query('DELETE FROM roles WHERE id = ?', [req.params.id]);
  res.json({ message: 'Role deleted' });
};

// Pages
exports.getPages = async (req, res) => {
  try {
    const [rows] = await db.query(`
      SELECT 
        p.*, 
        parent.label AS parent_label
      FROM pages p
      LEFT JOIN pages parent ON p.parent_id = parent.id
      ORDER BY p.parent_id, p.order
    `);

    res.json(rows);
  } catch (error) {
    console.error('Error fetching pages:', error);
    res.status(500).json({ error: 'Failed to fetch pages' });
  }
};

exports.createPage = async (req, res) => {
  const { label, path, icon, parent_id, order, show_in_menu } = req.body;

  try {
    await db.query(
      'INSERT INTO pages (label, path, icon, parent_id, `order`, show_in_menu) VALUES (?, ?, ?, ?, ?, ?)',
      [label, path, icon || null, parent_id || null, order || 0, show_in_menu ?? true]
    );
    res.status(201).json({ message: 'Page created successfully' });
  } catch (error) {
    console.error('Error creating page:', error);
    res.status(500).json({ error: 'Failed to create page' });
  }
};
exports.getPageById = async (req, res) => {
  const { id } = req.params;
  try {
    const [rows] = await db.query('SELECT * FROM pages WHERE id = ?', [id]);
    if (rows.length === 0) {
      return res.status(404).json({ error: 'Page not found' });
    }
    res.json(rows[0]);
  } catch (error) {
    console.error('Error fetching page:', error);
    res.status(500).json({ error: 'Failed to fetch page' });
  }
};

exports.updatePage = async (req, res) => {
  const { label, path, icon, parent_id, order, show_in_menu } = req.body;

  try {
    await db.query(
      'UPDATE pages SET label = ?, path = ?, icon = ?, parent_id = ?, `order` = ?, show_in_menu = ? WHERE id = ?',
      [label, path, icon, parent_id || null, order || 0, show_in_menu ?? true, req.params.id]
    );
    res.json({ message: 'Page updated successfully' });
  } catch (error) {
    console.error('Error updating page:', error);
    res.status(500).json({ error: 'Failed to update page' });
  }
};


exports.deletePage = async (req, res) => {
  await db.query('DELETE FROM pages WHERE id = ?', [req.params.id]);
  res.json({ message: 'Page deleted' });
};

// Get all page IDs assigned to a specific role
exports.getRolePages = async (req, res) => {
  const { roleId } = req.params;

  try {
    const [rows] = await db.query(
      "SELECT page_id FROM role_page_access WHERE role_id = ?",
      [roleId]
    );

    const pageIds = rows.map(r => r.page_id);
    res.json(pageIds);
  } catch (err) {
    console.error('Error fetching role pages:', err);
    res.status(500).json({ error: 'Failed to fetch role pages' });
  }
};


// Assign/update page access for a specific role
exports.updateRolePages = async (req, res) => {
  const { roleId } = req.params;
  const { pageIds } = req.body;

  try {
    // Validate pageIds exist
    const [existingPages] = await db.query(
      `SELECT id FROM pages WHERE id IN (${pageIds.map(() => '?').join(',')})`,
      pageIds
    );

    const validPageIds = existingPages.map(p => p.id);
    if (validPageIds.length !== pageIds.length) {
      return res.status(400).json({ error: 'Some page IDs do not exist' });
    }

    // Clear old access
    await db.query('DELETE FROM role_page_access WHERE role_id = ?', [roleId]);

    // Insert new access
    const values = validPageIds.map(pid => [roleId, pid]);
    if (values.length > 0) {
      await db.query('INSERT INTO role_page_access (role_id, page_id) VALUES ?', [values]);
    }

    res.json({ message: 'Role access updated successfully' });
  } catch (err) {
    console.error('Error updating role access:', err);
    res.status(500).json({ error: 'Server error' });
  }
};



exports.getPagesWithRoleAccess = async (req, res) => {
  const roleId = req.params.roleId;

  try {
    const [rows] = await db.query(`
      SELECT 
        p.*, 
        parent.label AS parent_label,
        CASE WHEN rpa.role_id IS NOT NULL THEN true ELSE false END AS assigned
      FROM pages p
      LEFT JOIN role_page_access rpa ON rpa.page_id = p.id AND rpa.role_id = ?
      LEFT JOIN pages parent ON p.parent_id = parent.id
      ORDER BY p.parent_id, p.order
    `, [roleId]);

    res.json(rows);
  } catch (error) {
    console.error('Error fetching pages with role access:', error);
    res.status(500).json({ error: 'Failed to fetch role pages' });
  }
};

