#!/bin/bash

# Create auth routes
cat > routes/auth.js << 'EOF'
const express = require('express');
const bcrypt = require('bcrypt');
const { query } = require('../config/database');
const { redirectIfAuth } = require('../middleware/auth');
const router = express.Router();

router.get('/login', redirectIfAuth, (req, res) => {
  res.render('admin/login', {
    error: req.query.error,
    title: 'Admin Login - SkyArtShop'
  });
});

router.post('/login', async (req, res) => {
  const { email, password } = req.body;
  try {
    const result = await query(
      'SELECT id, email, name, password, role FROM adminusers WHERE email = $1',
      [email]
    );
    if (result.rows.length === 0) {
      return res.redirect('/admin/login?error=invalid');
    }
    const admin = result.rows[0];
    const validPassword = await bcrypt.compare(password, admin.password);
    if (!validPassword) {
      return res.redirect('/admin/login?error=invalid');
    }
    await query('UPDATE adminusers SET lastlogin = NOW() WHERE id = $1', [admin.id]);
    req.session.adminId = admin.id;
    req.session.email = admin.email;
    req.session.name = admin.name;
    req.session.role = admin.role;
    res.redirect('/admin/dashboard');
  } catch (error) {
    console.error('Login error:', error);
    res.redirect('/admin/login?error=server');
  }
});

router.get('/logout', (req, res) => {
  req.session.destroy((err) => {
    if (err) console.error('Logout error:', err);
    res.redirect('/admin/login');
  });
});

module.exports = router;
EOF

# Create admin routes
cat > routes/admin.js << 'EOF'
const express = require('express');
const { query } = require('../config/database');
const { requireAuth } = require('../middleware/auth');
const router = express.Router();

router.get('/dashboard', requireAuth, async (req, res) => {
  try {
    const productsCount = await query('SELECT COUNT(*) FROM products');
    const ordersCount = await query('SELECT COUNT(*) FROM orders');
    const usersCount = await query('SELECT COUNT(*) FROM appusers');
    const pagesCount = await query('SELECT COUNT(*) FROM pages');
    const recentOrders = await query(
      'SELECT id, ordernumber, totalamount, status, createdat FROM orders ORDER BY createdat DESC LIMIT 5'
    );
    res.render('admin/dashboard', {
      title: 'Dashboard - SkyArtShop Admin',
      user: req.session,
      stats: {
        products: productsCount.rows[0].count,
        orders: ordersCount.rows[0].count,
        users: usersCount.rows[0].count,
        pages: pagesCount.rows[0].count
      },
      recentOrders: recentOrders.rows
    });
  } catch (error) {
    console.error('Dashboard error:', error);
    res.status(500).send('Server error');
  }
});

router.get('/products', requireAuth, async (req, res) => {
  try {
    const result = await query(
      'SELECT id, name, price, stockquantity, isactive, createdat FROM products ORDER BY createdat DESC'
    );
    res.render('admin/products', {
      title: 'Products - SkyArtShop Admin',
      user: req.session,
      products: result.rows
    });
  } catch (error) {
    console.error('Products error:', error);
    res.status(500).send('Server error');
  }
});

router.get('/orders', requireAuth, async (req, res) => {
  try {
    const result = await query(
      'SELECT id, ordernumber, totalamount, status, createdat FROM orders ORDER BY createdat DESC'
    );
    res.render('admin/orders', {
      title: 'Orders - SkyArtShop Admin',
      user: req.session,
      orders: result.rows
    });
  } catch (error) {
    console.error('Orders error:', error);
    res.status(500).send('Server error');
  }
});

router.get('/users', requireAuth, async (req, res) => {
  try {
    const result = await query(
      'SELECT id, email, name, role, createdat, lastlogin FROM adminusers ORDER BY createdat DESC'
    );
    res.render('admin/users', {
      title: 'Admin Users - SkyArtShop Admin',
      user: req.session,
      users: result.rows
    });
  } catch (error) {
    console.error('Users error:', error);
    res.status(500).send('Server error');
  }
});

module.exports = router;
EOF

# Create public routes
cat > routes/public.js << 'EOF'
const express = require('express');
const { query } = require('../config/database');
const router = express.Router();

router.get('/', async (req, res) => {
  try {
    const products = await query(
      'SELECT id, name, description, price, imageurl FROM products WHERE isactive = true ORDER BY createdat DESC LIMIT 8'
    );
    const sections = await query(
      'SELECT * FROM homepagesections ORDER BY displayorder ASC'
    );
    res.render('public/home', {
      title: 'Welcome - SkyArtShop',
      products: products.rows,
      sections: sections.rows
    });
  } catch (error) {
    console.error('Home page error:', error);
    res.status(500).send('Server error');
  }
});

router.get('/shop', async (req, res) => {
  try {
    const products = await query(
      'SELECT id, name, description, price, imageurl, category FROM products WHERE isactive = true ORDER BY name ASC'
    );
    res.render('public/shop', {
      title: 'Shop - SkyArtShop',
      products: products.rows
    });
  } catch (error) {
    console.error('Shop page error:', error);
    res.status(500).send('Server error');
  }
});

module.exports = router;
EOF

# Create main server.js
cat > server.js << 'EOF'
const express = require('express');
const session = require('express-session');
const pgSession = require('connect-pg-simple')(session);
const path = require('path');
const { pool } = require('./config/database');
require('dotenv').config();

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

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

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use('/assets', express.static(path.join(__dirname, '../wwwroot/assets')));
app.use('/uploads', express.static(path.join(__dirname, '../wwwroot/uploads')));

app.use(session({
  store: new pgSession({
    pool: pool,
    tableName: 'session',
    createTableIfMissing: true
  }),
  secret: process.env.SESSION_SECRET || 'skyart-shop-secret-2025',
  resave: false,
  saveUninitialized: false,
  cookie: {
    secure: false,
    httpOnly: true,
    maxAge: 24 * 60 * 60 * 1000
  }
}));

app.use((req, res, next) => {
  res.locals.session = req.session;
  res.locals.currentPath = req.path;
  next();
});

const authRoutes = require('./routes/auth');
const adminRoutes = require('./routes/admin');
const publicRoutes = require('./routes/public');

app.use('/admin', authRoutes);
app.use('/admin', adminRoutes);
app.use('/', publicRoutes);

app.get('/health', (req, res) => {
  res.json({ 
    status: 'ok', 
    timestamp: new Date().toISOString(),
    database: 'connected'
  });
});

app.use((req, res) => {
  res.status(404).render('public/404', {
    title: '404 - Page Not Found'
  });
});

app.use((err, req, res, next) => {
  console.error('Error:', err);
  res.status(500).send('Server error');
});

app.listen(PORT, '0.0.0.0', () => {
  console.log('========================================');
  console.log('  SkyArtShop Backend Server');
  console.log('========================================');
  console.log(`🚀 Server running on http://localhost:${PORT}`);
  console.log(`📦 Environment: ${process.env.NODE_ENV || 'development'}`);
  console.log(`🗄️  Database: PostgreSQL (${process.env.DB_NAME})`);
  console.log('========================================');
});

process.on('SIGTERM', () => {
  console.log('SIGTERM received, closing server...');
  pool.end(() => {
    console.log('Database pool closed');
    process.exit(0);
  });
});
EOF

echo "✓ Server files created"
