<?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']
);

// Check if indicator_themes table exists
$themes_exists = false;
$result = $conn->query("SHOW TABLES LIKE 'indicator_themes'");
if ($result && $result->num_rows > 0) {
    $themes_exists = true;
}

// Create indicator_themes table if it doesn't exist
if (!$themes_exists) {
    $create_table_sql = "CREATE TABLE indicator_themes (
        theme_id INT(11) AUTO_INCREMENT PRIMARY KEY,
        theme_name VARCHAR(100) NOT NULL,
        theme_description TEXT,
        theme_color VARCHAR(50),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    )";
    
    if ($conn->query($create_table_sql)) {
        // Insert default themes
        $default_themes = [
            ['Economic', 'Economic indicators', '#28a745'],
            ['Social', 'Social indicators', '#007bff'],
            ['Environmental', 'Environmental indicators', '#17a2b8'],
            ['Governance', 'Governance indicators', '#6610f2']
        ];
        
        $theme_stmt = $conn->prepare("INSERT INTO indicator_themes (theme_name, theme_description, theme_color) VALUES (?, ?, ?)");
        $theme_stmt->bind_param("sss", $theme_name, $theme_desc, $theme_color);
        
        foreach ($default_themes as $theme) {
            $theme_name = $theme[0];
            $theme_desc = $theme[1];
            $theme_color = $theme[2];
            $theme_stmt->execute();
        }
        
        $theme_stmt->close();
        $themes_exists = true;
    }
}

// Check if theme_id column exists in national_indicators
$theme_id_exists = false;
$result = $conn->query("SHOW COLUMNS FROM national_indicators LIKE 'theme_id'");
if ($result && $result->num_rows > 0) {
    $theme_id_exists = true;
}

// Add theme_id column if it doesn't exist
if (!$theme_id_exists) {
    $conn->query("ALTER TABLE national_indicators ADD COLUMN theme_id INT(11) DEFAULT NULL");
}

// Initialize variables
$indicators = [];
$themes = [];
$total_indicators = 0;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 10;
$theme_filter = isset($_GET['theme_id']) ? (int)$_GET['theme_id'] : 0;

// Get total indicator count
$count_sql = "SELECT COUNT(*) as total FROM national_indicators";
if ($theme_filter > 0) {
    $count_sql .= " WHERE theme_id = $theme_filter";
}

$count_result = $conn->query($count_sql);
if ($count_result && $row = $count_result->fetch_assoc()) {
    $total_indicators = $row['total'];
}

// Calculate pagination
$total_pages = ceil($total_indicators / $per_page);
if ($page > $total_pages && $total_pages > 0) {
    $page = $total_pages;
}
$offset = ($page - 1) * $per_page;

// Get themes for filter
if ($themes_exists) {
    $theme_result = $conn->query("SELECT * FROM indicator_themes ORDER BY theme_name");
    if ($theme_result) {
        while ($row = $theme_result->fetch_assoc()) {
            $themes[] = $row;
        }
    }
}

// Get indicators with pagination
$indicator_sql = "SELECT ni.*, 
                 " . ($themes_exists ? "t.theme_name, t.theme_color" : "'' as theme_name, '' as theme_color") . "
                 FROM national_indicators ni
                 " . ($themes_exists ? "LEFT JOIN indicator_themes t ON ni.theme_id = t.theme_id" : "") . "
                 " . ($theme_filter > 0 ? "WHERE ni.theme_id = $theme_filter" : "") . "
                 ORDER BY ni.indicator_id DESC
                 LIMIT $offset, $per_page";

$result = $conn->query($indicator_sql);
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $indicators[] = $row;
    }
}

// Close database connection
$conn->close();

// Utility function for pagination links
function get_pagination($total_pages, $current_page, $base_url) {
    $output = '<nav aria-label="Page navigation"><ul class="pagination justify-content-center">';
    
    // Previous button
    if ($current_page > 1) {
        $output .= '<li class="page-item"><a class="page-link" href="' . $base_url . '&page=' . ($current_page - 1) . '">Previous</a></li>';
    } else {
        $output .= '<li class="page-item disabled"><span class="page-link">Previous</span></li>';
    }
    
    // Page numbers
    $start_page = max(1, $current_page - 2);
    $end_page = min($total_pages, $current_page + 2);
    
    for ($i = $start_page; $i <= $end_page; $i++) {
        if ($i == $current_page) {
            $output .= '<li class="page-item active"><span class="page-link">' . $i . '</span></li>';
        } else {
            $output .= '<li class="page-item"><a class="page-link" href="' . $base_url . '&page=' . $i . '">' . $i . '</a></li>';
        }
    }
    
    // Next button
    if ($current_page < $total_pages) {
        $output .= '<li class="page-item"><a class="page-link" href="' . $base_url . '&page=' . ($current_page + 1) . '">Next</a></li>';
    } else {
        $output .= '<li class="page-item disabled"><span class="page-link">Next</span></li>';
    }
    
    $output .= '</ul></nav>';
    return $output;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Indicators - NSA Admin Dashboard</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;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .header h1 {
            color: var(--primary-color);
            font-size: 1.5rem;
            margin-bottom: 0;
        }

        .content-card {
            background-color: white;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
            margin-bottom: 20px;
        }
        
        .theme-badge {
            display: inline-block;
            padding: 0.25rem 0.5rem;
            border-radius: 0.25rem;
            color: white;
            font-size: 0.8rem;
        }
        
        .nav-pills .nav-link.active {
            background-color: var(--primary-color);
        }
        
        .nav-pills .nav-link {
            color: var(--primary-color);
        }
        
        .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);
        }
        
        .footer {
            padding: 15px 20px;
            text-align: center;
            color: #6c757d;
            font-size: 0.9rem;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <!-- Header -->
    <div class="header">
        <h1>National Indicators</h1>
        <div class="user-info">
            <span class="me-2"><?php echo htmlspecialchars($_SESSION['username']); ?></span>
            <i class="fas fa-user-circle"></i>
        </div>
    </div>
    
    <div class="container-fluid">
        <div class="row">
            <!-- Navigation Column -->
            <div class="col-md-3 mb-4">
                <div class="content-card">
                    <div class="card-body">
                        <h5 class="mb-3">Navigation</h5>
                        <div class="list-group">
                            <a href="index.php" class="list-group-item list-group-item-action">
                                <i class="fas fa-tachometer-alt me-2"></i> Dashboard
                            </a>
                            <a href="reports.php" class="list-group-item list-group-item-action">
                                <i class="fas fa-file-alt me-2"></i> Reports
                            </a>
                            <a href="indicators.php" class="list-group-item list-group-item-action active">
                                <i class="fas fa-chart-line me-2"></i> Indicators
                            </a>
                            <a href="setup_themes.php" class="list-group-item list-group-item-action">
                                <i class="fas fa-palette me-2"></i> Setup Themes
                            </a>
                        </div>
                        
                        <!-- Theme Filter -->
                        <?php if (!empty($themes)): ?>
                        <div class="mt-4">
                            <h5 class="mb-3">Filter by Theme</h5>
                            <form action="indicators.php" method="get" class="mb-3">
                                <select class="form-select mb-2" name="theme_id">
                                    <option value="0">All Themes</option>
                                    <?php foreach ($themes as $theme): ?>
                                    <option value="<?php echo $theme['theme_id']; ?>" <?php echo ($theme_filter == $theme['theme_id']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($theme['theme_name']); ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                                <button type="submit" class="btn btn-primary btn-sm w-100">Apply Filter</button>
                            </form>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            
            <!-- Main Content Column -->
            <div class="col-md-9">
                <div class="content-card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">National Indicators</h5>
                    </div>
                    <div class="card-body">
                        <!-- Stats Summary -->
                        <div class="row mb-4">
                            <div class="col-md-4">
                                <div class="card bg-light">
                                    <div class="card-body text-center">
                                        <i class="fas fa-chart-line fs-3 text-primary mb-2"></i>
                                        <h5 class="card-title">Total Indicators</h5>
                                        <p class="card-text fs-4 fw-bold"><?php echo number_format($total_indicators); ?></p>
                                    </div>
                                </div>
                            </div>
                            <?php if ($themes_exists): ?>
                            <div class="col-md-4">
                                <div class="card bg-light">
                                    <div class="card-body text-center">
                                        <i class="fas fa-palette fs-3 text-success mb-2"></i>
                                        <h5 class="card-title">Theme Categories</h5>
                                        <p class="card-text fs-4 fw-bold"><?php echo number_format(count($themes)); ?></p>
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                        
                        <!-- Indicators Table -->
                        <?php if (empty($indicators)): ?>
                            <div class="alert alert-info">
                                <i class="fas fa-info-circle me-2"></i>
                                No indicators found. Please add some indicators.
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>Indicator Name</th>
                                            <th>Value</th>
                                            <th>Unit</th>
                                            <th>Year</th>
                                            <?php if ($themes_exists): ?>
                                            <th>Theme</th>
                                            <?php endif; ?>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($indicators as $item): ?>
                                        <tr>
                                            <td><?php echo $item['indicator_id']; ?></td>
                                            <td><?php echo htmlspecialchars($item['indicator_name']); ?></td>
                                            <td><?php echo htmlspecialchars($item['value']); ?></td>
                                            <td><?php echo htmlspecialchars($item['unit']); ?></td>
                                            <td><?php echo htmlspecialchars($item['year']); ?></td>
                                            <?php if ($themes_exists): ?>
                                            <td>
                                                <?php if (!empty($item['theme_name'])): ?>
                                                <span class="theme-badge" style="background-color: <?php echo htmlspecialchars($item['theme_color']); ?>">
                                                    <?php echo htmlspecialchars($item['theme_name']); ?>
                                                </span>
                                                <?php else: ?>
                                                <span class="text-muted">None</span>
                                                <?php endif; ?>
                                            </td>
                                            <?php endif; ?>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                                
                                <!-- Pagination -->
                                <?php if ($total_pages > 1): ?>
                                <div class="mt-4">
                                    <?php echo get_pagination($total_pages, $page, 'indicators.php?action=list' . ($theme_filter > 0 ? "&theme_id=$theme_filter" : '')); ?>
                                </div>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </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>