require('dotenv').config();
const express = require('express');
const axios = require('axios');
const path = require('path');

const app = express();
const port = 3000;

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));


function getFormattedDate() {
    const now = new Date();
    return now.toLocaleString('id-ID', {
        timeZone: 'Asia/Jakarta', // Zona waktu Surabaya adalah Asia/Jakarta (WIB)
        year: 'numeric',
        month: 'long',
        day: 'numeric'
    });
}


function getFormattedTimeOnly() {
    const now = new Date();
    return now.toLocaleString('id-ID', {
        timeZone: 'Asia/Jakarta', // Zona waktu Surabaya adalah Asia/Jakarta (WIB)
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
}


async function sendTelegramMessage(messageText, res, viewName, successMsg, errorMsg) {
    const TELEGRAM_BOT_TOKEN = process.env.TELEGRAM_BOT_TOKEN;
    const TELEGRAM_CHAT_ID = process.env.TELEGRAM_CHAT_ID;

    if (!TELEGRAM_BOT_TOKEN || !TELEGRAM_CHAT_ID) {
        console.error('Error: TELEGRAM_BOT_TOKEN atau TELEGRAM_CHAT_ID belum diset di .env');
        return res.render(viewName, { message: 'Konfigurasi bot notifikasi belum lengkap. Mohon hubungi administrator.', type: 'error' });
    }

    try {
        await axios.post(`https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage`, {
            chat_id: TELEGRAM_CHAT_ID,
            text: messageText,
            parse_mode: 'Markdown' 
        });
        res.render(viewName, { message: successMsg, type: 'success' });
    } catch (error) {
        console.error('Error mengirim pesan ke Telegram:', error.response ? error.response.data : error.message);
        res.render(viewName, { message: errorMsg, type: 'error' });
    }
}


app.get('/', (req, res) => {
    res.render('index', { message: null, type: null });
});


app.get('/request/web', (req, res) => {
    res.render('request_web', { message: null, type: null });
});


app.post('/submit-request-web', async (req, res) => {
    const {
        nama,
        projectType,
        requestWebDetail
    } = req.body;

    const pengirim = nama ? nama.trim() : '*Anonim*';
    const jenisProyek = projectType ? projectType.trim() : '_Tidak Disebutkan_';

    if (!requestWebDetail || !requestWebDetail.trim()) {
        return res.render('request_web', { message: 'Mohon jelaskan detail permintaan website Anda!', type: 'error' });
    }

    let messageText = `✨🌐 *PERMINTAAN WEBSITE BARU* 🌐✨\n`;
    messageText += `━━━━━━━━━━━━━━━━━━━━━━━\n`;
    messageText += `*👤 Pengirim:* ${pengirim}\n`;
    messageText += `*📅 Tanggal:* ${getFormattedDate()}\n`;
    messageText += `*⏰ Waktu:* ${getFormattedTimeOnly()} WIB\n`;
    messageText += `*📌 Kategori:* ${jenisProyek}\n`;
    messageText += `━━━━━━━━━━━━━━━━━━━━━━━\n\n`;
    messageText += `*📝 Detail Permintaan Website:*\n`;
    messageText += `\`\`\`\n${requestWebDetail.trim()}\n\`\`\`\n`;
    messageText += `━━━━━━━━━━━━━━━━━━━━━━━\n`;
    messageText += `_Mohon segera tinjau dan tindak lanjuti._`;

    await sendTelegramMessage(
        messageText,
        res,
        'request_web',
        '✅ Permintaan website Anda telah berhasil terkirim! Terima kasih atas informasinya. Kami akan segera meninjaunya.',
        '❌ Maaf, terjadi kesalahan saat mengirim permintaan website. Silakan coba lagi nanti.'
    );
});



app.get('/request/wabot', (req, res) => {
    res.render('request_wabot', { message: null, type: null });
});


app.post('/submit-request-wabot', async (req, res) => {
    const {
        nama,
        featureTypes, 
        requestWaBotDetail, 
        waBotApiLink        
    } = req.body;

    const pengirim = nama ? nama.trim() : '*Anonim*';

    if (!requestWaBotDetail || !requestWaBotDetail.trim()) {
        return res.render('request_wabot', { message: 'Mohon jelaskan deskripsi fitur baru yang Anda inginkan!', type: 'error' });
    }

    let messageText = `⚙️ *PERMINTAAN FITUR BOT BARU* ⚙️\n`;
    messageText += `━━━━━━━━━━━━━━━━━━━━━━━\n`;
    messageText += `*👤 Pengirim:* ${pengirim}\n`;
    messageText += `*📅 Tanggal:* ${getFormattedDate()}\n`;
    messageText += `*⏰ Waktu:* ${getFormattedTimeOnly()} WIB\n`;
    messageText += `━━━━━━━━━━━━━━━━━━━━━━━\n\n`;

    
    let selectedFeatureTypes = [];
    if (Array.isArray(featureTypes)) {
        selectedFeatureTypes = featureTypes;
    } else if (typeof featureTypes === 'string' && featureTypes.trim() !== '') {
        selectedFeatureTypes.push(featureTypes.trim());
    }
    
    const featureInfo = selectedFeatureTypes.length > 0 ? 
                        `Tipe Fitur/Plugin: *${selectedFeatureTypes.join('*, *')}*` : 
                        '_Tidak ada tipe fitur/plugin yang spesifik._';
    messageText += `*💡 ${featureInfo}*\n\n`; 


    messageText += `*📝 Deskripsi Fitur Baru:*\n`;
    messageText += `\`\`\`\n${requestWaBotDetail.trim()}\n\`\`\`\n`;
    
    if (waBotApiLink && waBotApiLink.trim()) {
        messageText += `\n*🔗 Dokumentasi API / Referensi:*\n`;
        messageText += `\`\`\`\n${waBotApiLink.trim()}\n\`\`\`\n`;
    }
    
    messageText += `━━━━━━━━━━━━━━━━━━━━━━━\n`;
    messageText += `_Mohon segera tinjau dan tindak lanjuti permintaan fitur ini._`;

    await sendTelegramMessage(
        messageText,
        res,
        'request_wabot',
        '✅ Permintaan fitur bot Anda telah berhasil terkirim! Terima kasih atas informasinya. Kami akan segera meninjaunya.',
        '❌ Maaf, terjadi kesalahan saat mengirim permintaan fitur bot. Silakan coba lagi nanti.'
    );
});



app.get('/feedback', (req, res) => {
    res.render('feedback', { message: null, type: null });
});


app.post('/submit-feedback', async (req, res) => {
    const {
        nama,
        kritikSaranDetail
    } = req.body;

    const pengirim = nama ? nama.trim() : '*Anonim*';

    if (!kritikSaranDetail || !kritikSaranDetail.trim()) {
        return res.render('feedback', { message: 'Mohon isi detail kritik atau saran Anda!', type: 'error' });
    }

    let messageText = `💬💡 *KRITIK & SARAN BARU* 💡💬\n`;
    messageText += `━━━━━━━━━━━━━━━━━━━━━━━\n`;
    messageText += `*👤 Pengirim:* ${pengirim}\n`;
    messageText += `*📅 Tanggal:* ${getFormattedDate()}\n`;
    messageText += `*⏰ Waktu:* ${getFormattedTimeOnly()} WIB\n`;
    messageText += `━━━━━━━━━━━━━━━━━━━━━━━\n\n`;
    
    messageText += `*📝 Detail Kritik / Saran:*\n`;
    messageText += `\`\`\`\n${kritikSaranDetail.trim()}\n\`\`\`\n`;
    
    messageText += `━━━━━━━━━━━━━━━━━━━━━━━\n`;
    messageText += `_Terima kasih atas masukan berharga ini. Akan kami pertimbangkan._`;

    await sendTelegramMessage(
        messageText,
        res,
        'feedback',
        '✅ Kritik atau saran Anda telah berhasil terkirim! Terima kasih atas masukan Anda.',
        '❌ Maaf, terjadi kesalahan saat mengirim kritik/saran. Silakan coba lagi nanti.'
    );
});


app.listen(port, () => {
    console.log(`Aplikasi web berjalan di http://localhost:${port}`);
});