const express = require('express');
const path = require('path');
const fs = require('fs');
const multer = require('multer');
const bcrypt = require('bcryptjs');
const store = require('../store');
const requireLogin = require('../middleware/auth');

const router = express.Router();

// Liste des icônes disponibles pour les avantages (clé → libellé)
const ICONS = [
  ['securite', 'Bouclier / Sécurité'], ['piscine', 'Piscine'], ['sport', 'Sport / Fitness'],
  ['parking', 'Parking'], ['espaces', 'Espaces verts'], ['commerce', 'Commerce'],
  ['jeux', 'Aire de jeux'], ['cinema', 'Cinéma'], ['maison', 'Maison'],
  ['cle', 'Clé'], ['etoile', 'Étoile'], ['soleil', 'Soleil'],
  ['climatisation', 'Climatisation'], ['chauffage', 'Chauffage'], ['fibre', 'Fibre optique'],
  ['camera', 'Caméra'], ['video', 'Vidéophone / Interphone'], ['vitrage', 'Double vitrage'],
  ['ascenseur', 'Ascenseur'], ['credit', 'Crédit bancaire'],
  ['horloge', 'Délais / Ponctualité'], ['accompagnement', 'Accompagnement']
];

// ---- Upload des photos ----
const uploadDir = path.join(__dirname, '..', 'public', 'uploads');
fs.mkdirSync(uploadDir, { recursive: true });

const storage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, uploadDir),
  filename: (req, file, cb) => {
    const ext = (path.extname(file.originalname) || '.jpg').toLowerCase();
    cb(null, 'bien-' + Date.now() + '-' + Math.round(Math.random() * 1e4) + ext);
  }
});
const upload = multer({
  storage,
  limits: { fileSize: 8 * 1024 * 1024 },
  fileFilter: (req, file, cb) => cb(null, /^image\/(jpe?g|png|webp)$/.test(file.mimetype))
});

// Normalise un champ qui peut arriver en string unique ou en tableau
function toArray(v) {
  if (v === undefined || v === null) return [];
  return Array.isArray(v) ? v : [v];
}

// Assemble les typologies saisies en lignes parallèles (typo_nom[], typo_nb[], ...)
function buildTypologies(b) {
  const noms = toArray(b.typo_nom), nbs = toArray(b.typo_nb), sups = toArray(b.typo_superficie),
        plans = toArray(b.typo_plan), photo = toArray(b.typo_photo), photos = toArray(b.typo_photos),
        avs = toArray(b.typo_avantages), descs = toArray(b.typo_description);
  const out = [];
  for (let i = 0; i < noms.length; i++) {
    const t = {
      nom: (noms[i] || '').trim(), nb: (nbs[i] || '').trim(), superficie: (sups[i] || '').trim(),
      plan: (plans[i] || '').trim(), photo: (photo[i] || '').trim(), photos: (photos[i] || '').trim(),
      avantages: (avs[i] || '').trim(), description: (descs[i] || '').trim()
    };
    if (t.nom || t.nb || t.superficie || t.plan || t.photo || t.photos || t.avantages || t.description) out.push(t);
  }
  return out;
}

router.use(requireLogin);

// ---- Tableau de bord ----
router.get('/', (req, res) => {
  res.render('dashboard', {
    nbBiens: store.bienCount(),
    nbMessages: store.messageCount(),
    nonLus: store.unreadCount(),
    nbAvantages: store.avantageCount(),
    recents: store.recentMessages(5)
  });
});

// ===================== BIENS =====================
router.get('/biens', (req, res) => {
  res.render('biens', { biens: store.allBiens() });
});

router.get('/biens/new', (req, res) => {
  res.render('bien-form', { bien: null });
});

router.post('/biens', upload.array('photos', 12), (req, res) => {
  const b = req.body;
  const photos = (req.files || []).map(f => '/uploads/' + f.filename);
  store.createBien({ ...b, typologies: buildTypologies(b), photos, image: photos[0] || '' });
  res.redirect('/admin/biens');
});

router.get('/biens/:id/edit', (req, res) => {
  const bien = store.getBien(req.params.id);
  if (!bien) return res.redirect('/admin/biens');
  res.render('bien-form', { bien });
});

router.post('/biens/:id', upload.array('photos', 12), (req, res) => {
  const b = req.body;
  const kept = toArray(b.keep_photos);                       // photos existantes conservées
  const added = (req.files || []).map(f => '/uploads/' + f.filename); // nouvelles
  const photos = [...kept, ...added];
  store.updateBien(req.params.id, { ...b, typologies: buildTypologies(b), photos, image: photos[0] || '' });
  res.redirect('/admin/biens');
});

router.post('/biens/:id/delete', (req, res) => {
  store.deleteBien(req.params.id);
  res.redirect('/admin/biens');
});

// ===================== AVANTAGES =====================
router.get('/avantages', (req, res) => {
  res.render('avantages', { avantages: store.allAvantages() });
});

router.get('/avantages/new', (req, res) => {
  res.render('avantage-form', { avantage: null, icons: ICONS });
});

router.post('/avantages', (req, res) => {
  store.createAvantage(req.body);
  res.redirect('/admin/avantages');
});

router.get('/avantages/:id/edit', (req, res) => {
  const avantage = store.getAvantage(req.params.id);
  if (!avantage) return res.redirect('/admin/avantages');
  res.render('avantage-form', { avantage, icons: ICONS });
});

router.post('/avantages/:id', (req, res) => {
  store.updateAvantage(req.params.id, req.body);
  res.redirect('/admin/avantages');
});

router.post('/avantages/:id/delete', (req, res) => {
  store.deleteAvantage(req.params.id);
  res.redirect('/admin/avantages');
});

// ===================== CONTENU DU SITE =====================
router.get('/contenu', (req, res) => {
  res.render('contenu', { content: store.getContent(), saved: req.query.saved === '1' });
});

router.post('/contenu', (req, res) => {
  const allowed = [
    'hero_kicker', 'hero_lead', 'residence_text',
    'contact_address', 'contact_phone1', 'contact_phone2', 'contact_email', 'contact_hours',
    'loc_text', 'loc_address'
  ];
  const payload = {};
  for (const k of allowed) if (req.body[k] !== undefined) payload[k] = String(req.body[k]).trim();
  store.setContent(payload);
  res.redirect('/admin/contenu?saved=1');
});

// ===================== DEMANDES =====================
router.get('/messages', (req, res) => {
  const messages = store.allMessages();
  store.markAllRead();
  res.render('messages', { messages });
});

router.post('/messages/:id/delete', (req, res) => {
  store.deleteMessage(req.params.id);
  res.redirect('/admin/messages');
});

// ===================== MON COMPTE =====================
// Permet au proprietaire du site de changer son mot de passe lui-meme,
// sans que personne d'autre n'ait a le connaitre.
router.get('/compte', (req, res) => {
  res.render('compte', { email: req.session.userEmail, err: null, ok: req.query.ok === '1' });
});

router.post('/compte/motdepasse', (req, res) => {
  const email = req.session.userEmail;
  const actuel = String(req.body.actuel || '');
  const nouveau = String(req.body.nouveau || '');
  const confirm = String(req.body.confirm || '');

  const fail = (m) => res.status(400).render('compte', { email: email, err: m, ok: false });

  const user = store.getUserByEmail(email);
  if (!user) return fail("Session expiree, reconnectez-vous.");
  if (!bcrypt.compareSync(actuel, user.password_hash)) return fail("Le mot de passe actuel est incorrect.");
  if (nouveau.length < 10) return fail("Le nouveau mot de passe doit faire au moins 10 caracteres.");
  if (nouveau !== confirm) return fail("Les deux nouveaux mots de passe ne correspondent pas.");
  if (nouveau === actuel) return fail("Le nouveau mot de passe doit etre different de l'actuel.");

  store.setUserPassword(email, bcrypt.hashSync(nouveau, 10));
  res.redirect('/admin/compte?ok=1');
});

module.exports = router;
