const express = require('express');
const router = express.Router();
const fs = require('fs');
const path = require('path');
const multer = require('multer');

// Configure Multer for File Uploads (Brochure PDF & Images)
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadDir = path.join(__dirname, '../public/uploads');
    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    if (file.fieldname === 'brosurFile') {
      cb(null, 'brosur.pdf');
    } else {
      const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
      cb(null, uniqueSuffix + path.extname(file.originalname));
    }
  }
});

const upload = multer({
  storage: storage,
  limits: { fileSize: 15 * 1024 * 1024 } // 15 MB limit
});

// Paths to JSON data files
const dataDir = path.join(__dirname, '../data');
const brosurPath = path.join(dataDir, 'brosur.json');
const newsPath = path.join(dataDir, 'news.json');
const testimonialsPath = path.join(dataDir, 'testimonials.json');
const ppdbLeadsPath = path.join(dataDir, 'ppdb_leads.json');
const majorsPath = path.join(dataDir, 'majors.json');
const labsPath = path.join(dataDir, 'labs.json');

// Helper functions for JSON read/write
function readJSON(filePath, defaultValue = []) {
  try {
    if (fs.existsSync(filePath)) {
      return JSON.parse(fs.readFileSync(filePath, 'utf8'));
    }
  } catch (err) {
    console.error('Error reading JSON:', filePath, err);
  }
  return defaultValue;
}

function writeJSON(filePath, data) {
  try {
    fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
    return true;
  } catch (err) {
    console.error('Error writing JSON:', filePath, err);
    return false;
  }
}

// Authentication Middleware
function requireAdminAuth(req, res, next) {
  if (req.session && req.session.isAdmin) {
    return next();
  }
  res.redirect('/admin/login');
}

// ==========================================
// ADMIN LOGIN & LOGOUT ROUTES
// ==========================================

router.get('/login', (req, res) => {
  if (req.session && req.session.isAdmin) {
    return res.redirect('/admin');
  }
  res.render('admin/login', { error: null });
});

router.post('/login', (req, res) => {
  const { username, password } = req.body;
  const settingsPath = path.join(__dirname, '../data/settings.json');
  let validUser = 'admin';
  let validPass = 'adminteratai3';
  if (fs.existsSync(settingsPath)) {
    const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
    if (settings.adminUsername) validUser = settings.adminUsername;
    if (settings.adminPassword) validPass = settings.adminPassword;
  }
  
  if (username === validUser && password === validPass) {
    req.session.isAdmin = true;
    req.session.adminUser = username;
    return res.redirect('/admin');
  }
  res.render('admin/login', { error: 'Username atau password salah! Silakan coba lagi.' });
});

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

// Protect all remaining admin routes
router.use(requireAdminAuth);

// ==========================================
// ADMIN DASHBOARD OVERVIEW
// ==========================================
router.get('/', (req, res) => {
  const news = readJSON(newsPath);
  const leads = readJSON(ppdbLeadsPath);
  const testimonials = readJSON(testimonialsPath);
  const brosur = readJSON(brosurPath, {});

  res.render('admin/dashboard', {
    activeTab: 'dashboard',
    stats: {
      totalNews: news.length,
      totalLeads: leads.length,
      totalReviews: testimonials.length,
      brosur: brosur
    },
    recentLeads: leads.slice(-5).reverse(),
    adminUser: req.session.adminUser || 'Admin Sekolah'
  });
});

// ==========================================
// CONTENT & MEDIA MANAGEMENT
// ==========================================
router.get('/content', (req, res) => {
  const idLocale = readJSON(path.join(__dirname, '../locales/id.json'));
  const enLocale = readJSON(path.join(__dirname, '../locales/en.json'));
  const settings = readJSON(path.join(__dirname, '../data/settings.json'));

  res.render('admin/content', {
    activeTab: 'content',
    idLocale,
    enLocale,
    settings,
    message: req.query.msg || null
  });
});

const translate = require('translate-google');

router.post('/content/text', async (req, res) => {
  const { lang, data } = req.body;
  
  if (lang === 'id' && data) {
    const idLocalePath = path.join(__dirname, '../locales/id.json');
    const enLocalePath = path.join(__dirname, '../locales/en.json');
    try {
      const parsedData = JSON.parse(data);
      
      // Save ID
      writeJSON(idLocalePath, parsedData);
      
      // Auto translate to EN by chunking (per section) to avoid payload limits
      const translatedData = {};
      for (const section of Object.keys(parsedData)) {
        try {
          // Add a small artificial delay to avoid rate limits
          await new Promise(r => setTimeout(r, 500));
          translatedData[section] = await translate(parsedData[section], { from: 'id', to: 'en' });
        } catch (err) {
          console.error(`Failed to translate section ${section}:`, err.message);
          // Fallback to original text if translation fails
          translatedData[section] = parsedData[section];
        }
      }
      
      writeJSON(enLocalePath, translatedData);
      
      return res.json({ success: true, message: 'Teks ID berhasil disimpan dan diterjemahkan otomatis ke EN!' });
    } catch (e) {
      console.error('Translation error:', e);
      return res.status(400).json({ success: false, message: 'Gagal menyimpan atau menerjemahkan: ' + e.message });
    }
  }
  
  // If english is posted directly (fallback)
  if (lang === 'en' && data) {
     return res.json({ success: true }); 
  }
  
  res.status(400).json({ success: false, message: 'Missing data' });
});

router.post('/content/photo', upload.single('photoFile'), (req, res) => {
  const { imageKey, redirectUrl } = req.body;
  const redirectTarget = redirectUrl || '/admin/content';
  
  if (!imageKey) {
    return res.redirect(`${redirectTarget}?msg=Kunci gambar tidak ditemukan`);
  }

  if (req.file) {
    const settingsPath = path.join(__dirname, '../data/settings.json');
    let settings = readJSON(settingsPath, { images: {} });
    
    // Construct the public URL for the uploaded file
    const publicUrl = '/uploads/' + req.file.filename;
    
    if (!settings.images) settings.images = {};
    settings.images[imageKey] = publicUrl;
    
    writeJSON(settingsPath, settings);
    return res.redirect(`${redirectTarget}?msg=Foto berhasil diperbarui!`);
  }
  
  res.redirect(`${redirectTarget}?msg=Tidak ada file yang diunggah`);
});

// ==========================================
// BROSUR MANAGEMENT (GANTI BROSUR)
// ==========================================
router.get('/brosur', (req, res) => {
  const brosur = readJSON(brosurPath, {
    title: 'Brosur PPDB SMK Teratai Putih Global 3 Bekasi 2026/2027',
    filename: 'Brosur_SMK_Teratai_Putih_Global_3_Bekasi.pdf',
    filePath: '/uploads/brosur.pdf',
    fileSize: '2.4 MB',
    lastUpdated: '2026-08-02',
    downloadCount: 0
  });

  res.render('admin/brosur', {
    activeTab: 'brosur',
    brosur,
    message: req.query.msg || null
  });
});

router.post('/brosur/update', upload.single('brosurFile'), (req, res) => {
  const { title } = req.body;
  let brosurData = readJSON(brosurPath, {});

  brosurData.title = title || brosurData.title || 'Brosur PPDB SMK Teratai Putih Global 3 Bekasi';
  brosurData.lastUpdated = new Date().toISOString().split('T')[0];

  if (req.file) {
    const stats = fs.statSync(req.file.path);
    const sizeInMB = (stats.size / (1024 * 1024)).toFixed(2) + ' MB';
    brosurData.filename = req.file.originalname;
    brosurData.filePath = '/uploads/brosur.pdf';
    brosurData.fileSize = sizeInMB;
  }

  writeJSON(brosurPath, brosurData);
  res.redirect('/admin/brosur?msg=Brosur berhasil diperbarui!');
});

// ==========================================
// BERITA MANAGEMENT (NEWS CMS)
// ==========================================
router.get('/berita', (req, res) => {
  const news = readJSON(newsPath);
  res.render('admin/berita', {
    activeTab: 'berita',
    news,
    message: req.query.msg || null
  });
});

router.post('/berita/add', upload.fields([
  { name: 'imageFile', maxCount: 1 },
  { name: 'galleryFiles', maxCount: 20 }
]), async (req, res) => {
  const { title, category, summary, content, author } = req.body;
  const news = readJSON(newsPath);
  
  // Thumbnail image
  let image = 'https://images.unsplash.com/photo-1517245386807-bb43f82c33c4?auto=format&fit=crop&w=800&q=80';
  if (req.files && req.files['imageFile'] && req.files['imageFile'][0]) {
    image = '/uploads/' + req.files['imageFile'][0].filename;
  } else if (req.body.imageUrl && req.body.imageUrl.trim() !== '') {
    image = req.body.imageUrl;
  }

  // Gallery images (array of URLs)
  let gallery = [];
  if (req.files && req.files['galleryFiles']) {
    gallery = req.files['galleryFiles'].map(f => '/uploads/' + f.filename);
  }

  const id = 'news-' + Date.now();
  const date = new Date().toISOString().split('T')[0];

  // Auto-translate to English
  let title_en = title;
  let summary_en = summary;
  let content_en = content;
  try {
    [title_en, summary_en, content_en] = await Promise.all([
      translate(title, { from: 'id', to: 'en' }),
      translate(summary, { from: 'id', to: 'en' }),
      translate(content, { from: 'id', to: 'en' })
    ]);
  } catch (err) {
    console.error('Auto-translate news failed:', err.message);
  }

  const newArticle = {
    id,
    title,
    title_en,
    category,
    date,
    author: author || 'Admin Humas SMK TPG 3',
    image,
    gallery,
    summary,
    summary_en,
    content,
    content_en
  };

  news.unshift(newArticle);
  writeJSON(newsPath, news);
  res.redirect('/admin/berita?msg=Artikel Berita berhasil ditambahkan dan diterjemahkan otomatis!');
});


router.post('/berita/delete/:id', (req, res) => {
  let news = readJSON(newsPath);
  news = news.filter(item => item.id !== req.params.id);
  writeJSON(newsPath, news);
  res.redirect('/admin/berita?msg=Artikel Berita berhasil dihapus!');
});

// ==========================================
// ULASAN GOOGLE MAPS MANAGEMENT (REVIEWS CMS)
// ==========================================
router.get('/ulasan', (req, res) => {
  const testimonials = readJSON(testimonialsPath);
  res.render('admin/ulasan', {
    activeTab: 'ulasan',
    testimonials,
    message: req.query.msg || null
  });
});

router.post('/ulasan/add', (req, res) => {
  const { name, role, timeAgo, rating, quote, reviewUrl } = req.body;
  const testimonials = readJSON(testimonialsPath);

  const initial = name ? name.charAt(0).toUpperCase() : 'G';
  const colors = ['#E91E63', '#00897B', '#795548', '#1976D2', '#9C27B0', '#FF9800'];
  const bgColor = colors[Math.floor(Math.random() * colors.length)];

  const newReview = {
    name,
    role: role || 'Local Guide • Google Verified',
    timeAgo: timeAgo || 'Baru saja',
    rating: parseInt(rating) || 5,
    initial,
    bgColor,
    quote,
    reviewUrl: reviewUrl || 'https://maps.app.goo.gl/17ndHiWWaSsjseUe7'
  };

  testimonials.unshift(newReview);
  writeJSON(testimonialsPath, testimonials);
  res.redirect('/admin/ulasan?msg=Ulasan Google Maps berhasil ditambahkan!');
});

router.post('/ulasan/delete/:index', (req, res) => {
  let testimonials = readJSON(testimonialsPath);
  const index = parseInt(req.params.index);
  if (index >= 0 && index < testimonials.length) {
    testimonials.splice(index, 1);
    writeJSON(testimonialsPath, testimonials);
  }
  res.redirect('/admin/ulasan?msg=Ulasan berhasil dihapus!');
});

// ==========================================
// PPDB LEADS MANAGEMENT
// ==========================================
router.get('/ppdb-leads', (req, res) => {
  const leads = readJSON(ppdbLeadsPath);
  res.render('admin/ppdb-leads', {
    activeTab: 'ppdb-leads',
    leads: leads.reverse(),
    message: req.query.msg || null
  });
});

router.get('/ppdb-leads/export', (req, res) => {
  const leads = readJSON(ppdbLeadsPath);
  let csv = 'ID Registrasi,Waktu Pendaftaran,Nama Lengkap Siswa,SMP/MTs Asal,Jurusan Pilihan,Jenis Kelamin,No WhatsApp,Email,Alamat Rumah,Status\n';
  leads.forEach(l => {
    const nama = l.fullname || l.nama || '-';
    const sekolah = l.school_origin || l.asalSekolah || '-';
    const jurusan = l.major || l.pilihanJurusan || '-';
    const gender = l.gender || l.jenisKelamin || '-';
    const alamat = l.address || l.alamat || '-';
    const tanggal = l.date || l.registeredAt || '-';
    const wa = l.whatsapp || '-';
    const email = l.email || '-';
    const status = l.status || 'Baru';

    csv += `"${l.id}","${tanggal}","${nama}","${sekolah}","${jurusan}","${gender}","${wa}","${email}","${alamat.replace(/"/g, '""')}","${status}"\n`;
  });

  res.setHeader('Content-Type', 'text/csv');
  res.setHeader('Content-Disposition', 'attachment; filename="data-pendaftar-ppdb-smk-teratai-putih-3.csv"');
  res.status(200).send(csv);
});

router.post('/ppdb-leads/status', (req, res) => {
  const { leadId, status } = req.body;
  if (!leadId || !status) return res.redirect('/admin/ppdb-leads?msg=Gagal mengubah status');
  
  let leads = readJSON(ppdbLeadsPath);
  let updated = false;
  
  leads = leads.map(l => {
    if (l.id === leadId) {
      l.status = status;
      updated = true;
    }
    return l;
  });
  
  if (updated) {
    writeJSON(ppdbLeadsPath, leads);
    return res.redirect('/admin/ppdb-leads?msg=Status berhasil diperbarui');
  }
  
  res.redirect('/admin/ppdb-leads?msg=Data tidak ditemukan');
});

router.post('/ppdb-leads/delete', (req, res) => {
  const { leadId } = req.body;
  if (!leadId) return res.redirect('/admin/ppdb-leads?msg=Gagal menghapus data');
  
  let leads = readJSON(ppdbLeadsPath);
  const initialLength = leads.length;
  
  leads = leads.filter(l => l.id !== leadId);
  
  if (leads.length !== initialLength) {
    writeJSON(ppdbLeadsPath, leads);
    return res.redirect('/admin/ppdb-leads?msg=Data pendaftar berhasil dihapus');
  }
  
  res.redirect('/admin/ppdb-leads?msg=Data tidak ditemukan');
});

// ==========================================
// PENGATURAN SISTEM
// ==========================================
router.get('/settings', (req, res) => {
  const settingsPath = path.join(__dirname, '../data/settings.json');
  let settings = { images: {} };
  if (fs.existsSync(settingsPath)) {
    settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
  }
  res.render('admin/settings', {
    activeTab: 'settings',
    settings: settings,
    message: req.query.msg || null
  });
});

router.post('/settings/credentials', (req, res) => {
  const { adminUsername, adminPassword } = req.body;
  if (!adminUsername || !adminPassword) {
    return res.redirect('/admin/settings?msg=Username dan Password tidak boleh kosong');
  }
  
  const settingsPath = path.join(__dirname, '../data/settings.json');
  let settings = {};
  if (fs.existsSync(settingsPath)) {
    settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
  }
  
  settings.adminUsername = adminUsername;
  settings.adminPassword = adminPassword;
  writeJSON(settingsPath, settings);
  
  // Re-login user after changing credentials
  req.session.adminUser = adminUsername;
  
  res.redirect('/admin/settings?msg=Kredensial berhasil diperbarui. Silakan gunakan kredensial baru ini untuk login selanjutnya.');
});

router.post('/settings/whatsapp', (req, res) => {
  let { adminWhatsapp } = req.body;
  
  if (adminWhatsapp) {
    // Basic sanitization: remove +, spaces, and dashes
    adminWhatsapp = adminWhatsapp.replace(/[\+\s\-]/g, '');
    
    // Ensure it starts with 62 instead of 0
    if (adminWhatsapp.startsWith('0')) {
      adminWhatsapp = '62' + adminWhatsapp.substring(1);
    }
    
    const settingsPath = path.join(__dirname, '../data/settings.json');
    let settings = {};
    if (fs.existsSync(settingsPath)) {
      settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
    }
    
    settings.adminWhatsapp = adminWhatsapp;
    writeJSON(settingsPath, settings);
    
    return res.redirect('/admin/settings?msg=Nomor WhatsApp berhasil diperbarui.');
  }
  
  res.redirect('/admin/settings?msg=Nomor WhatsApp tidak valid.');
});

module.exports = router;

