<?php
// Simple submission viewer for administrators
// IMPORTANT: Add proper authentication before using in production

session_start();

// Basic authentication - REPLACE WITH PROPER AUTH IN PRODUCTION
$AUTH_PASSWORD = '6JASrjTkN77yyHslZhku6pDv'; // Change this!

if (!isset($_SESSION['authenticated']) || $_SESSION['authenticated'] !== true) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['password'])) {
        if ($_POST['password'] === $AUTH_PASSWORD) {
            $_SESSION['authenticated'] = true;
        } else {
            $error = 'Invalid password';
        }
    }
    
    if (!isset($_SESSION['authenticated']) || $_SESSION['authenticated'] !== true) {
        ?>
        <!DOCTYPE html>
        <html>
        <head>
            <title>Admin Login</title>
            <style>
                body { font-family: Arial, sans-serif; background: #f5f5f5; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; }
                .login-form { background: white; padding: 30px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
                input[type="password"] { padding: 10px; width: 200px; margin-bottom: 10px; }
                button { padding: 10px 20px; background: #179e83; color: white; border: none; border-radius: 4px; cursor: pointer; }
                .error { color: red; margin-bottom: 10px; }
            </style>
        </head>
        <body>
            <div class="login-form">
                <h2>Admin Login</h2>
                <?php if (isset($error)): ?>
                    <div class="error"><?php echo $error; ?></div>
                <?php endif; ?>
                <form method="POST">
                    <input type="password" name="password" placeholder="Enter password" required><br>
                    <button type="submit">Login</button>
                </form>
            </div>
        </body>
        </html>
        <?php
        exit;
    }
}

// Get all submission files
$submissionFiles = glob('../logs/submissions-*.json');
$allSubmissions = [];

foreach ($submissionFiles as $file) {
    $submissions = json_decode(file_get_contents($file), true);
    if ($submissions) {
        $allSubmissions = array_merge($allSubmissions, $submissions);
    }
}

// Sort by timestamp (newest first)
usort($allSubmissions, function($a, $b) {
    return strtotime($b['timestamp']) - strtotime($a['timestamp']);
});

// Handle CSV export
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="submissions-' . date('Y-m-d') . '.csv"');
    
    $output = fopen('php://output', 'w');
    fputcsv($output, ['Timestamp', 'Name', 'Email', 'Company', 'Service', 'Message', 'IP', 'User Agent', 'Referrer']);
    
    foreach ($allSubmissions as $submission) {
        fputcsv($output, [
            $submission['timestamp'],
            $submission['name'],
            $submission['email'],
            $submission['company'],
            $submission['service'],
            $submission['message'],
            $submission['ip'],
            $submission['user_agent'],
            $submission['referrer']
        ]);
    }
    
    fclose($output);
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Contact Form Submissions</title>
    <style>
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            background: #f5f5f5;
            margin: 0;
            padding: 20px;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        .header {
            background: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }
        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            text-align: center;
        }
        .stat-value {
            font-size: 36px;
            font-weight: bold;
            color: #179e83;
        }
        .stat-label {
            color: #666;
            margin-top: 5px;
        }
        .submissions {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            overflow: hidden;
        }
        .submission {
            padding: 20px;
            border-bottom: 1px solid #eee;
        }
        .submission:last-child {
            border-bottom: none;
        }
        .submission-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
        }
        .submission-date {
            color: #666;
            font-size: 14px;
        }
        .submission-email {
            color: #179e83;
            font-weight: 500;
        }
        .submission-details {
            display: grid;
            grid-template-columns: 120px 1fr;
            gap: 10px;
            margin-top: 10px;
        }
        .detail-label {
            font-weight: 500;
            color: #666;
        }
        .message {
            background: #f9f9f9;
            padding: 15px;
            border-radius: 4px;
            margin-top: 10px;
            white-space: pre-wrap;
        }
        .btn {
            padding: 10px 20px;
            background: #179e83;
            color: white;
            text-decoration: none;
            border-radius: 4px;
            display: inline-block;
            border: none;
            cursor: pointer;
        }
        .btn:hover {
            background: #5a67d8;
        }
        .btn-secondary {
            background: #e2e8f0;
            color: #333;
        }
        .btn-secondary:hover {
            background: #cbd5e0;
        }
        .empty {
            text-align: center;
            padding: 60px;
            color: #666;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>Contact Form Submissions</h1>
            <div>
                <a href="?export=csv" class="btn btn-secondary">Export CSV</a>
                <a href="?logout" class="btn btn-secondary">Logout</a>
            </div>
        </div>
        
        <div class="stats">
            <div class="stat-card">
                <div class="stat-value"><?php echo count($allSubmissions); ?></div>
                <div class="stat-label">Total Submissions</div>
            </div>
            <div class="stat-card">
                <div class="stat-value"><?php 
                    $today = date('Y-m-d');
                    $todayCount = count(array_filter($allSubmissions, function($s) use ($today) {
                        return date('Y-m-d', strtotime($s['timestamp'])) === $today;
                    }));
                    echo $todayCount;
                ?></div>
                <div class="stat-label">Today</div>
            </div>
            <div class="stat-card">
                <div class="stat-value"><?php 
                    $thisMonth = date('Y-m');
                    $monthCount = count(array_filter($allSubmissions, function($s) use ($thisMonth) {
                        return date('Y-m', strtotime($s['timestamp'])) === $thisMonth;
                    }));
                    echo $monthCount;
                ?></div>
                <div class="stat-label">This Month</div>
            </div>
        </div>
        
        <div class="submissions">
            <?php if (empty($allSubmissions)): ?>
                <div class="empty">
                    <p>No submissions yet.</p>
                </div>
            <?php else: ?>
                <?php foreach ($allSubmissions as $submission): ?>
                    <div class="submission">
                        <div class="submission-header">
                            <div>
                                <strong><?php echo htmlspecialchars($submission['name']); ?></strong>
                                <span class="submission-email"><?php echo htmlspecialchars($submission['email']); ?></span>
                            </div>
                            <div class="submission-date">
                                <?php echo date('F j, Y g:i A', strtotime($submission['timestamp'])); ?>
                            </div>
                        </div>
                        
                        <div class="submission-details">
                            <?php if (!empty($submission['company'])): ?>
                                <div class="detail-label">Company:</div>
                                <div><?php echo htmlspecialchars($submission['company']); ?></div>
                            <?php endif; ?>
                            
                            <?php if (!empty($submission['service'])): ?>
                                <div class="detail-label">Service:</div>
                                <div><?php echo htmlspecialchars($submission['service']); ?></div>
                            <?php endif; ?>
                            
                            <div class="detail-label">IP Address:</div>
                            <div><?php echo htmlspecialchars($submission['ip']); ?></div>
                        </div>
                        
                        <div class="message">
                            <?php echo htmlspecialchars($submission['message']); ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
    
    <?php
    // Handle logout
    if (isset($_GET['logout'])) {
        session_destroy();
        header('Location: view-submissions.php');
        exit;
    }
    ?>
</body>
</html>