const express = require('express');
const path = require('path');
const fs = require('fs');
const cors = require('cors');

const cookieParser = require('cookie-parser');
const session = require('express-session');
const adminRouter = require('./routes/admin');

const app = express();
const PORT = process.env.PORT || 3005;

// Middleware
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(session({
  secret: 'smk-teratai-putih-3-secret-key-2026',
  resave: false,
  saveUninitialized: false,
  cookie: { maxAge: 24 * 60 * 60 * 1000 } // 24 hours
}));
app.use(express.static(path.join(__dirname, 'public')));

// i18n Middleware
app.use((req, res, next) => {
  // Read locales dynamically to reflect CMS changes immediately
  let idLocale = {};
  let enLocale = {};
  try {
    idLocale = JSON.parse(fs.readFileSync(path.join(__dirname, 'locales', 'id.json'), 'utf8'));
    enLocale = JSON.parse(fs.readFileSync(path.join(__dirname, 'locales', 'en.json'), 'utf8'));
  } catch (err) {
    console.error('Error reading locales:', err);
  }

  // Exclude admin routes from i18n language toggle if necessary, or just apply globally
  const lang = req.cookies.lang || 'id';
  res.locals.currentLang = lang;
  res.locals.t = lang === 'en' ? enLocale : idLocale;
  
  // Load Settings
  let settings = { images: {} };
  try {
    const settingsPath = path.join(__dirname, 'data', 'settings.json');
    if (fs.existsSync(settingsPath)) {
      settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
    }
  } catch (err) {
    console.error('Error reading settings.json:', err);
  }
  res.locals.settings = settings;

  next();
});

// Route to switch language
app.get('/set-lang/:lang', (req, res) => {
  const lang = req.params.lang === 'en' ? 'en' : 'id';
  res.cookie('lang', lang, { maxAge: 365 * 24 * 60 * 60 * 1000 }); // 1 year
  res.redirect(req.get('Referrer') || '/');
});

// Mount CMS Admin Router
app.use('/admin', adminRouter);

// Set View Engine to EJS
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

// Helper function to read JSON data safely
const readJsonData = (filename) => {
  try {
    const filePath = path.join(__dirname, 'data', filename);
    if (!fs.existsSync(filePath)) return [];
    const content = fs.readFileSync(filePath, 'utf8');
    return JSON.parse(content);
  } catch (err) {
    console.error(`Error reading ${filename}:`, err);
    return [];
  }
};

// Helper function to write JSON data safely
const writeJsonData = (filename, data) => {
  try {
    const filePath = path.join(__dirname, 'data', filename);
    fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8');
    return true;
  } catch (err) {
    console.error(`Error writing ${filename}:`, err);
    return false;
  }
};

// --- ROUTES ---

// 1. Home Page (Beranda)
app.get('/', (req, res) => {
  const news = readJsonData('news.json');
  const labs = readJsonData('labs.json');
  const majors = readJsonData('majors.json');
  const testimonials = readJsonData('testimonials.json');

  res.render('index', {
    title: 'Beranda | SMK Teratai Putih Global 3 Bekasi',
    currentPage: 'beranda',
    news: news.slice(0, 3),
    labs: labs,
    majors: majors,
    testimonials: testimonials
  });
});

// 2. School Profile Page (Profil Sekolah)
app.get('/profil', (req, res) => {
  res.render('profil', {
    title: 'Profil Sekolah | SMK Teratai Putih Global 3 Bekasi',
    currentPage: 'profil'
  });
});

// 3. Majors & Industry Class Page (Jurusan & Kelas Industri)
app.get('/jurusan', (req, res) => {
  const majors = readJsonData('majors.json');
  const selectedId = req.query.id || null;
  res.render('jurusan', {
    title: 'Program Keahlian & Kelas Industri | SMK Teratai Putih Global 3 Bekasi',
    currentPage: 'jurusan',
    majors: majors,
    selectedId: selectedId
  });
});

app.get('/jurusan/:id', (req, res) => {
  const majors = readJsonData('majors.json');
  const majorId = req.params.id;
  res.render('jurusan', {
    title: 'Program Keahlian | SMK Teratai Putih Global 3 Bekasi',
    currentPage: 'jurusan',
    majors: majors,
    selectedId: majorId
  });
});

// 4. Lab Facilities Page (Fasilitas Lab Komputer)
app.get('/fasilitas-lab', (req, res) => {
  const labs = readJsonData('labs.json');
  const activeLabId = req.query.lab || 'all';
  res.render('lab', {
    title: 'Fasilitas Laboratorium Komputer | SMK Teratai Putih Global 3 Bekasi',
    currentPage: 'fasilitas-lab',
    labs: labs,
    activeLabId: activeLabId
  });
});

// 5. News & Announcements Page (Berita & Pengumuman)
app.get('/berita', (req, res) => {
  let newsList = readJsonData('news.json');
  const query = (req.query.q || '').trim().toLowerCase();
  const category = (req.query.category || 'semua').toLowerCase();

  if (category !== 'semua') {
    newsList = newsList.filter(item => item.category.toLowerCase() === category);
  }

  if (query) {
    newsList = newsList.filter(item => 
      item.title.toLowerCase().includes(query) || 
      item.summary.toLowerCase().includes(query) ||
      item.content.toLowerCase().includes(query)
    );
  }

  res.render('berita', {
    title: 'Berita & Pengumuman | SMK Teratai Putih Global 3 Bekasi',
    currentPage: 'berita',
    newsList: newsList,
    searchQuery: req.query.q || '',
    activeCategory: category
  });
});

// 6. News Detail Page
app.get('/berita/:id', (req, res) => {
  const newsList = readJsonData('news.json');
  const article = newsList.find(n => n.id === req.params.id);

  if (!article) {
    return res.status(404).render('berita', {
      title: 'Artikel Tidak Ditemukan',
      currentPage: 'berita',
      newsList: newsList,
      searchQuery: '',
      activeCategory: 'semua'
    });
  }

  const related = newsList.filter(n => n.id !== article.id).slice(0, 3);

  res.render('berita-detail', {
    title: `${article.title} | SMK Teratai Putih Global 3 Bekasi`,
    currentPage: 'berita',
    article: article,
    related: related
  });
});

// 7. PPDB Online Page
app.get('/ppdb', (req, res) => {
  const majors = readJsonData('majors.json');
  res.render('ppdb', {
    title: 'PPDB Online 2026/2027 | SMK Teratai Putih Global 3 Bekasi',
    currentPage: 'ppdb',
    majors: majors
  });
});

// 8. Contact Page
app.get('/kontak', (req, res) => {
  res.render('kontak', {
    title: 'Kontak & Lokasi | SMK Teratai Putih Global 3 Bekasi',
    currentPage: 'kontak'
  });
});

// --- REST API ENDPOINTS ---

// API: PPDB Registration Form Submit
app.post('/api/ppdb/register', (req, res) => {
  const { nama, email, whatsapp, asalSekolah, pilihanJurusan, jenisKelamin, alamat } = req.body;

  if (!nama || !whatsapp || !asalSekolah || !pilihanJurusan) {
    return res.status(400).json({
      success: false,
      message: 'Mohon lengkapi semua kolom yang wajib diisi.'
    });
  }

  const leads = readJsonData('ppdb_leads.json');
  const dateStr = new Date().toLocaleString('id-ID', { timeZone: 'Asia/Jakarta' });
  const newLead = {
    id: 'REG-' + Date.now(),
    fullname: nama,
    nama: nama,
    email: email || '-',
    whatsapp: whatsapp,
    school_origin: asalSekolah,
    asalSekolah: asalSekolah,
    major: pilihanJurusan,
    pilihanJurusan: pilihanJurusan,
    gender: jenisKelamin || 'Laki-laki',
    jenisKelamin: jenisKelamin || 'Laki-laki',
    address: alamat || '-',
    alamat: alamat || '-',
    date: dateStr,
    registeredAt: dateStr,
    status: 'Baru'
  };

  leads.unshift(newLead);
  const isSaved = writeJsonData('ppdb_leads.json', leads);

  if (isSaved) {
    // Build pre-filled WhatsApp notification link for admin
    const settingsData = readJsonData('settings.json') || {};
    const adminWa = settingsData.adminWhatsapp || '6281234567890'; // ganti dengan nomor WA admin
    const waTextRaw = `[PPDB BARU] ${dateStr}\n\nNama: ${nama}\nSekolah Asal: ${asalSekolah}\nJurusan: ${pilihanJurusan}\nJenis Kelamin: ${jenisKelamin || '-'}\nWhatsApp: ${whatsapp}\nEmail: ${email || '-'}\n\nID: ${newLead.id}`;
    const adminNotifyLink = `https://wa.me/${adminWa}?text=${encodeURIComponent(waTextRaw)}`;

    return res.status(200).json({
      success: true,
      registrationId: newLead.id,
      adminNotifyLink,
      message: 'Pendaftaran awal PPDB berhasil dikirim! Tim Humas SMK Teratai Putih Global 3 Bekasi akan menghubungi Anda via WhatsApp/Email.'
    });
  } else {
    return res.status(500).json({
      success: false,
      message: 'Terjadi kesalahan sistem saat menyimpan data registration.'
    });
  }
});

// API: Get latest PPDB lead count (for admin real-time notification)
app.get('/api/ppdb/latest-count', (req, res) => {
  const leads = readJsonData('ppdb_leads.json');
  const latest = leads[0] || null;
  res.json({
    total: leads.length,
    latestId: latest ? latest.id : null,
    latestName: latest ? (latest.fullname || latest.nama) : null,
    latestTime: latest ? latest.date : null
  });
});

// API: Contact Form Submit
app.post('/api/kontak/send', (req, res) => {
  const { nama, email, subjek, pesan } = req.body;

  if (!nama || !email || !pesan) {
    return res.status(400).json({
      success: false,
      message: 'Mohon isi nama, email, dan pesan Anda.'
    });
  }

  return res.status(200).json({
    success: true,
    message: 'Terima kasih! Pesan Anda berhasil dikirim ke Humas SMK Teratai Putih Global 3 Bekasi.'
  });
});

// API: Check CBT Portal status & link integration
app.get('/api/cbt/status', (req, res) => {
  res.json({
    status: 'online',
    portalName: 'NK-CBT Sekolah Interaktif',
    studentUrl: 'http://cbt.smkterataiputihglobal3.sch.id/student',
    teacherUrl: 'http://cbt.smkterataiputihglobal3.sch.id/teacher',
    serverTime: new Date().toISOString()
  });
});

// Download Brochure Route
app.get('/download/brosur', (req, res) => {
  const uploadedPath = path.join(__dirname, 'public', 'uploads', 'brosur.pdf');
  const downloadsPath = path.join(__dirname, 'public', 'downloads', 'Brosur-SMK-Teratai-Putih-Global-3-Bekasi.pdf');
  
  if (fs.existsSync(uploadedPath)) {
    res.download(uploadedPath, 'Brosur-SMK-Teratai-Putih-Global-3-Bekasi.pdf');
  } else if (fs.existsSync(downloadsPath)) {
    res.download(downloadsPath);
  } else {
    // If PDF isn't present physically yet, stream a dynamically generated text file formatted as PDF info sheet
    res.setHeader('Content-Type', 'text/plain; charset=utf-8');
    res.setHeader('Content-Disposition', 'attachment; filename="Brosur-SMK-Teratai-Putih-Global-3-Bekasi.txt"');
    res.send(`=======================================================
BROSUR & PROFIL SEKOLAH - SMK TERATAI PUTIH GLOBAL 3 BEKASI
=======================================================
Alamat : Jl. Pengasinan No. 1, Rawalumbu, Kota Bekasi, Jawa Barat
Telepon: (021) 82422201 / WhatsApp: 0812-3456-7890
Website: https://smkterataiputihglobal3.sch.id

--- PROGRAM KEAHLIAN REGULER ---
1. TJKT (Teknik Jaringan Komputer dan Telekomunikasi)
2. AKL (Akuntansi dan Keuangan Lembaga)
3. MPLB (Manajemen Perkantoran dan Layanan Bisnis)

--- KELAS INDUSTRI / UNGGULAN ---
1. Axioo Class Program (Terintegrasi khusus pada Jurusan TJKT)

--- FASILITAS 4 LAB KOMPUTER RESMI ---
1. Lab Komputer TJKT (Praktik Jaringan, Mikrotik & Server Enterprise)
2. Lab Komputer Axioo Class (Praktik Perakitan, Hardware & Maintenance)
3. Lab Komputer AKL (Komputasi Akuntansi Accurate & MYOB)
4. Lab Komputer MPLB (Simulasi Perkantoran & Administrasi Digital)

--- INFORMASI PPDB 2026/2027 ---
Daftar secara online di website resmi atau hubungi Panitia PPDB.
Gelombang 1: Dapatkan Beasiswa Potongan Biaya Masuk!
=======================================================`);
  }
});

// 404 Error Handler
app.use((req, res) => {
  res.status(404).render('berita', {
    title: 'Halaman Tidak Ditemukan (404)',
    currentPage: '',
    newsList: [],
    searchQuery: '',
    activeCategory: 'semua'
  });
});

// Start Server
app.listen(PORT, () => {
  console.log(`==================================================`);
  console.log(`  SMK Teratai Putih Global 3 Bekasi Website Server`);
  console.log(`  Server running at http://localhost:${PORT}`);
  console.log(`==================================================`);
});
