File size: 24,056 Bytes
f355d62
 
cbbb3a0
 
f355d62
cbbb3a0
 
 
 
 
 
 
923720c
cbbb3a0
 
f355d62
 
923720c
f355d62
cbbb3a0
 
f355d62
923720c
cbbb3a0
 
 
 
 
 
f355d62
cbbb3a0
 
 
 
 
 
 
 
 
 
f355d62
cbbb3a0
f355d62
 
cbbb3a0
 
f355d62
 
 
cbbb3a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f355d62
cbbb3a0
 
 
 
 
 
 
 
f355d62
cbbb3a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f355d62
cbbb3a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f355d62
 
cbbb3a0
 
 
 
f355d62
 
cbbb3a0
 
 
 
 
f355d62
cbbb3a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
923720c
cbbb3a0
f355d62
923720c
 
cbbb3a0
923720c
 
 
 
cbbb3a0
f355d62
cbbb3a0
 
 
 
923720c
cbbb3a0
f355d62
 
cbbb3a0
 
923720c
 
cbbb3a0
923720c
 
 
cbbb3a0
923720c
cbbb3a0
 
923720c
cbbb3a0
 
f355d62
cbbb3a0
f355d62
cbbb3a0
 
 
 
 
 
 
 
f355d62
cbbb3a0
 
 
f355d62
cbbb3a0
 
 
 
 
f355d62
 
cbbb3a0
 
 
f355d62
 
cbbb3a0
 
 
 
 
 
 
f355d62
 
cbbb3a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
923720c
cbbb3a0
 
 
923720c
cbbb3a0
 
 
 
 
 
f355d62
 
923720c
cbbb3a0
 
923720c
cbbb3a0
 
 
f355d62
cbbb3a0
 
 
 
923720c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
const path = require('path');
const fs = require('fs');
const dns = require('dns');
const express = require('express');
const cors = require('cors');
const dotenv = require('dotenv');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const multer = require('multer');
const Datastore = require('@seald-io/nedb');
const { MongoClient, ObjectId } = require('mongodb');

// Load environment variables
dotenv.config({ path: path.join(__dirname, '.env') });
dotenv.config({ path: path.join(__dirname, '..', '.env') });

const app = express();
const PORT = Number(process.env.PORT || 7860);  // Hugging Face default port
const JWT_SECRET = process.env.JWT_SECRET || 'hitech_secret_2025';
const MONGODB_URI = process.env.MONGODB_URI;
const MONGODB_DB = process.env.MONGODB_DB || 'hitech_technologies';

const ROOT_DIR = __dirname;  // Fixed for Hugging Face
const PUBLIC_DIR = path.join(ROOT_DIR, 'public');
const UPLOADS_DIR = path.join(ROOT_DIR, 'uploads');
const LEGACY_DATA_DIR = path.join(ROOT_DIR, 'data');

let mongoClient;
let mongoDb;

const asyncHandler = (fn) => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);
const collection = (name) => mongoDb.collection(name);
const toObjectId = (value) => (ObjectId.isValid(value) ? new ObjectId(value) : null);

function ensureDirs() {
  if (!fs.existsSync(UPLOADS_DIR)) fs.mkdirSync(UPLOADS_DIR, { recursive: true });
  if (!fs.existsSync(LEGACY_DATA_DIR)) fs.mkdirSync(LEGACY_DATA_DIR, { recursive: true });
}

function normalizeDoc(doc) {
  if (!doc) return doc;
  const id = String(doc._id);
  return {
    ...doc,
    _id: id,
    id,
    created_at: doc.createdAt,
    updated_at: doc.updatedAt,
  };
}

const normalizeDocs = (docs) => (Array.isArray(docs) ? docs.map(normalizeDoc) : []);

async function findDocs(name, query = {}, sort = {}) {
  let cursor = collection(name).find(query);
  if (Object.keys(sort).length) cursor = cursor.sort(sort);
  return normalizeDocs(await cursor.toArray());
}

async function findOneDoc(name, query = {}) {
  return normalizeDoc(await collection(name).findOne(query));
}

async function insertDoc(name, doc) {
  const result = await collection(name).insertOne(doc);
  return normalizeDoc({ ...doc, _id: result.insertedId });
}

async function updateDoc(name, query, set, options = {}) {
  return collection(name).updateOne(query, { $set: set }, options);
}

async function upsertDoc(name, query, set) {
  return collection(name).updateOne(query, { $set: set }, { upsert: true });
}

async function removeDoc(name, query) {
  return collection(name).deleteOne(query);
}

async function countDocs(name, query = {}) {
  return collection(name).countDocuments(query);
}

function deleteStoredFile(urlPath) {
  if (!urlPath || typeof urlPath !== 'string') return;
  const safeRelative = urlPath.replace(/^\//, '');
  const fullPath = path.join(ROOT_DIR, safeRelative);
  if (!fullPath.startsWith(UPLOADS_DIR)) return;
  if (fs.existsSync(fullPath)) fs.unlinkSync(fullPath);
}

function legacyFile(name) {
  return path.join(LEGACY_DATA_DIR, `${name}.db`);
}

function loadLegacyDocs(filePath) {
  return new Promise((resolve, reject) => {
    if (!fs.existsSync(filePath)) return resolve([]);
    const store = new Datastore({ filename: filePath, autoload: true });
    store.find({}).exec((err, docs) => {
      if (err) return reject(err);
      resolve(docs || []);
    });
  });
}

function legacyDocToMongo(doc) {
  if (!doc) return doc;
  const { _id, ...rest } = doc;
  return {
    ...rest,
    legacyId: _id ? String(_id) : undefined,
    createdAt: doc.createdAt ? new Date(doc.createdAt) : new Date(),
    updatedAt: doc.updatedAt ? new Date(doc.updatedAt) : undefined,
  };
}

function stripUndefined(doc) {
  return Object.fromEntries(Object.entries(doc).filter(([, value]) => value !== undefined));
}

const DEFAULT_SETTINGS = {
  company_name: 'HiTech Technologies',
  tagline: "Pakistan's Leading Software Company",
  hero_title: 'Smart *Software* Solutions That *Scale* With You',
  hero_subtitle: 'From custom AI automation to enterprise-grade software systems - we build technology that transforms your business operations and delivers real results.',
  about_text: 'HiTech Technologies was founded with a clear mission: to make world-class software development accessible to businesses of every size in Pakistan and beyond. We specialize in custom software, AI automation, data science, mobile apps, web platforms, and enterprise management systems.',
  address: 'G-11, Islamabad, Pakistan',
  phone: '03345555362',
  email: 'info@hitechtech.pk',
  whatsapp: '03345555362',
  facebook: 'https://facebook.com/hitechtech',
  linkedin: 'https://linkedin.com/company/hitechtech',
  twitter: 'https://twitter.com/hitechtech',
  working_hours: 'Mon - Sat: 9:00 AM - 6:00 PM',
  footer_text: "Pakistan's trusted software development company. We build custom software, AI automation, and enterprise solutions for businesses of all sizes.",
};

const DEFAULT_SERVICES = [
  { name: 'AI Automation', description: 'Harness artificial intelligence to automate workflows, reduce manual tasks, and optimize operations. We build ML pipelines, chatbots, and intelligent systems that adapt to your business.', icon: 'fa-brain', features: 'Workflow Automation,ML Pipelines,Chatbot Development,Document AI,Predictive Analytics', status: 'active', sort_order: 1 },
  { name: 'Data Science Services', description: 'Transform raw data into actionable insights. Custom dashboards, predictive models, and analytics pipelines that empower smarter, data-driven decisions across your organization.', icon: 'fa-chart-bar', features: 'Data Analytics,Custom Dashboards,Predictive Models,Business Intelligence,Data Engineering', status: 'active', sort_order: 2 },
  { name: 'POS Software', description: 'Feature-rich Point-of-Sale systems for retail, restaurants, pharmacies, and all business types. Inventory control, fast billing, multi-branch support, and real-time reporting in one system.', icon: 'fa-cash-register', features: 'Inventory Control,Multi-Branch,Barcode Support,Sales Reports,Customer Loyalty', status: 'active', sort_order: 3 },
  { name: 'App Development', description: 'Beautiful, high-performance mobile applications for iOS and Android. We develop native and cross-platform apps using Flutter and React Native with exceptional user experiences.', icon: 'fa-mobile-alt', features: 'iOS & Android,Flutter / React Native,UI/UX Design,API Integration,Push Notifications', status: 'active', sort_order: 4 },
  { name: 'Web Development', description: 'Responsive, fast, and scalable web applications built with modern frameworks. From corporate websites to complex enterprise portals - we deliver exceptional digital experiences.', icon: 'fa-globe', features: 'React / Vue / Next.js,E-Commerce,Web Portals,REST APIs,SEO Optimized', status: 'active', sort_order: 5 },
  { name: 'Custom Software', description: 'Bespoke software built from scratch to match your unique business processes. ERP systems, CRM solutions, billing platforms, and specialized industry tools tailored to your workflow.', icon: 'fa-code', features: 'ERP Systems,CRM Solutions,Billing Systems,HR & Payroll,API Development', status: 'active', sort_order: 6 },
];

const DEFAULT_PRODUCTS = [
  { name: 'School Management System', category: 'Education', description: 'A complete academic management platform for schools, colleges, and educational institutes. Manage everything from admissions to results in one centralized system with parent portal and SMS alerts.', features: 'Student Enrollment & Records,Attendance Tracking (Manual & Biometric),Fee Collection & Receipts,Grade Book & Result Management,Parent Portal & SMS Notifications,Teacher & Staff Management,Library Management,Timetable & Scheduling', banner_color: '#0D2B7A', status: 'active' },
  { name: 'Patient Token System', category: 'Healthcare', description: 'Eliminate waiting room chaos with a smart patient queuing system for clinics, hospitals, and labs. Display tokens on screen, notify patients via SMS, and manage priorities with ease.', features: 'Auto Token Generation,Digital Display Screen,Priority Queue (Emergency),SMS & WhatsApp Notifications,Multiple Counter Support,Doctor-Wise Queuing,Daily Reports & Analytics,Multi-Branch Support', banner_color: '#C91F1F', status: 'active' },
  { name: 'Gym Management System', category: 'Fitness', description: 'A powerful gym and fitness center management platform. Handle memberships, payments, staff, workout plans, and member check-in all in one comprehensive system.', features: 'Member Registration & Profiles,Subscription & Membership Plans,Automated Billing & Renewals,Biometric / Card Check-in,Staff & Trainer Management,Workout Plan Assignment,Expiry Alerts & Notifications,Revenue Reports & Analytics', banner_color: '#071B52', status: 'active' },
];

async function seedDefaults() {
  const adminCount = await countDocs('admins');
  if (adminCount === 0) {
    await insertDoc('admins', {
      username: 'Huzaifa',
      password_hash: bcrypt.hashSync('12345', 10),
      createdAt: new Date(),
    });
    console.log('Seeded default admin: Huzaifa / 12345');
  }

  const settingsCount = await countDocs('settings');
  if (settingsCount === 0) {
    const docs = Object.entries(DEFAULT_SETTINGS).map(([key, value]) => ({ key, value }));
    await collection('settings').insertMany(docs);
  }

  const servicesCount = await countDocs('services');
  if (servicesCount === 0) {
    const docs = DEFAULT_SERVICES.map((doc) => ({ ...doc, banner_url: null, createdAt: new Date() }));
    await collection('services').insertMany(docs);
  }

  const productsCount = await countDocs('products');
  if (productsCount === 0) {
    const docs = DEFAULT_PRODUCTS.map((doc) => ({ ...doc, banner_url: null, createdAt: new Date() }));
    await collection('products').insertMany(docs);
  }
}

async function migrateLegacyCollection(collectionName, filePath, mapper = legacyDocToMongo) {
  const currentCount = await countDocs(collectionName);
  if (currentCount > 0) return;
  const docs = await loadLegacyDocs(filePath);
  if (!docs.length) return;
  const mapped = docs.map(mapper).map(stripUndefined);
  if (!mapped.length) return;
  await collection(collectionName).insertMany(mapped);
  console.log(`Migrated ${mapped.length} docs into ${collectionName}`);
}

async function bootstrapDatabase() {
  ensureDirs();
  if (!MONGODB_URI) {
    throw new Error('MONGODB_URI is missing. Put it in .env or Hugging Face secret');
  }

  console.log('MongoDB URI exists, attempting connection...');
  
  const connectOptions = {
    serverSelectionTimeoutMS: 30000,
    socketTimeoutMS: 45000,
    connectTimeoutMS: 30000,
    family: 4, // Force IPv4 - important for Hugging Face
  };

  const tryConnect = async () => {
    mongoClient = new MongoClient(MONGODB_URI, connectOptions);
    await mongoClient.connect();
    mongoDb = mongoClient.db(MONGODB_DB);
    console.log('βœ… MongoDB Connected Successfully!');
  };

  try {
    await tryConnect();
  } catch (error) {
    console.error('First connection attempt failed:', error.message);
    
    const isSrvUri = MONGODB_URI.startsWith('mongodb+srv://');
    const isSrvLookupError = String(error?.message || '').includes('querySrv') || 
                            String(error?.code || '').includes('ECONNREFUSED');
    
    if (isSrvUri && isSrvLookupError) {
      console.log('Attempting with DNS servers 1.1.1.1, 8.8.8.8...');
      dns.setServers(['1.1.1.1', '8.8.8.8']);
      await tryConnect();
      console.log('MongoDB connected after switching DNS resolvers');
    } else {
      throw error;
    }
  }

  await migrateLegacyCollection('admins', legacyFile('admins'));
  await migrateLegacyCollection('settings', legacyFile('settings'));
  await migrateLegacyCollection('services', legacyFile('services'));
  await migrateLegacyCollection('products', legacyFile('products'));
  await migrateLegacyCollection('posts', legacyFile('posts'));
  await migrateLegacyCollection('contacts', legacyFile('contacts'));
  await seedDefaults();
}

const auth = asyncHandler(async (req, res, next) => {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(401).json({ error: 'Unauthorized' });
  try {
    req.user = jwt.verify(token, JWT_SECRET);
    next();
  } catch {
    res.status(401).json({ error: 'Invalid token' });
  }
});

const storage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, UPLOADS_DIR),
  filename: (req, file, cb) => cb(null, `${Date.now()}-${Math.random().toString(36).slice(2)}${path.extname(file.originalname)}`),
});

const upload = multer({
  storage,
  limits: { fileSize: 10 * 1024 * 1024 },
  fileFilter: (req, file, cb) => {
    if (/image/.test(file.mimetype)) cb(null, true);
    else cb(new Error('Images only'));
  },
});

app.use(cors());
app.use(express.json({ limit: '20mb' }));
app.use(express.urlencoded({ extended: true }));
app.use(express.static(PUBLIC_DIR));
app.use('/uploads', express.static(UPLOADS_DIR));

app.post('/api/auth/login', asyncHandler(async (req, res) => {
  const { username, password } = req.body;
  if (!username || !password) return res.status(400).json({ error: 'Username and password required' });
  const user = await findOneDoc('admins', { username });
  if (!user || !bcrypt.compareSync(password, user.password_hash)) {
    return res.status(401).json({ error: 'Invalid credentials' });
  }
  const token = jwt.sign({ id: user.id, username: user.username }, JWT_SECRET, { expiresIn: '24h' });
  res.json({ token, username: user.username });
}));

app.post('/api/auth/change-password', auth, asyncHandler(async (req, res) => {
  const { currentPassword, newPassword } = req.body;
  const user = await findOneDoc('admins', { _id: toObjectId(req.user.id) });
  if (!user || !bcrypt.compareSync(currentPassword, user.password_hash)) {
    return res.status(401).json({ error: 'Current password incorrect' });
  }
  await updateDoc('admins', { _id: toObjectId(req.user.id) }, { password_hash: bcrypt.hashSync(newPassword, 10) });
  res.json({ success: true });
}));

app.get('/api/settings', asyncHandler(async (req, res) => {
  const rows = await findDocs('settings');
  const settings = {};
  rows.forEach((row) => {
    settings[row.key] = row.value;
  });
  res.json(settings);
}));

app.put('/api/settings', auth, asyncHandler(async (req, res) => {
  for (const [key, value] of Object.entries(req.body)) {
    await upsertDoc('settings', { key }, { key, value: value || '' });
  }
  res.json({ success: true });
}));

app.get('/api/services', asyncHandler(async (req, res) => {
  const query = req.query.all ? {} : { status: 'active' };
  const docs = await findDocs('services', query, { sort_order: 1, createdAt: 1 });
  res.json(docs);
}));

app.post('/api/services', auth, upload.single('banner'), asyncHandler(async (req, res) => {
  const { name, description, icon, features, status, sort_order } = req.body;
  if (!name) return res.status(400).json({ error: 'Name required' });
  const banner_url = req.file ? `/uploads/${req.file.filename}` : null;
  const doc = await insertDoc('services', {
    name,
    description: description || '',
    icon: icon || 'fa-cog',
    banner_url,
    features: features || '',
    status: status || 'active',
    sort_order: Number.isFinite(Number(sort_order)) ? Number(sort_order) : 0,
    createdAt: new Date(),
  });
  res.json(doc);
}));

app.put('/api/services/:id', auth, upload.single('banner'), asyncHandler(async (req, res) => {
  const existingId = toObjectId(req.params.id);
  if (!existingId) return res.status(404).json({ error: 'Not found' });
  const existing = await findOneDoc('services', { _id: existingId });
  if (!existing) return res.status(404).json({ error: 'Not found' });

  const banner_url = req.file ? `/uploads/${req.file.filename}` : existing.banner_url;
  if (req.file && existing.banner_url) deleteStoredFile(existing.banner_url);

  await updateDoc('services', { _id: existingId }, {
    name: req.body.name || existing.name,
    description: req.body.description ?? existing.description,
    icon: req.body.icon || existing.icon,
    banner_url,
    features: req.body.features ?? existing.features,
    status: req.body.status || existing.status,
    sort_order: Number.isFinite(Number(req.body.sort_order)) ? Number(req.body.sort_order) : existing.sort_order,
    updatedAt: new Date(),
  });

  res.json({ success: true, banner_url });
}));

app.delete('/api/services/:id', auth, asyncHandler(async (req, res) => {
  const id = toObjectId(req.params.id);
  if (!id) return res.status(404).json({ error: 'Not found' });
  const service = await findOneDoc('services', { _id: id });
  if (!service) return res.status(404).json({ error: 'Not found' });
  if (service.banner_url) deleteStoredFile(service.banner_url);
  await removeDoc('services', { _id: id });
  res.json({ success: true });
}));

app.get('/api/products', asyncHandler(async (req, res) => {
  const query = req.query.all ? {} : { status: 'active' };
  const docs = await findDocs('products', query, { createdAt: 1 });
  res.json(docs);
}));

app.post('/api/products', auth, upload.single('banner'), asyncHandler(async (req, res) => {
  const { name, category, description, features, banner_color, status } = req.body;
  if (!name) return res.status(400).json({ error: 'Name required' });
  const banner_url = req.file ? `/uploads/${req.file.filename}` : null;
  const doc = await insertDoc('products', {
    name,
    category: category || '',
    description: description || '',
    features: features || '',
    banner_url,
    banner_color: banner_color || '#0D2B7A',
    status: status || 'active',
    createdAt: new Date(),
  });
  res.json(doc);
}));

app.put('/api/products/:id', auth, upload.single('banner'), asyncHandler(async (req, res) => {
  const id = toObjectId(req.params.id);
  if (!id) return res.status(404).json({ error: 'Not found' });
  const existing = await findOneDoc('products', { _id: id });
  if (!existing) return res.status(404).json({ error: 'Not found' });

  const banner_url = req.file ? `/uploads/${req.file.filename}` : existing.banner_url;
  if (req.file && existing.banner_url) deleteStoredFile(existing.banner_url);

  await updateDoc('products', { _id: id }, {
    name: req.body.name || existing.name,
    category: req.body.category ?? existing.category,
    description: req.body.description ?? existing.description,
    features: req.body.features ?? existing.features,
    banner_url,
    banner_color: req.body.banner_color || existing.banner_color,
    status: req.body.status || existing.status,
    updatedAt: new Date(),
  });

  res.json({ success: true, banner_url });
}));

app.delete('/api/products/:id', auth, asyncHandler(async (req, res) => {
  const id = toObjectId(req.params.id);
  if (!id) return res.status(404).json({ error: 'Not found' });
  const product = await findOneDoc('products', { _id: id });
  if (!product) return res.status(404).json({ error: 'Not found' });
  if (product.banner_url) deleteStoredFile(product.banner_url);
  await removeDoc('products', { _id: id });
  res.json({ success: true });
}));

app.get('/api/posts', asyncHandler(async (req, res) => {
  const query = req.query.all ? {} : { status: 'published' };
  const docs = await findDocs('posts', query, { createdAt: -1 });
  res.json(docs);
}));

app.post('/api/posts', auth, upload.single('banner'), asyncHandler(async (req, res) => {
  const { title, content, excerpt, status } = req.body;
  if (!title) return res.status(400).json({ error: 'Title required' });
  const banner_url = req.file ? `/uploads/${req.file.filename}` : null;
  const doc = await insertDoc('posts', {
    title,
    content: content || '',
    excerpt: excerpt || '',
    banner_url,
    status: status || 'published',
    createdAt: new Date(),
  });
  res.json(doc);
}));

app.put('/api/posts/:id', auth, upload.single('banner'), asyncHandler(async (req, res) => {
  const id = toObjectId(req.params.id);
  if (!id) return res.status(404).json({ error: 'Not found' });
  const existing = await findOneDoc('posts', { _id: id });
  if (!existing) return res.status(404).json({ error: 'Not found' });

  const banner_url = req.file ? `/uploads/${req.file.filename}` : existing.banner_url;
  if (req.file && existing.banner_url) deleteStoredFile(existing.banner_url);

  await updateDoc('posts', { _id: id }, {
    title: req.body.title || existing.title,
    content: req.body.content ?? existing.content,
    excerpt: req.body.excerpt ?? existing.excerpt,
    banner_url,
    status: req.body.status || existing.status,
    updatedAt: new Date(),
  });

  res.json({ success: true });
}));

app.delete('/api/posts/:id', auth, asyncHandler(async (req, res) => {
  const id = toObjectId(req.params.id);
  if (!id) return res.status(404).json({ error: 'Not found' });
  const post = await findOneDoc('posts', { _id: id });
  if (!post) return res.status(404).json({ error: 'Not found' });
  if (post.banner_url) deleteStoredFile(post.banner_url);
  await removeDoc('posts', { _id: id });
  res.json({ success: true });
}));

app.post('/api/contact', asyncHandler(async (req, res) => {
  const { name, email, phone, service_interest, budget, message } = req.body;
  if (!name || !message) return res.status(400).json({ error: 'Name and message required' });
  await insertDoc('contacts', {
    name,
    email: email || '',
    phone: phone || '',
    service_interest: service_interest || '',
    budget: budget || '',
    message,
    is_read: false,
    createdAt: new Date(),
  });
  res.json({ success: true, message: 'Your message has been received! We will contact you within 24 hours.' });
}));

app.get('/api/contacts', auth, asyncHandler(async (req, res) => {
  const docs = await findDocs('contacts', {}, { createdAt: -1 });
  res.json(docs);
}));

app.put('/api/contacts/:id/read', auth, asyncHandler(async (req, res) => {
  const id = toObjectId(req.params.id);
  if (!id) return res.status(404).json({ error: 'Not found' });
  await updateDoc('contacts', { _id: id }, { is_read: true, updatedAt: new Date() });
  res.json({ success: true });
}));

app.delete('/api/contacts/:id', auth, asyncHandler(async (req, res) => {
  const id = toObjectId(req.params.id);
  if (!id) return res.status(404).json({ error: 'Not found' });
  await removeDoc('contacts', { _id: id });
  res.json({ success: true });
}));

app.get('/api/admin/stats', auth, asyncHandler(async (req, res) => {
  const [services, products, posts, contacts, unread] = await Promise.all([
    countDocs('services', { status: 'active' }),
    countDocs('products', { status: 'active' }),
    countDocs('posts', { status: 'published' }),
    countDocs('contacts'),
    countDocs('contacts', { is_read: false }),
  ]);

  res.json({ services, products, posts, contacts, unread });
}));

app.get('/api/health', asyncHandler(async (req, res) => {
  const adminCount = await countDocs('admins');
  res.json({
    status: 'OK',
    message: 'Server is running!',
    mongodb: 'Connected',
    db: MONGODB_DB,
    admins: adminCount,
  });
}));

// Serve admin panel and frontend
app.get('/admin', (req, res) => res.sendFile(path.join(PUBLIC_DIR, 'admin.html')));
app.get('*', (req, res) => res.sendFile(path.join(PUBLIC_DIR, 'index.html')));

// Error handler
app.use((err, req, res, next) => {
  console.error(err);
  if (err && err.message === 'Images only') {
    return res.status(400).json({ error: 'Images only' });
  }
  res.status(500).json({ error: err?.message || 'Server error' });
});

// Start server
bootstrapDatabase()
  .then(() => {
    app.listen(PORT, '0.0.0.0', () => {
      console.log(`\nπŸš€ HiTech Technologies (MongoDB) - http://localhost:${PORT}`);
      console.log(`πŸ”‘ Admin Panel - http://localhost:${PORT}/admin`);
      console.log(`πŸ“¦ MongoDB DB - ${MONGODB_DB}`);
    });
  })
  .catch((error) => {
    console.error('Failed to bootstrap application:', error);
    process.exit(1);
  });