<?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 message arrays
$success_messages = [];
$error_messages = [];

// Check if national_indicators table exists
$table_exists = false;
$result = $conn->query("SHOW TABLES LIKE 'national_indicators'");
if ($result && $result->num_rows > 0) {
    $table_exists = true;
    $success_messages[] = "✅ National indicators table exists.";
} else {
    $error_messages[] = "❌ National indicators table does not exist.";
    
    // Create the national_indicators table
    $create_table_sql = "CREATE TABLE national_indicators (
        indicator_id INT(11) AUTO_INCREMENT PRIMARY KEY,
        indicator_name VARCHAR(255) NOT NULL,
        description TEXT,
        value VARCHAR(50),
        unit VARCHAR(50),
        year VARCHAR(10),
        theme_id INT(11),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    )";
    
    if ($conn->query($create_table_sql)) {
        $success_messages[] = "✅ Created national_indicators table.";
        $table_exists = true;
    } else {
        $error_messages[] = "❌ Failed to create national_indicators table: " . $conn->error;
    }
}

// Check if theme_id column exists in national_indicators table
if ($table_exists) {
    $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;
        $success_messages[] = "✅ theme_id column exists in national_indicators table.";
    } else {
        $error_messages[] = "❌ theme_id column does not exist in national_indicators table.";
        
        // Add theme_id column
        if ($conn->query("ALTER TABLE national_indicators ADD COLUMN theme_id INT(11) DEFAULT NULL")) {
            $success_messages[] = "✅ Added theme_id column to national_indicators table.";
            $theme_id_exists = true;
        } else {
            $error_messages[] = "❌ Failed to add theme_id column: " . $conn->error;
        }
    }
}

// Check if themes table exists
$themes_table_exists = false;
$result = $conn->query("SHOW TABLES LIKE 'themes'");
if ($result && $result->num_rows > 0) {
    $themes_table_exists = true;
    $success_messages[] = "✅ Themes table exists.";
    
    // Check if we have any indicator themes
    $result = $conn->query("SELECT COUNT(*) as count FROM themes WHERE theme_type = 'indicator' OR theme_type IS NULL");
    $row = $result->fetch_assoc();
    if ($row['count'] > 0) {
        $success_messages[] = "✅ Found " . $row['count'] . " themes that can be used for indicators.";
    } else {
        $warning_messages[] = "⚠️ No indicator themes found in themes table. Adding default themes.";
        
        // Insert default themes
        $default_themes = [
            ['Economic', 'Economic indicators', '#28a745', 'indicator'],
            ['Social', 'Social indicators', '#007bff', 'indicator'],
            ['Environmental', 'Environmental indicators', '#17a2b8', 'indicator'],
            ['Governance', 'Governance indicators', '#6610f2', 'indicator']
        ];
        
        $theme_stmt = $conn->prepare("INSERT INTO themes (theme_name, theme_description, theme_color, theme_type) VALUES (?, ?, ?, ?)");
        $theme_stmt->bind_param("ssss", $theme_name, $theme_desc, $theme_color, $theme_type);
        
        foreach ($default_themes as $theme) {
            $theme_name = $theme[0];
            $theme_desc = $theme[1];
            $theme_color = $theme[2];
            $theme_type = $theme[3];
            if ($theme_stmt->execute()) {
                $success_messages[] = "✅ Added theme: " . $theme_name;
            } else {
                $error_messages[] = "❌ Failed to add theme " . $theme_name . ": " . $theme_stmt->error;
            }
        }
        
        $theme_stmt->close();
    }
} else {
    $error_messages[] = "❌ Themes table does not exist.";
}

// Close database 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>Setup 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;
        }
        
        .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">
        <div class="d-flex align-items-center">
            <img src="assets/nsa-logo.jpeg" alt="NSA Logo" height="40" class="me-3">
            <h1>Setup Indicators</h1>
        </div>
        <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">
                                <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>
                            <a href="setup_indicators.php" class="list-group-item list-group-item-action active">
                                <i class="fas fa-tools me-2"></i> Setup Indicators
                            </a>
                        </div>
                    </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">Setup Indicators</h5>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-info mb-4">
                            <h5><i class="fas fa-info-circle me-2"></i>Indicator Setup Status</h5>
                            <p>This page helps you set up the indicators system and ensures that all required tables and columns exist.</p>
                        </div>
                        
                        <!-- Success Messages -->
                        <?php if (!empty($success_messages)): ?>
                        <div class="alert alert-success mb-3">
                            <h5><i class="fas fa-check-circle me-2"></i>Success</h5>
                            <ul class="mb-0">
                                <?php foreach ($success_messages as $message): ?>
                                <li><?php echo $message; ?></li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                        <?php endif; ?>
                        
                        <!-- Error Messages -->
                        <?php if (!empty($error_messages)): ?>
                        <div class="alert alert-danger mb-3">
                            <h5><i class="fas fa-exclamation-circle me-2"></i>Errors</h5>
                            <ul class="mb-0">
                                <?php foreach ($error_messages as $message): ?>
                                <li><?php echo $message; ?></li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                        <?php endif; ?>
                        
                        <!-- Warning Messages -->
                        <?php if (!empty($warning_messages)): ?>
                        <div class="alert alert-warning mb-3">
                            <h5><i class="fas fa-exclamation-triangle me-2"></i>Warnings</h5>
                            <ul class="mb-0">
                                <?php foreach ($warning_messages as $message): ?>
                                <li><?php echo $message; ?></li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                        <?php endif; ?>
                        
                        <div class="mt-4">
                            <a href="indicators.php" class="btn btn-primary me-2">
                                <i class="fas fa-chart-line me-2"></i>Go to Indicators
                            </a>
                            <a href="setup_indicators.php" class="btn btn-outline-secondary">
                                <i class="fas fa-sync me-2"></i>Run Setup Again
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 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>
</body>
</html>