<?php
/**
 * Admin Dashboard for viewing contact form submissions
 */

require_once 'csp_config.php';
require_once 'Database.php';
require_once 'SubmissionTracker.php';
require_once 'AdminAuth.php';

// Send security headers
send_security_headers();

// Start session for admin authentication
session_start();

// Initialize admin auth
$adminAuth = new AdminAuth();
$isAuthenticated = isset($_SESSION['admin_authenticated']) && $_SESSION['admin_authenticated'] === true;

// Handle login
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['admin_login'])) {
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';
    
    try {
        $admin = $adminAuth->authenticate($username, $password);
        if ($admin) {
            $_SESSION['admin_authenticated'] = true;
            $_SESSION['admin_user'] = $admin;
            $isAuthenticated = true;
        } else {
            $loginError = 'Invalid username or password';
        }
    } catch (Exception $e) {
        $loginError = 'Login failed: ' . $e->getMessage();
    }
}

// Handle logout
if (isset($_GET['logout'])) {
    unset($_SESSION['admin_authenticated']);
    unset($_SESSION['admin_user']);
    $isAuthenticated = false;
    header('Location: admin_dashboard.php');
    exit;
}

// If not authenticated, show login form
if (!$isAuthenticated) {
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Login - Mark's Tech Solution</title>
    <link rel="stylesheet" href="contact_form_styles.css">
    <style>
        .login-container {
            max-width: 400px;
            margin: 100px auto;
            padding: 30px;
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .login-form {
            text-align: center;
        }
        .login-form input[type="text"],
        .login-form input[type="password"] {
            width: 100%;
            padding: 12px;
            margin: 10px 0;
            border: 2px solid #ddd;
            border-radius: 5px;
            font-size: 16px;
        }
        .login-form button {
            width: 100%;
            padding: 12px;
            background-color: #ff6600;
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 16px;
            cursor: pointer;
        }
        .login-form button:hover {
            background-color: #cc5200;
        }
        .error {
            color: #e74c3c;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <div class="login-container">
        <h1>Admin Login</h1>
        <form method="post" class="login-form">
            <input type="text" name="username" placeholder="Username" required>
            <input type="password" name="password" placeholder="Password" required>
            <button type="submit" name="admin_login">Login</button>
            <?php if (isset($loginError)): ?>
                <div class="error"><?php echo htmlspecialchars($loginError); ?></div>
            <?php endif; ?>
        </form>
    </div>
</body>
</html>
<?php
    exit;
}

// Initialize services
$submissionTracker = new SubmissionTracker();

// Handle actions
$action = $_GET['action'] ?? '';
$message = '';
$messageType = 'info';

if ($action === 'block_ip' && isset($_GET['ip'])) {
    $ip = $_GET['ip'];
    $reason = $_GET['reason'] ?? 'Manual block by admin';
    $submissionTracker->blockIp($ip, $reason);
    $message = "IP {$ip} has been blocked";
    $messageType = 'success';
}

if ($action === 'update_status' && isset($_GET['id']) && isset($_GET['status'])) {
    $submissionId = $_GET['id'];
    $status = $_GET['status'];
    $notes = $_GET['notes'] ?? '';
    $submissionTracker->updateSubmissionStatus($submissionId, $status, $notes);
    $message = "Submission status updated to {$status}";
    $messageType = 'success';
}

// Get data
$recentSubmissions = $submissionTracker->getRecentSubmissions(50);
$stats = $submissionTracker->getSubmissionStats(30);
$securityEvents = $submissionTracker->getSecurityEvents(20);

// Get summary stats
$totalSubmissions = count($recentSubmissions);
$processedCount = 0;
$spamCount = 0;
$errorCount = 0;

foreach ($recentSubmissions as $submission) {
    switch ($submission['submission_status']) {
        case 'processed':
            $processedCount++;
            break;
        case 'spam':
            $spamCount++;
            break;
        case 'error':
            $errorCount++;
            break;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Dashboard - Mark's Tech Solution</title>
    <link rel="stylesheet" href="contact_form_styles.css">
    <style>
        .dashboard-container {
            max-width: 1200px;
            margin: 20px auto;
            padding: 20px;
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 2px solid #eee;
        }
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            text-align: center;
        }
        .stat-number {
            font-size: 2em;
            font-weight: bold;
            color: #ff6600;
        }
        .stat-label {
            color: #666;
            margin-top: 5px;
        }
        .section {
            background: white;
            margin-bottom: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        .section-header {
            background: #ff6600;
            color: white;
            padding: 15px 20px;
            font-weight: bold;
        }
        .section-content {
            padding: 20px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        th {
            background-color: #f8f9fa;
            font-weight: bold;
        }
        tr:hover {
            background-color: #f5f5f5;
        }
        .status-badge {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.8em;
            font-weight: bold;
        }
        .status-pending { background-color: #fff3cd; color: #856404; }
        .status-processed { background-color: #d4edda; color: #155724; }
        .status-spam { background-color: #f8d7da; color: #721c24; }
        .status-error { background-color: #f8d7da; color: #721c24; }
        .action-buttons {
            display: flex;
            gap: 5px;
        }
        .btn {
            padding: 6px 12px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            text-decoration: none;
            font-size: 0.8em;
        }
        .btn-primary { background-color: #ff6600; color: white; }
        .btn-danger { background-color: #e74c3c; color: white; }
        .btn-success { background-color: #27ae60; color: white; }
        .btn:hover { opacity: 0.8; }
        .message {
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 5px;
            font-weight: 500;
        }
        .message.success { background-color: #d4edda; color: #155724; }
        .message.error { background-color: #f8d7da; color: #721c24; }
        .message.info { background-color: #d1ecf1; color: #0c5460; }
        .search-box {
            margin-bottom: 20px;
        }
        .search-box input {
            width: 300px;
            padding: 10px;
            border: 2px solid #ddd;
            border-radius: 5px;
        }
        .pagination {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin-top: 20px;
        }
        .pagination a {
            padding: 8px 12px;
            border: 1px solid #ddd;
            text-decoration: none;
            border-radius: 4px;
        }
        .pagination a.active {
            background-color: #3498db;
            color: white;
        }
    </style>
</head>
<body>
    <div class="dashboard-container">
        <div class="header">
            <h1>Admin Dashboard</h1>
            <a href="?logout=1" class="btn btn-danger">Logout</a>
        </div>

        <?php if ($message): ?>
            <div class="message <?php echo $messageType; ?>">
                <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endif; ?>

        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-number"><?php echo $totalSubmissions; ?></div>
                <div class="stat-label">Total Submissions</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo $processedCount; ?></div>
                <div class="stat-label">Processed</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo $spamCount; ?></div>
                <div class="stat-label">Spam</div>
            </div>
            <div class="stat-card">
                <div class="stat-number"><?php echo $errorCount; ?></div>
                <div class="stat-label">Errors</div>
            </div>
        </div>

        <div class="section">
            <div class="section-header">Recent Submissions</div>
            <div class="section-content">
                <div class="search-box">
                    <form method="get">
                        <input type="text" name="search" placeholder="Search submissions..." value="<?php echo htmlspecialchars($_GET['search'] ?? ''); ?>">
                        <button type="submit" class="btn btn-primary">Search</button>
                    </form>
                </div>
                
                <table>
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Message Preview</th>
                            <th>IP Address</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($recentSubmissions as $submission): ?>
                            <tr>
                                <td><?php echo date('M j, Y H:i', strtotime($submission['created_at'])); ?></td>
                                <td><?php echo htmlspecialchars($submission['name']); ?></td>
                                <td><?php echo htmlspecialchars($submission['email']); ?></td>
                                <td><?php echo htmlspecialchars(substr($submission['message_preview'], 0, 50)) . '...'; ?></td>
                                <td>
                                    <?php echo htmlspecialchars($submission['ip_address']); ?>
                                    <br>
                                    <small>Reps: <?php echo number_format($submission['reputation_score'], 2); ?></small>
                                </td>
                                <td>
                                    <span class="status-badge status-<?php echo $submission['submission_status']; ?>">
                                        <?php echo ucfirst($submission['submission_status']); ?>
                                    </span>
                                </td>
                                <td>
                                    <div class="action-buttons">
                                        <?php if ($submission['submission_status'] === 'pending'): ?>
                                            <a href="?action=update_status&id=<?php echo $submission['submission_id']; ?>&status=processed" class="btn btn-success">Process</a>
                                            <a href="?action=update_status&id=<?php echo $submission['submission_id']; ?>&status=spam" class="btn btn-danger">Spam</a>
                                        <?php endif; ?>
                                        <a href="?action=block_ip&ip=<?php echo $submission['ip_address']; ?>&reason=Admin%20block%20from%20dashboard" class="btn btn-danger" onclick="return confirm('Block this IP address?')">Block IP</a>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="section">
            <div class="section-header">Recent Security Events</div>
            <div class="section-content">
                <table>
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Event Type</th>
                            <th>IP Address</th>
                            <th>Details</th>
                            <th>Severity</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($securityEvents as $event): ?>
                            <tr>
                                <td><?php echo date('M j, Y H:i:s', strtotime($event['created_at'])); ?></td>
                                <td><?php echo htmlspecialchars($event['event_type']); ?></td>
                                <td><?php echo htmlspecialchars($event['ip_address']); ?></td>
                                <td><?php echo htmlspecialchars($event['event_details']); ?></td>
                                <td>
                                    <span class="status-badge status-<?php echo $event['severity']; ?>">
                                        <?php echo ucfirst($event['severity']); ?>
                                    </span>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="section">
            <div class="section-header">30-Day Statistics</div>
            <div class="section-content">
                <table>
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Total</th>
                            <th>Processed</th>
                            <th>Spam</th>
                            <th>Unique IPs</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($stats as $stat): ?>
                            <tr>
                                <td><?php echo date('M j, Y', strtotime($stat['submission_date'])); ?></td>
                                <td><?php echo $stat['total_submissions']; ?></td>
                                <td><?php echo $stat['processed_submissions']; ?></td>
                                <td><?php echo $stat['spam_submissions']; ?></td>
                                <td><?php echo $stat['unique_ips']; ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</body>
</html>
