<?php
// Ensure no output before session_start
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Start session at the very beginning
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Set session variables to simulate admin login
if (!isset($_SESSION['user_id'])) {
    $_SESSION['user_id'] = 1;
    $_SESSION['username'] = 'admin';
    $_SESSION['role'] = 'admin';
}

// Database connection
$config = [
    'db_host' => 'localhost',
    'db_user' => 'nsaorg_mobileapp',
    'db_pass' => '.com/iisADMIN123',
    'db_name' => 'nsaorg_mobileapp'
];

// Connect to database
$conn = new mysqli(
    $config['db_host'],
    $config['db_user'],
    $config['db_pass'],
    $config['db_name']
);

// Initialize stats and arrays
$stats = [
    'reports_count' => 0,
    'recent_reports_count' => 0,
    'categories_count' => 0,
    'indicators_count' => 0
];
$recent_reports = [];
$recent_indicators = [];

// Get basic stats if connection succeeds
if (!$conn->connect_error) {
    try {
        // Reports count
        $result = $conn->query("SELECT COUNT(*) as count FROM reports");
        if ($result && $row = $result->fetch_assoc()) {
            $stats['reports_count'] = $row['count'];
        }
        
        // Recent reports count (last 30 days)
        $result = $conn->query("SELECT COUNT(*) as count FROM reports WHERE report_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)");
        if ($result && $row = $result->fetch_assoc()) {
            $stats['recent_reports_count'] = $row['count'];
        }
        
        // Categories count
        $result = $conn->query("SELECT COUNT(*) as count FROM report_categories");
        if ($result && $row = $result->fetch_assoc()) {
            $stats['categories_count'] = $row['count'];
        }
        
        // Indicators count
        $result = $conn->query("SELECT COUNT(*) as count FROM national_indicators");
        if ($result && $row = $result->fetch_assoc()) {
            $stats['indicators_count'] = $row['count'];
        }
        
        // Get recent reports
        $result = $conn->query("SELECT * FROM reports ORDER BY report_date DESC LIMIT 5");
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $recent_reports[] = $row;
            }
        }
        
        // Get recent indicators
        $result = $conn->query("SELECT * FROM national_indicators ORDER BY indicator_id DESC LIMIT 5");
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $recent_indicators[] = $row;
            }
        }
    } catch (Exception $e) {
        // Log error but continue
        error_log("Database error: " . $e->getMessage());
    }
    
    // Close connection
    $conn->close();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard - NSA Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css">
    <style>
        :root {
            --primary-color: #1f3889;
            --secondary-color: #ad9237;
            --primary-dark: #152a6a;
            --secondary-dark: #967d2f;
        }
        
        body {
            min-height: 100vh;
            background-color: #f8f9fa;
            padding: 20px;
        }
        
        .header {
            background-color: white;
            padding: 15px 20px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
            border-radius: 5px;
        }
        
        .header h1 {
            color: var(--primary-color);
            font-size: 1.5rem;
            margin-bottom: 0;
        }
        
        .dashboard-card {
            background-color: white;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
            padding: 20px;
            height: 100%;
            margin-bottom: 20px;
        }
        
        .dashboard-card .card-icon {
            font-size: 2rem;
            margin-bottom: 10px;
        }
        
        .dashboard-card .card-title {
            font-size: 0.9rem;
            color: #6c757d;
            margin-bottom: 5px;
        }
        
        .dashboard-card .card-value {
            font-size: 1.5rem;
            font-weight: 600;
        }
        
        .btn-primary {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }
        
        .btn-primary:hover {
            background-color: var(--primary-dark);
            border-color: var(--primary-dark);
        }
        
        .btn-success {
            background-color: var(--secondary-color);
            border-color: var(--secondary-color);
        }
        
        .btn-success:hover {
            background-color: var(--secondary-dark);
            border-color: var(--secondary-dark);
        }
        
        .footer {
            padding: 15px 20px;
            text-align: center;
            color: #6c757d;
            font-size: 0.9rem;
            border-top: 1px solid #eee;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <!-- Header -->
        <!-- Header -->
    <div class="header d-flex justify-content-between align-items-center">
        <div class="d-flex align-items-center">
            <img src="assets/nsa-logo.jpeg" alt="NSA Logo" height="40" class="me-3">
            <h1>NSA Admin Dashboard</h1>
        </div>
        <div>
            <span class="me-2"><?php echo htmlspecialchars($_SESSION['username']); ?></span>
            <i class="fas fa-user-circle"></i>
        </div>
    </div>
    
    <div class="container">
        <!-- Alert -->
        <div class="alert alert-success mb-4">
            <h4 class="alert-heading">Welcome to the NSA Admin Dashboard!</h4>
            <p>You are now logged in with admin access. You can view and manage reports, indicators, and other data.</p>
        </div>
        
        <!-- Stats cards -->
        <div class="row mb-4">
            <div class="col-md-3 mb-3">
                <div class="dashboard-card">
                    <div class="card-icon text-primary">
                        <i class="fas fa-file-alt"></i>
                    </div>
                    <div class="card-title">Total Reports</div>
                    <div class="card-value"><?php echo number_format($stats['reports_count']); ?></div>
                </div>
            </div>
            
            <div class="col-md-3 mb-3">
                <div class="dashboard-card">
                    <div class="card-icon text-success">
                        <i class="fas fa-calendar-check"></i>
                    </div>
                    <div class="card-title">Recent Reports (30d)</div>
                    <div class="card-value"><?php echo number_format($stats['recent_reports_count']); ?></div>
                </div>
            </div>
            
            <div class="col-md-3 mb-3">
                <div class="dashboard-card">
                    <div class="card-icon text-info">
                        <i class="fas fa-tags"></i>
                    </div>
                    <div class="card-title">Report Categories</div>
                    <div class="card-value"><?php echo number_format($stats['categories_count']); ?></div>
                </div>
            </div>
            
            <div class="col-md-3 mb-3">
                <div class="dashboard-card">
                    <div class="card-icon text-warning">
                        <i class="fas fa-chart-line"></i>
                    </div>
                    <div class="card-title">Total Indicators</div>
                    <div class="card-value"><?php echo number_format($stats['indicators_count']); ?></div>
                </div>
            </div>
        </div>
        
        <!-- Quick access buttons -->
        <div class="dashboard-card mb-4">
            <h5 class="mb-3">Navigation</h5>
            <div class="row">
                <div class="col-md-3 mb-2">
                    <a href="reports.php" class="btn btn-primary w-100">
                        <i class="fas fa-file-alt me-1"></i> Reports
                    </a>
                </div>
                <div class="col-md-3 mb-2">
                    <a href="indicators.php" class="btn btn-success w-100">
                        <i class="fas fa-chart-line me-1"></i> Indicators
                    </a>
                </div>
                <div class="col-md-3 mb-2">
                    <a href="report-categories.php" class="btn btn-info text-white w-100">
                        <i class="fas fa-tags me-1"></i> Categories
                    </a>
                </div>
                <div class="col-md-3 mb-2">
                    <a href="settings.php" class="btn btn-secondary w-100">
                        <i class="fas fa-cog me-1"></i> Settings
                    </a>
                </div>
            </div>
        </div>
        
        <!-- Recent reports -->
        <div class="row">
            <div class="col-md-6 mb-4">
                <div class="dashboard-card h-100">
                    <h5 class="mb-3">Recent Reports</h5>
                    <?php if (empty($recent_reports)): ?>
                        <p class="text-muted">No reports found</p>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Title</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($recent_reports as $report): ?>
                                        <tr>
                                            <td><?php echo isset($report['id']) ? htmlspecialchars($report['id']) : 
                                                (isset($report['report_id']) ? htmlspecialchars($report['report_id']) : ''); ?></td>
                                            <td><?php echo isset($report['title']) ? htmlspecialchars($report['title']) : 
                                                (isset($report['report_title']) ? htmlspecialchars($report['report_title']) : ''); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="col-md-6 mb-4">
                <div class="dashboard-card h-100">
                    <h5 class="mb-3">Recent Indicators</h5>
                    <?php if (empty($recent_indicators)): ?>
                        <p class="text-muted">No indicators found</p>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Name</th>
                                        <th>Value</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($recent_indicators as $indicator): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($indicator['indicator_id'] ?? ''); ?></td>
                                            <td><?php echo htmlspecialchars($indicator['indicator_name'] ?? ''); ?></td>
                                            <td><?php echo htmlspecialchars($indicator['value'] ?? ''); ?></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <!-- Diagnostic links -->
        <div class="dashboard-card">
            <h5 class="mb-3">Diagnostic Tools</h5>
            <div class="list-group">
                <a href="test.php" class="list-group-item list-group-item-action d-flex align-items-center">
                    <i class="fas fa-stethoscope me-3 text-primary"></i>
                    <div>
                        <h6 class="mb-1">Diagnostic Test</h6>
                        <p class="mb-0 small text-muted">Check database connection and server information</p>
                    </div>
                </a>
                <a href="backup_index.php" class="list-group-item list-group-item-action d-flex align-items-center">
                    <i class="fas fa-life-ring me-3 text-success"></i>
                    <div>
                        <h6 class="mb-1">Backup Dashboard</h6>
                        <p class="mb-0 small text-muted">Simplified version of the dashboard</p>
                    </div>
                </a>
            </div>
        </div>
    </div>
    
    <!-- Footer -->
    <div class="footer">
        <p>NSA Admin Dashboard &copy; <?php echo date('Y'); ?> Namibia Statistics Agency</p>
    </div>
    
    <!-- Scripts -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>