<?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 connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// 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;
$error_message = null;

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

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

// Get themes for filter if themes table exists
if ($themes_exists) {
    try {
        // Simple query to get all themes
        $theme_sql = "SELECT * FROM themes ORDER BY theme_name";
        $theme_result = $conn->query($theme_sql);
        if ($theme_result) {
            while ($row = $theme_result->fetch_assoc()) {
                $themes[] = $row;
            }
        }
    } catch (Exception $e) {
        $error_message = "Error getting themes: " . $e->getMessage();
    }
}

// Get indicators count and data if table exists
if ($indicators_table_exists && !$error_message) {
    try {
        // 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 indicators with pagination - using the simplest query possible
        if ($themes_exists) {
            $indicator_sql = "SELECT ni.*, t.theme_name
                             FROM national_indicators ni
                             LEFT JOIN 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";
        } else {
            $indicator_sql = "SELECT * 
                             FROM national_indicators
                             " . ($theme_filter > 0 ? "WHERE theme_id = $theme_filter" : "") . "
                             ORDER BY indicator_id DESC
                             LIMIT $offset, $per_page";
        }
        
        $result = $conn->query($indicator_sql);
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $indicators[] = $row;
            }
        } else {
            $error_message = "Error executing query: " . $conn->error;
        }
    } catch (Exception $e) {
        $error_message = "Error processing indicators: " . $e->getMessage();
    }
}

// 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;
            --sidebar-width: 250px;
        }
        
        body {
            min-height: 100vh;
            background-color: #f8f9fa;
        }
        
        /* Sidebar */
        .sidebar {
            width: var(--sidebar-width);
            position: fixed;
            top: 0;
            left: 0;
            height: 100%;
            z-index: 1000;
            background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
            color: white;
            padding-top: 20px;
            transition: all 0.3s;
        }
        
        .sidebar-header {
            padding: 10px 20px;
            text-align: center;
            margin-bottom: 20px;
        }
        
        .sidebar-header img {
            max-width: 120px;
            margin-bottom: 10px;
        }
        
        .sidebar-menu {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        
        .sidebar-menu li {
            margin-bottom: 5px;
        }
        
        .sidebar-menu a {
            color: rgba(255, 255, 255, 0.8);
            text-decoration: none;
            padding: 12px 20px;
            display: block;
            transition: all 0.3s;
            border-left: 4px solid transparent;
        }
        
        .sidebar-menu a:hover, .sidebar-menu a.active {
            color: white;
            background-color: rgba(255, 255, 255, 0.1);
            border-left-color: var(--secondary-color);
        }
        
        .sidebar-menu i {
            margin-right: 10px;
            width: 20px;
            text-align: center;
        }
        
        /* Main content */
        .main-content {
            margin-left: var(--sidebar-width);
            padding: 20px;
            transition: all 0.3s;
        }
        
        /* Header */
        .main-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;
        }
        
        .main-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;
            background-color: #6c757d; /* Default gray color */
        }
        
        .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 {
            margin-left: var(--sidebar-width);
            padding: 15px 20px;
            text-align: center;
            color: #6c757d;
            font-size: 0.9rem;
            border-top: 1px solid #eee;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .sidebar {
                width: 0;
                padding-top: 60px;
            }
            
            .sidebar.active {
                width: var(--sidebar-width);
            }
            
            .main-content, .footer {
                margin-left: 0;
            }
            
            .main-content.sidebar-active, .footer.sidebar-active {
                margin-left: var(--sidebar-width);
            }
            
            .sidebar-toggle {
                display: block;
            }
        }
        
        .sidebar-toggle {
            display: none;
            position: fixed;
            top: 15px;
            left: 15px;
            z-index: 1050;
            background-color: var(--primary-color);
            border: none;
            color: white;
            width: 40px;
            height: 40px;
            border-radius: 3px;
        }
    </style>
</head>
<body>
    <!-- Sidebar toggle button (mobile) -->
    <button class="sidebar-toggle d-md-none" id="sidebarToggle">
        <i class="fas fa-bars"></i>
    </button>
    
    <!-- Sidebar -->
    <div class="sidebar">
        <div class="sidebar-header">
            <img src="assets/nsa-logo.jpeg" alt="NSA Logo" class="img-fluid">
            <h5>NSA Admin</h5>
        </div>
        
        <ul class="sidebar-menu">
            <li><a href="index.php"><i class="fas fa-tachometer-alt"></i> Dashboard</a></li>
            <li><a href="reports.php"><i class="fas fa-file-alt"></i> Reports</a></li>
            <li><a href="report-categories.php"><i class="fas fa-tags"></i> Report Categories</a></li>
            <li><a href="indicators.php" class="active"><i class="fas fa-chart-line"></i> Indicators</a></li>
            <li><a href="indicator-themes.php"><i class="fas fa-palette"></i> Indicator Themes</a></li>
            <li><a href="users.php"><i class="fas fa-users"></i> Users</a></li>
            <li><a href="settings.php"><i class="fas fa-cog"></i> Settings</a></li>
            <li><a href="login.php?action=logout"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
        </ul>
    </div>
    
    <!-- Main content -->
    <div class="main-content">
        <!-- Header -->
        <div class="main-header d-flex justify-content-between align-items-center">
            <h1>National Indicators</h1>
            <div class="user-info">
                <span class="me-2"><?php echo htmlspecialchars($_SESSION['username'] ?? 'Admin User'); ?></span>
                <i class="fas fa-user-circle"></i>
            </div>
        </div>
        
        <?php if (isset($_GET['success'])): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <?php echo htmlspecialchars($_GET['success']); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>
        
        <?php if (!empty($error_message)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?php echo $error_message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>
        
        <!-- Theme Filter -->
        <?php if (!empty($themes)): ?>
        <div class="content-card mb-4">
            <div class="card-header">
                <h5 class="mb-0">Filter by Theme</h5>
            </div>
            <div class="card-body">
                <form action="indicators.php" method="get">
                    <input type="hidden" name="action" value="list">
                    <div class="row align-items-end">
                        <div class="col-md-8 mb-2 mb-md-0">
                            <select class="form-select" 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>
                        </div>
                        <div class="col-md-4">
                            <button type="submit" class="btn btn-primary w-100">Apply Filter</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
        <?php endif; ?>
            
        <!-- Main Content -->
                <div class="content-card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">National Indicators</h5>
                        <a href="setup_indicators.php" class="btn btn-sm btn-primary">
                            <i class="fas fa-plus me-1"></i> Add New Indicator
                        </a>
                    </div>
                    <div class="card-body">
                        <?php if (!$indicators_table_exists): ?>
                            <div class="alert alert-warning">
                                <i class="fas fa-exclamation-triangle me-2"></i>
                                The national_indicators table does not exist. Please run the <a href="setup_indicators.php">setup</a> first.
                            </div>
                        <?php elseif ($error_message): ?>
                            <div class="alert alert-danger">
                                <i class="fas fa-exclamation-circle me-2"></i>
                                <strong>Error:</strong> <?php echo htmlspecialchars($error_message); ?>
                            </div>
                        <?php else: ?>
                            <!-- 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">
                                                        <?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?' . (isset($_GET['action']) ? 'action=' . $_GET['action'] : 'action=list') . ($theme_filter > 0 ? "&theme_id=$theme_filter" : '')); ?>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            <?php endif; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Footer -->
    <div class="footer">
        <p>&copy; <?php echo date('Y'); ?> Namibia Statistics Agency. All rights reserved.</p>
    </div>
    
    <?php if (isset($_GET['debug']) && $_GET['debug'] === '1'): ?>
    <div class="container mt-4">
        <div class="card">
            <div class="card-header bg-secondary text-white">
                <h5 class="mb-0">Debug Information</h5>
            </div>
            <div class="card-body">
                <h6>Database Tables</h6>
                <pre><?php 
                    $conn = new mysqli($config['db_host'], $config['db_user'], $config['db_pass'], $config['db_name']);
                    $tables = $conn->query("SHOW TABLES");
                    while ($table = $tables->fetch_array()) {
                        echo htmlspecialchars($table[0]) . "\n";
                        $columns = $conn->query("SHOW COLUMNS FROM " . $table[0]);
                        echo "  Columns:\n";
                        while ($col = $columns->fetch_assoc()) {
                            echo "    " . htmlspecialchars($col['Field']) . " - " . htmlspecialchars($col['Type']) . "\n";
                        }
                        echo "\n";
                    }
                    $conn->close();
                ?></pre>
                
                <h6>Generated SQL Query</h6>
                <pre><?php echo isset($indicator_sql) ? htmlspecialchars($indicator_sql) : "No query generated"; ?></pre>
                
                <h6>Themes Data</h6>
                <pre><?php print_r($themes); ?></pre>
                
                <h6>Indicators Data (First Row)</h6>
                <pre><?php echo !empty($indicators) ? print_r($indicators[0], true) : "No indicators found"; ?></pre>
            </div>
        </div>
    </div>
    <?php endif; ?>
    
    </div> <!-- End of main-content -->
    
    <!-- Footer -->
    <div class="footer">
        <p>&copy; <?php echo date('Y'); ?> Namibia Statistics Agency. All rights reserved.</p>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Mobile sidebar toggle functionality
        document.addEventListener('DOMContentLoaded', function() {
            const sidebarToggle = document.getElementById('sidebarToggle');
            if (sidebarToggle) {
                sidebarToggle.addEventListener('click', function() {
                    document.querySelector('.sidebar').classList.toggle('active');
                    document.querySelector('.main-content').classList.toggle('sidebar-active');
                    document.querySelector('.footer').classList.toggle('sidebar-active');
                });
            }
        });
    </script>
</body>
</html>