const express = require('express');
const mysql = require('mysql2/promise');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const multer = require('multer');
const QRCode = require('qrcode');
const cors = require('cors');
const path = require('path');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 3000;
const JWT_SECRET = process.env.JWT_SECRET || 'tvoj-tajni-kljuc-PROMIJENI-ME';

// Database konfiguracija
const dbConfig = {
  host: process.env.DB_HOST || 'localhost',
  user: process.env.DB_USER || 'taptapcp_cardbazauser',
  password: process.env.DB_PASSWORD || '(bC.vE}JY.@G?xCl',
  database: process.env.DB_NAME || 'taptapcp_cardbaza',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
};

const pool = mysql.createPool(dbConfig);

// Middleware
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use('/uploads', express.static('uploads'));
app.use(express.static('public'));

// Multer config za upload slika
const storage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, 'uploads/'),
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, 'profile-' + uniqueSuffix + path.extname(file.originalname));
  }
});
const upload = multer({ 
  storage: storage,
  limits: { fileSize: 5 * 1024 * 1024 }, // 5MB limit
  fileFilter: (req, file, cb) => {
    const allowedTypes = /jpeg|jpg|png|gif/;
    const extname = allowedTypes.test(path.extname(file.originalname).toLowerCase());
    const mimetype = allowedTypes.test(file.mimetype);
    if (mimetype && extname) return cb(null, true);
    cb(new Error('Samo slike su dozvoljene!'));
  }
});

// Auth middleware
const authMiddleware = async (req, res, next) => {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(401).json({ error: 'Nedostaje token' });
  
  try {
    const decoded = jwt.verify(token, JWT_SECRET);
    req.adminId = decoded.id;
    next();
  } catch (error) {
    res.status(401).json({ error: 'Nevažeći token' });
  }
};

// ===== AUTH RUTE =====
// Login
app.post('/api/auth/login', async (req, res) => {
  const { username, password } = req.body;
  
  try {
    const [rows] = await pool.query('SELECT * FROM admin_users WHERE username = ?', [username]);
    if (rows.length === 0) return res.status(401).json({ error: 'Pogrešni podaci' });
    
    const admin = rows[0];
    const validPassword = await bcrypt.compare(password, admin.password);
    if (!validPassword) return res.status(401).json({ error: 'Pogrešni podaci' });
    
    const token = jwt.sign({ id: admin.id }, JWT_SECRET, { expiresIn: '24h' });
    res.json({ token, username: admin.username });
  } catch (error) {
    res.status(500).json({ error: 'Greška na serveru' });
  }
});

// ===== USER RUTE =====
// Dohvati sve korisnike (admin)
app.get('/api/users', authMiddleware, async (req, res) => {
  try {
    const [users] = await pool.query('SELECT * FROM users ORDER BY created_at DESC');
    res.json(users);
  } catch (error) {
    res.status(500).json({ error: 'Greška pri dohvaćanju korisnika' });
  }
});

// Dohvati jednog korisnika
app.get('/api/users/:slug', async (req, res) => {
  try {
    const [users] = await pool.query('SELECT * FROM users WHERE slug = ?', [req.params.slug]);
    if (users.length === 0) return res.status(404).json({ error: 'Korisnik nije pronađen' });
    
    const user = users[0];
    const [links] = await pool.query('SELECT * FROM links WHERE user_id = ? ORDER BY sort_order', [user.id]);
    const [modules] = await pool.query('SELECT * FROM modules WHERE user_id = ?', [user.id]);
    
    res.json({ ...user, links, modules });
  } catch (error) {
    res.status(500).json({ error: 'Greška pri dohvaćanju korisnika' });
  }
});

// Kreiraj novog korisnika
app.post('/api/users', authMiddleware, upload.single('slika'), async (req, res) => {
  const { slug, ime, prezime, opis, email, telefon, whatsapp } = req.body;
  const slika = req.file ? `/uploads/${req.file.filename}` : null;
  
  try {
    const [result] = await pool.query(
      'INSERT INTO users (slug, ime, prezime, opis, email, telefon, whatsapp, slika) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
      [slug, ime, prezime, opis, email, telefon, whatsapp, slika]
    );
    
    // Dodaj defaultne module
    const userId = result.insertId;
    const defaultModules = ['mapa', 'instagram_feed', 'vcard', 'qr_code'];
    for (const module of defaultModules) {
      await pool.query('INSERT INTO modules (user_id, modul_name, aktivan) VALUES (?, ?, false)', [userId, module]);
    }
    
    res.status(201).json({ id: userId, slug });
  } catch (error) {
    if (error.code === 'ER_DUP_ENTRY') {
      res.status(400).json({ error: 'Slug već postoji' });
    } else {
      res.status(500).json({ error: 'Greška pri kreiranju korisnika' });
    }
  }
});

// Ažuriraj korisnika
app.put('/api/users/:id', authMiddleware, upload.single('slika'), async (req, res) => {
  const { ime, prezime, opis, email, telefon, whatsapp } = req.body;
  const userId = req.params.id;
  
  try {
    let updateQuery = 'UPDATE users SET ime = ?, prezime = ?, opis = ?, email = ?, telefon = ?, whatsapp = ?';
    const params = [ime, prezime, opis, email, telefon, whatsapp];
    
    if (req.file) {
      updateQuery += ', slika = ?';
      params.push(`/uploads/${req.file.filename}`);
    }
    
    updateQuery += ' WHERE id = ?';
    params.push(userId);
    
    await pool.query(updateQuery, params);
    res.json({ message: 'Korisnik ažuriran' });
  } catch (error) {
    res.status(500).json({ error: 'Greška pri ažuriranju korisnika' });
  }
});

// Obriši korisnika
app.delete('/api/users/:id', authMiddleware, async (req, res) => {
  try {
    await pool.query('DELETE FROM users WHERE id = ?', [req.params.id]);
    res.json({ message: 'Korisnik obrisan' });
  } catch (error) {
    res.status(500).json({ error: 'Greška pri brisanju korisnika' });
  }
});

// ===== LINKS RUTE =====
// Dodaj link
app.post('/api/users/:userId/links', authMiddleware, async (req, res) => {
  const { tip, url, sort_order } = req.body;
  const userId = req.params.userId;
  
  try {
    const [result] = await pool.query(
      'INSERT INTO links (user_id, tip, url, sort_order) VALUES (?, ?, ?, ?)',
      [userId, tip, url, sort_order || 0]
    );
    res.status(201).json({ id: result.insertId });
  } catch (error) {
    res.status(500).json({ error: 'Greška pri dodavanju linka' });
  }
});

// Ažuriraj link
app.put('/api/links/:id', authMiddleware, async (req, res) => {
  const { tip, url, sort_order } = req.body;
  
  try {
    await pool.query('UPDATE links SET tip = ?, url = ?, sort_order = ? WHERE id = ?', [tip, url, sort_order, req.params.id]);
    res.json({ message: 'Link ažuriran' });
  } catch (error) {
    res.status(500).json({ error: 'Greška pri ažuriranju linka' });
  }
});

// Obriši link
app.delete('/api/links/:id', authMiddleware, async (req, res) => {
  try {
    await pool.query('DELETE FROM links WHERE id = ?', [req.params.id]);
    res.json({ message: 'Link obrisan' });
  } catch (error) {
    res.status(500).json({ error: 'Greška pri brisanju linka' });
  }
});

// ===== MODULE RUTE =====
// Ažuriraj modul
app.put('/api/modules/:id', authMiddleware, async (req, res) => {
  const { aktivan, config } = req.body;
  
  try {
    await pool.query('UPDATE modules SET aktivan = ?, config = ? WHERE id = ?', [aktivan, config, req.params.id]);
    res.json({ message: 'Modul ažuriran' });
  } catch (error) {
    res.status(500).json({ error: 'Greška pri ažuriranju modula' });
  }
});

// ===== QR KOD =====
app.get('/api/qr/:slug', async (req, res) => {
  const url = `https://card.taptap.ba/${req.params.slug}`;
  
  try {
    const qrCode = await QRCode.toDataURL(url, {
      width: 300,
      margin: 2,
      color: { dark: '#000000', light: '#ffffff' }
    });
    res.json({ qrCode, url });
  } catch (error) {
    res.status(500).json({ error: 'Greška pri generiranju QR koda' });
  }
});

// ===== ANALITIKA =====
// Logiraj posjet
app.post('/api/visits/:slug', async (req, res) => {
  const { qr_scan } = req.body;
  
  try {
    const [users] = await pool.query('SELECT id FROM users WHERE slug = ?', [req.params.slug]);
    if (users.length === 0) return res.status(404).json({ error: 'Korisnik nije pronađen' });
    
    const userId = users[0].id;
    const ip = req.ip || req.connection.remoteAddress;
    const userAgent = req.headers['user-agent'];
    
    await pool.query(
      'INSERT INTO visits (user_id, ip, user_agent, qr_scan) VALUES (?, ?, ?, ?)',
      [userId, ip, userAgent, qr_scan || false]
    );
    
    res.json({ message: 'Posjet zabilježen' });
  } catch (error) {
    res.status(500).json({ error: 'Greška pri zapisivanju posjeta' });
  }
});

// Dohvati analitiku za korisnika
app.get('/api/analytics/:userId', authMiddleware, async (req, res) => {
  try {
    const [visits] = await pool.query(
      'SELECT COUNT(*) as total, SUM(qr_scan) as qr_scans FROM visits WHERE user_id = ?',
      [req.params.userId]
    );
    
    const [recentVisits] = await pool.query(
      'SELECT ip, user_agent, timestamp, qr_scan FROM visits WHERE user_id = ? ORDER BY timestamp DESC LIMIT 50',
      [req.params.userId]
    );
    
    res.json({ 
      total: visits[0].total,
      qr_scans: visits[0].qr_scans || 0,
      recent: recentVisits
    });
  } catch (error) {
    res.status(500).json({ error: 'Greška pri dohvaćanju analitike' });
  }
});

// Test ruta
app.get('/api/health', (req, res) => {
  res.json({ status: 'OK', message: 'Server je aktivan' });
});

// Pokretanje servera
app.listen(PORT, () => {
  console.log(`Server pokrenut na portu ${PORT}`);
});