File size: 24,988 Bytes
ecafd26
 
 
 
 
 
 
 
 
 
 
6ebe5c8
ecafd26
 
 
 
6ebe5c8
 
 
 
 
 
ecafd26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ebe5c8
ecafd26
7568af0
 
ca0aa5d
ecafd26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ebe5c8
ecafd26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca0aa5d
ecafd26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ebe5c8
ecafd26
 
 
 
 
 
 
 
 
 
 
 
6ebe5c8
 
ecafd26
6ebe5c8
ecafd26
 
 
 
 
 
6ebe5c8
ecafd26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ebe5c8
ecafd26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ebe5c8
 
ecafd26
 
6ebe5c8
ecafd26
6ebe5c8
ecafd26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ebe5c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7568af0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca0aa5d
7568af0
 
6ebe5c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecafd26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ebe5c8
ecafd26
 
 
 
 
 
6ebe5c8
 
ecafd26
 
 
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const path = require('path');
const bcrypt = require('bcrypt');
const multer = require('multer');
const { generateOtp, sendOtpEmail } = require('./mailService');
const { getPool, initializeDatabase, closePool } = require('./db');
const otpService = require('./otpService');
const axios = require('axios');
const http = require('http');
const socketIo = require('socket.io');
const fs = require('fs');

const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
    cors: {
        origin: "*",
        methods: ["GET", "POST"]
    }
});
const port = process.env.PORT || 3000;

// Initialize database and start server
(async () => {
    try {
        await initializeDatabase();
        console.log('Database initialized successfully.');
        
        // Test database connection
        const pool = getPool();
        const client = await pool.connect();
        client.release();
        console.log('Connected to main database');
        
        server.listen(port, () => {
            console.log(`Server running on port ${port}`);
        });
    } catch (err) {
        console.error('Failed to initialize database or start server:', err);
        process.exit(1);
    }
})();

// Middleware
app.use(cors());
app.use(express.json());

// Serve static files from React build directory
app.use(express.static(path.join(__dirname, 'public')));

// Store logs in memory (in production, use a database)
let serverLogs = [];

// Logging middleware
function logRequest(req, res, next) {
    const start = Date.now();
    
    // Log incoming request
    const requestLog = {
        type: 'request',
        message: `${req.method} ${req.path}`,
        details: {
            method: req.method,
            path: req.path,
            headers: req.headers,
            body: req.body,
            timestamp: new Date().toISOString(),
            ip: req.ip || req.connection.remoteAddress
        },
        source: 'middleware'
    };
    
    emitLog(requestLog);
    
    // Override res.end to log response
    const originalEnd = res.end;
    res.end = function(chunk, encoding) {
        const duration = Date.now() - start;
        
        const responseLog = {
            type: 'response',
            message: `${req.method} ${req.path} - ${res.statusCode} (${duration}ms)`,
            details: {
                statusCode: res.statusCode,
                duration: duration,
                headers: res.getHeaders(),
                timestamp: new Date().toISOString()
            },
            source: 'middleware'
        };
        
        emitLog(responseLog);
        originalEnd.call(this, chunk, encoding);
    };
    
    next();
}

// Apply logging middleware
app.use(logRequest);

// Emit log to all connected clients
function emitLog(logData) {
    serverLogs.unshift(logData);
    
    // Keep only last 1000 logs
    if (serverLogs.length > 1000) {
        serverLogs = serverLogs.slice(0, 1000);
    }
    
    io.emit('server-log', logData);
}

// Manual logging function
function log(level, message, details = {}) {
    const logData = {
        type: level,
        message: message,
        details: {
            ...details,
            timestamp: new Date().toISOString()
        },
        source: 'server'
    };
    
    emitLog(logData);
    
    // Also log to console
    console.log(`[${level.toUpperCase()}] ${message}`, details);
}

// OTP Authentication middleware
const requireOtpAuth = async (req, res, next) => {
    const otp = req.headers['x-otp-token'];
    const email = req.headers['x-user-email'];

    if (!otp || !email) {
        return res.status(401).json({ error: 'Missing OTP or email headers' });
    }

    try {
        const pool = getPool();
        const result = await pool.query(
            'SELECT * FROM otps WHERE email = $1 AND otp = $2 AND verified = true AND expires_at > NOW()',
            [email, otp]
        );

        if (result.rows.length === 0) {
            return res.status(401).json({ error: 'Invalid or expired OTP' });
        }

        req.user = { email };
        next();
    } catch (err) {
        console.error('OTP verification error:', err);
        res.status(500).json({ error: 'Internal server error' });
    }
};

// Admin OTP Authentication middleware
const requireAdminOtpAuth = async (req, res, next) => {
    try {
        const otp = req.headers['x-otp-token'];
        const email = req.headers['x-user-email'];

        if (!otp || !email) {
            return res.status(401).json({ 
                success: false, 
                error: 'Missing authentication headers' 
            });
        }

        const pool = getPool();
        // Verify OTP
        const result = await pool.query(
            'SELECT * FROM otps WHERE email = $1 AND otp = $2 AND is_used = false AND expires_at > NOW()',
            [email, otp]
        );

        if (result.rows.length === 0) {
            return res.status(401).json({ 
                success: false, 
                error: 'Invalid or expired OTP' 
            });
        }

        // Mark OTP as used
        await pool.query(
            'UPDATE otps SET is_used = true WHERE email = $1 AND otp = $2',
            [email, otp]
        );

        next();
    } catch (error) {
        console.error('Admin auth error:', error);
        res.status(500).json({ 
            success: false, 
            error: 'Authentication error' 
        });
    }
};

// Middleware to check OTP authentication
async function checkOtpAuth(req, res, next) {
  const otp = req.headers['x-otp-token'];
  const email = req.headers['x-user-email'];

  if (!otp || !email) {
    return res.status(401).json({ success: false, error: 'OTP token and email are required' });
  }

  try {
    const result = await otpService.verifyUserOtp(email, otp);
    if (!result.success) {
      return res.status(401).json({ success: false, error: 'Invalid OTP' });
    }
    next();
  } catch (error) {
    res.status(401).json({ success: false, error: error.message });
  }
}

// Middleware to check admin OTP authentication
async function checkAdminOtpAuth(req, res, next) {
    const otp = req.headers['x-otp-token'];
    
    if (!otp) {
        return res.status(401).json({ success: false, error: 'OTP token required' });
    }

    try {
        const response = await fetch('https://mail-steel.vercel.app/admin/verify-otp', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ otp })
        });

        const data = await response.json();
        if (!data.success) {
            return res.status(401).json({ success: false, error: 'Invalid OTP' });
        }

        next();
    } catch (error) {
        console.error('Admin OTP verification failed:', error);
        res.status(500).json({ success: false, error: 'Failed to verify admin OTP' });
    }
}

// Routes
app.get('/', (req, res) => {
    log('info', 'Homepage accessed', { 
        path: req.path, 
        userAgent: req.get('User-Agent'),
        ip: req.ip 
    });
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// API Routes

// Send OTP
app.post('/api/send-otp', async (req, res) => {
  const { email, type } = req.body;
  
  if (!email && type !== 'admin') {
    return res.status(400).json({ success: false, error: 'Email is required for user OTP' });
  }

  try {
    let result;
    if (type === 'admin') {
      result = await otpService.sendAdminOtp();
  } else {
      result = await otpService.sendUserOtp(email);
    }
    res.json(result);
  } catch (error) {
    res.status(500).json({ success: false, error: error.message });
  }
});

// Verify OTP
app.post('/api/verify-otp', async (req, res) => {
  const { email, otp, type } = req.body;
  
  if (!otp || (type !== 'admin' && !email)) {
    return res.status(400).json({ success: false, error: 'OTP and email (for user) are required' });
  }

  try {
    let result;
    if (type === 'admin') {
      result = await otpService.verifyAdminOtp(otp);
    } else {
      result = await otpService.verifyUserOtp(email, otp);
    }
    res.json(result);
  } catch (error) {
    res.status(500).json({ success: false, error: error.message });
  }
});

// Register new user
app.post('/api/register', async (req, res) => {
    const { name, email, password } = req.body;

    if (!name || !email || !password) {
        return res.status(400).json({ 
            success: false, 
            error: 'Name, email and password are required' 
        });
    }

    try {
        // Check if user already exists
        const { rows: existingUsers } = await getPool().query(
            'SELECT * FROM users WHERE email = $1',
            [email]
        );

        if (existingUsers.length > 0) {
            return res.status(400).json({ 
                success: false, 
                error: 'Email already registered' 
            });
        }

        // Hash password
        const hashedPassword = await bcrypt.hash(password, 10);

        // Create new user
        const { rows: newUser } = await getPool().query(
            'INSERT INTO users (name, email, password) VALUES ($1, $2, $3) RETURNING id, name, email',
            [name, email, hashedPassword]
        );

        res.json({ 
            success: true, 
            user: newUser[0],
            message: 'Registration successful' 
        });
    } catch (error) {
        console.error('Error registering user:', error);
        res.status(500).json({ 
            success: false, 
            error: 'Failed to register user' 
        });
    }
});

// Login
app.post('/api/login', async (req, res) => {
    const { email, password } = req.body;

    if (!email || !password) {
        return res.status(400).json({ 
            success: false, 
            error: 'Email and password are required' 
        });
    }

    try {
        const { rows: users } = await getPool().query(
            'SELECT * FROM users WHERE email = $1',
            [email]
        );

        if (users.length === 0) {
            return res.status(401).json({ 
                success: false, 
                error: 'Invalid email or password' 
            });
        }

        const user = users[0];
        const validPassword = await bcrypt.compare(password, user.password);

        if (!validPassword) {
            return res.status(401).json({ 
                success: false, 
                error: 'Invalid email or password' 
            });
        }

        res.json({ 
            success: true, 
            user: {
                id: user.id,
                name: user.name,
                email: user.email
            }
        });
    } catch (error) {
        console.error('Error logging in:', error);
        res.status(500).json({ 
            success: false, 
            error: 'Login failed' 
        });
    }
});

// Get user submissions (protected route example)
app.get('/api/user-submissions/:userId', checkOtpAuth, async (req, res) => {
  const { userId } = req.params;

  try {
    const result = await getPool().query(
      'SELECT * FROM submissions WHERE user_id = $1 ORDER BY created_at DESC',
      [userId]
    );
    res.json({ success: true, submissions: result.rows });
  } catch (error) {
    res.status(500).json({ success: false, error: 'Failed to fetch submissions' });
  }
});

// Gift Card Routes
app.post('/api/gift-cards', checkOtpAuth, async (req, res) => {
  const {
        ticket_user_name,
        gc_code,
        gc_phone,
        upi_id,
        amount,
        proof_video_url 
  } = req.body;
    const userId = req.headers['x-user-id'];

    if (!ticket_user_name || !gc_code || !gc_phone || !upi_id || !amount || !proof_video_url) {
        return res.status(400).json({ 
            success: false, 
            error: 'All fields are required including the video URL' 
        });
  }

  try {
        const result = await getPool().query(
            `INSERT INTO submissions (
                user_id, 
                ticket_user_name,
                gc_code,
                gc_phone,
                upi_id,
                amount,
                proof_video_url
            ) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING id`,
            [userId, ticket_user_name, gc_code, gc_phone, upi_id, amount, proof_video_url]
    );
        res.json({ 
            success: true, 
            submissionId: result.rows[0].id,
            message: 'Gift card submission successful'
        });
    } catch (error) {
        console.error('Gift card submission error:', error);
        res.status(500).json({ 
            success: false, 
            error: 'Failed to submit gift card. Please try again.' 
        });
  }
});

// File2Link Upload Route
app.post('/api/upload', async (req, res) => {
    try {
        const formData = new FormData();
        formData.append('file', req.files.file);

        const response = await axios.post('https://file2link-ol4p.onrender.com/.com/upload', formData, {
            headers: {
                ...formData.getHeaders()
            }
        });

        if (response.data.success) {
            res.json({
                success: true,
                videoUrl: response.data.access_url
            });
        } else {
            throw new Error('Upload failed');
        }
    } catch (error) {
        console.error('File upload error:', error);
        res.status(500).json({
            success: false,
            error: 'Failed to upload file. Please try again.'
        });
  }
});

// Get chat messages
app.get('/api/messages/:userId', checkOtpAuth, async (req, res) => {
  const { userId } = req.params;
  const userEmail = req.headers['x-user-email'];

  try {
  // Verify that the user is requesting their own messages
    const userResult = await getPool().query('SELECT id FROM users WHERE email = $1', [userEmail]);
    if (userResult.rows.length === 0 || userResult.rows[0].id !== parseInt(userId)) {
      return res.status(403).json({ success: false, error: 'Unauthorized access' });
  }

    const result = await getPool().query(
      'SELECT * FROM messages WHERE user_id = $1 ORDER BY created_at ASC',
      [userId]
    );
    res.json({ success: true, messages: result.rows });
  } catch (error) {
    console.error('Error fetching messages:', error);
    res.status(500).json({ success: false, error: 'Failed to fetch messages' });
  }
});

// Send message
app.post('/api/messages', checkOtpAuth, async (req, res) => {
  const { userId, content, sender } = req.body;
  const userEmail = req.headers['x-user-email'];

  if (!content || !sender) {
    return res.status(400).json({ success: false, error: 'Content and sender are required' });
  }

  try {
    // Verify that the user is sending a message to their own chat
    const userResult = await getPool().query('SELECT id FROM users WHERE email = $1', [userEmail]);
    if (userResult.rows.length === 0 || userResult.rows[0].id !== parseInt(userId)) {
      return res.status(403).json({ success: false, error: 'Unauthorized access' });
  }

    const result = await getPool().query(
      'INSERT INTO messages (user_id, content, sender) VALUES ($1, $2, $3) RETURNING *',
      [userId, content, sender]
    );
    res.json({ success: true, message: result.rows[0] });
  } catch (error) {
    console.error('Error sending message:', error);
    res.status(500).json({ success: false, error: 'Failed to send message' });
  }
});

// Admin routes
app.get('/api/admin/users', async (req, res) => {
    try {
        const result = await getPool().query('SELECT id, email, created_at FROM users ORDER BY created_at DESC');
        res.json({ success: true, users: result.rows });
    } catch (error) {
        console.error('Error fetching users:', error);
        res.status(500).json({ success: false, error: 'Failed to fetch users' });
    }
});

app.get('/api/admin/messages/all', async (req, res) => {
    try {
        const result = await getPool().query(`
            SELECT m.*, u.email as user_email 
            FROM messages m 
            JOIN users u ON m.user_id = u.id 
            ORDER BY m.created_at DESC
        `);
        res.json({ success: true, messages: result.rows });
    } catch (error) {
        console.error('Error fetching messages:', error);
        res.status(500).json({ success: false, error: 'Failed to fetch messages' });
    }
});

app.get('/api/admin/messages/:userId', async (req, res) => {
    const { userId } = req.params;
    try {
        const result = await getPool().query(
            'SELECT * FROM messages WHERE user_id = $1 ORDER BY created_at ASC',
            [userId]
        );
        res.json({ success: true, messages: result.rows });
    } catch (error) {
        console.error('Error fetching messages:', error);
        res.status(500).json({ success: false, error: 'Failed to fetch messages' });
    }
});

app.post('/api/admin/messages', async (req, res) => {
    try {
        const { userId, content } = req.body;
        await getPool().query(
            'INSERT INTO messages (user_id, content, sender) VALUES ($1, $2, $3)',
            [userId, content, 'admin']
        );
        res.json({ success: true });
    } catch (error) {
        console.error('Error sending message:', error);
        res.status(500).json({ success: false, error: 'Failed to send message' });
    }
});

app.delete('/api/admin/messages/:messageId',  async (req, res) => {
    const { messageId } = req.params;
    try {
        await getPool().query('DELETE FROM messages WHERE id = $1', [messageId]);
        res.json({ success: true });
    } catch (error) {
        console.error('Error deleting message:', error);
        res.status(500).json({ success: false, error: 'Failed to delete message' });
    }
});

app.delete('/api/admin/users/:userId',  async (req, res) => {
    const { userId } = req.params;
    try {
        // First delete all messages for the user
        await getPool().query('DELETE FROM messages WHERE user_id = $1', [userId]);
        // Then delete the user
        await getPool().query('DELETE FROM users WHERE id = $1', [userId]);
        res.json({ success: true });
    } catch (error) {
        console.error('Error deleting user:', error);
        res.status(500).json({ success: false, error: 'Failed to delete user' });
    }
});

app.get('/api/admin/submissions', async (req, res) => {
    try {
        const result = await getPool().query(`
            SELECT s.*, u.email as user_email 
            FROM submissions s 
            JOIN users u ON s.user_id = u.id 
            ORDER BY s.created_at DESC
        `);
        res.json({ success: true, submissions: result.rows });
    } catch (error) {
        console.error('Error fetching submissions:', error);
        res.status(500).json({ success: false, error: 'Failed to fetch submissions' });
    }
});

// Update submission status
app.post('/api/admin/submissions/:submissionId/status', async (req, res) => {
    const { submissionId } = req.params;
    const { status } = req.body;

    // Validate status
    const validStatuses = ['pending', 'approved', 'rejected', 'paid', 'closed'];
    if (!validStatuses.includes(status)) {
        return res.status(400).json({ 
            success: false, 
            error: `Invalid status. Must be one of: ${validStatuses.join(', ')}` 
        });
    }

    try {
        // First check if submission exists
        const checkResult = await getPool().query(
            'SELECT * FROM submissions WHERE id = $1',
            [submissionId]
        );

        if (checkResult.rows.length === 0) {
            return res.status(404).json({ success: false, error: 'Submission not found' });
        }

        // Update submission status with a CASE statement to ensure valid status
        const updateResult = await getPool().query(
            `UPDATE submissions 
             SET status = CASE 
                WHEN $1 IN ('pending', 'approved', 'rejected', 'paid', 'closed') 
                THEN $1 
                ELSE status 
             END
             WHERE id = $2 
             RETURNING *`,
            [status, submissionId]
        );

        if (updateResult.rows.length === 0) {
            return res.status(500).json({ 
                success: false, 
                error: 'Failed to update submission status' 
            });
        }

        res.json({ 
            success: true, 
            submission: updateResult.rows[0],
            message: `Status updated to ${status}`
        });
    } catch (error) {
        console.error('Error updating submission status:', error);
        res.status(500).json({ 
            success: false, 
            error: 'Failed to update submission status',
            details: error.message
        });
    }
});

// Get submission details including video proof
app.get('/api/admin/submissions/:submissionId', async (req, res) => {
    const { submissionId } = req.params;
    try {
        const result = await getPool().query(`
            SELECT s.*, u.email as user_email 
            FROM submissions s 
            JOIN users u ON s.user_id = u.id 
            WHERE s.id = $1
        `, [submissionId]);
        
        if (result.rows.length === 0) {
            return res.status(404).json({ success: false, error: 'Submission not found' });
        }
        
        res.json({ success: true, submission: result.rows[0] });
    } catch (error) {
        console.error('Error fetching submission details:', error);
        res.status(500).json({ success: false, error: 'Failed to fetch submission details' });
    }
});

// Check if submission is open (Sunday 9am-9pm)
app.get('/isubmissionopen', (req, res) => {
    const now = new Date();
    const dayOfWeek = now.getDay(); // 0 = Sunday, 1 = Monday, ..., 6 = Saturday
    const hour = now.getHours();
    
    // Check if it's Sunday (day 0) and between 9am (9) and 9pm (21)
    const isSubmissionOpen = dayOfWeek === 0 && hour >= 9 && hour < 21;
    
    log('info', 'Submission status checked', { 
        dayOfWeek: dayOfWeek,
        hour: hour,
        isOpen: isSubmissionOpen,
        ip: req.ip 
    });
    
    res.json({ 
        success: true, 
        isSubmissionOpen: isSubmissionOpen,
        currentTime: now.toISOString(),
        dayOfWeek: dayOfWeek,
        hour: hour
    });
});

// Catch-all route for React Router - serve index.html for all non-API routes
app.get('*', (req, res) => {
    // Skip API routes
    if (req.path.startsWith('/api/')) {
        return res.status(404).json({ error: 'API endpoint not found' });
    }
    
    // Skip the /isubmissionopen endpoint
    if (req.path === '/isubmissionopen') {
        return res.status(404).json({ error: 'Endpoint not found' });
    }
    
    log('info', 'React route accessed', { 
        path: req.path, 
        userAgent: req.get('User-Agent'),
        ip: req.ip 
    });
    
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// Socket.IO connection handling
io.on('connection', (socket) => {
    log('info', 'Client connected to server logs', { 
        socketId: socket.id,
        totalConnections: io.engine.clientsCount 
    });
    
    // Send existing logs to new client
    socket.emit('server-log', {
        type: 'info',
        message: 'Connected to server logs',
        details: { 
            socketId: socket.id,
            totalLogs: serverLogs.length 
        }
    });
    
    socket.on('disconnect', () => {
        log('info', 'Client disconnected from server logs', { 
            socketId: socket.id,
            totalConnections: io.engine.clientsCount 
        });
    });
    
    socket.on('request-logs', () => {
        log('info', 'Client requested historical logs', { socketId: socket.id });
        // Send last 100 logs
        const recentLogs = serverLogs.slice(0, 100);
        socket.emit('historical-logs', recentLogs);
    });
});

// Error handling
process.on('uncaughtException', (error) => {
    log('error', 'Uncaught Exception', { 
        error: error.message,
        stack: error.stack 
    });
});

process.on('unhandledRejection', (reason, promise) => {
    log('error', 'Unhandled Rejection', { 
        reason: reason,
        promise: promise 
    });
});

// Periodic system logs
setInterval(() => {
    const memoryUsage = process.memoryUsage();
    log('info', 'System status', {
        memory: {
            rss: Math.round(memoryUsage.rss / 1024 / 1024) + 'MB',
            heapUsed: Math.round(memoryUsage.heapUsed / 1024 / 1024) + 'MB',
            heapTotal: Math.round(memoryUsage.heapTotal / 1024 / 1024) + 'MB'
        },
        uptime: Math.round(process.uptime()) + 's',
        connections: io.engine.clientsCount
    });
}, 30000); // Every 30 seconds

module.exports = app;