// server.js
const express = require('express');
const mysql = require('mysql2');
const cors = require('cors');
const bodyParser = require('body-parser');
require('dotenv').config();

const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(express.static(__dirname));

// Create MySQL connection
const db = mysql.createConnection({
    host: process.env.DB_HOST || 'localhost',
    user: process.env.DB_USER || 'root',
    password: process.env.DB_PASSWORD || '',
    database: process.env.DB_NAME || 'spbu_gis',
    port: process.env.DB_PORT || 3306
});


db.connect(err => {
    if (err) {
        console.error('Database connection failed: ' + err.stack);
        return;
    }
    console.log('Connected to MySQL database.');
});

// GET route to fetch all SPBU locations
app.get('/api/spbus', (req, res) => {
    db.query('SELECT * FROM locations', (err, results) => {
        if (err) throw err;
        res.json(results);
    });
});

// POST route to save a new SPBU location
app.post('/api/spbus', (req, res) => {
    const { name, open_window, spbu_number, lat, lng } = req.body;
    
    const query = 'INSERT INTO locations (name, open_window, spbu_number, lat, lng) VALUES (?, ?, ?, ?, ?)';
    db.query(query, [name, open_window, spbu_number, lat, lng], (err, result) => {
        if (err) throw err;
        res.json({ message: 'SPBU saved successfully!', id: result.insertId });
    });
});

// PUT route to update an SPBU location
app.put('/api/spbus/:id', (req, res) => {
    const { id } = req.params;
    const { name, open_window, spbu_number, lat, lng } = req.body;
    
    const query = 'UPDATE locations SET name = ?, open_window = ?, spbu_number = ?, lat = ?, lng = ? WHERE id = ?';
    db.query(query, [name, open_window, spbu_number, lat, lng, id], (err, result) => {
        if (err) throw err;
        res.json({ message: 'SPBU updated successfully!' });
    });
});

// DELETE route to delete an SPBU location
app.delete('/api/spbus/:id', (req, res) => {
    const { id } = req.params;
    
    const query = 'DELETE FROM locations WHERE id = ?';
    db.query(query, [id], (err, result) => {
        if (err) throw err;
        res.json({ message: 'SPBU deleted successfully!' });
    });
});

// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
});