'use strict';
const express = require('express');
const bcrypt = require('bcryptjs');
const { db } = require('../db');
const { sign, requireAuth } = require('../middleware/auth');
const { sendMail } = require('../lib/mail');

const router = express.Router();

function money(n) {
  return 'R ' + Number(n || 0).toLocaleString('en-ZA', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

router.get('/login', (req, res) => {
  if (req.user) return res.redirect('/account');
  res.render('login', { title: 'Sign in | TOUS CINO', error: null, next: req.query.next || '/' });
});

router.post('/login', (req, res) => {
  const { email, password, next } = req.body;
  const user = db.prepare('SELECT * FROM users WHERE email = ?').get(String(email || '').toLowerCase());
  if (!user || !bcrypt.compareSync(String(password || ''), user.password_hash)) {
    return res.render('login', { title: 'Sign in | TOUS CINO', error: 'Incorrect email or password.', next: next || '/' });
  }
  res.cookie('tc_token', sign(user), { httpOnly: true, sameSite: 'lax', maxAge: 30 * 24 * 3600 * 1000 });
  res.redirect(next || '/account');
});

router.get('/register', (req, res) => {
  if (req.user) return res.redirect('/account');
  res.render('register', { title: 'Create account | TOUS CINO', error: null });
});

router.post('/register', (req, res) => {
  const { name, email, phone, password } = req.body;
  const cleanEmail = String(email || '').toLowerCase().trim();
  if (!name || !cleanEmail || !password) {
    return res.render('register', { title: 'Create account | TOUS CINO', error: 'Please fill in all fields.' });
  }
  if (String(password).length < 6) {
    return res.render('register', { title: 'Create account | TOUS CINO', error: 'Password must be at least 6 characters.' });
  }
  const exists = db.prepare('SELECT 1 FROM users WHERE email = ?').get(cleanEmail);
  if (exists) {
    return res.render('register', { title: 'Create account | TOUS CINO', error: 'An account with this email already exists.' });
  }
  const hash = bcrypt.hashSync(String(password), 10);
  const info = db.prepare('INSERT INTO users (name, email, phone, password_hash) VALUES (?, ?, ?, ?)').run(
    String(name).trim(),
    cleanEmail,
    String(phone || '').trim(),
    hash
  );
  const user = db.prepare('SELECT * FROM users WHERE id = ?').get(info.lastInsertRowid);
  res.cookie('tc_token', sign(user), { httpOnly: true, sameSite: 'lax', maxAge: 30 * 24 * 3600 * 1000 });
  sendMail({
    to: cleanEmail,
    subject: 'Welcome to TOUS CINO',
    html: `<h2>Welcome, ${name}!</h2><p>Your TOUS CINO account has been created. Happy shopping.</p>`,
  });
  res.redirect('/account');
});

router.get('/logout', (req, res) => {
  res.clearCookie('tc_token');
  res.redirect('/');
});

router.get('/', requireAuth, (req, res) => {
  const orders = db
    .prepare('SELECT * FROM orders WHERE user_id = ? ORDER BY created_at DESC LIMIT 20')
    .all(req.user.id);
  res.render('account', { title: 'My Account | TOUS CINO', orders, money });
});

router.post('/profile', requireAuth, (req, res) => {
  const { name, phone, password } = req.body;
  if (name) db.prepare('UPDATE users SET name = ?, phone = ? WHERE id = ?').run(String(name).trim(), String(phone || '').trim(), req.user.id);
  if (password && String(password).length >= 6) {
    db.prepare('UPDATE users SET password_hash = ? WHERE id = ?').run(bcrypt.hashSync(String(password), 10), req.user.id);
  }
  res.redirect('/account?updated=1');
});

router.get('/orders', requireAuth, (req, res) => {
  const orders = db.prepare('SELECT * FROM orders WHERE user_id = ? ORDER BY created_at DESC').all(req.user.id);
  const withCounts = orders.map((o) => {
    o.item_count = db.prepare('SELECT COALESCE(SUM(qty),0) c FROM order_items WHERE order_id = ?').get(o.id).c;
    return o;
  });
  res.render('account-orders', { title: 'My Orders | TOUS CINO', orders: withCounts, money });
});

module.exports = router;
