<?php
// This script sets up the theme connections for indicators using the existing themes table
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Start session at the beginning to avoid errors
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);
}

// Status messages
$messages = [];

// Check if themes table exists
$table_exists = false;
$check_table = $conn->query("SHOW TABLES LIKE 'themes'");
if ($check_table && $check_table->num_rows > 0) {
    $table_exists = true;
    $messages[] = [
        'type' => 'success',
        'text' => "Found existing 'themes' table. We'll use this for indicator categorization."
    ];
} else {
    // If themes table doesn't exist, create it
    $sql = "CREATE TABLE themes (
        theme_id INT(11) AUTO_INCREMENT PRIMARY KEY,
        theme_name VARCHAR(100) NOT NULL,
        theme_type VARCHAR(50) DEFAULT NULL
    )";
    
    if ($conn->query($sql) === TRUE) {
        $table_exists = true;
        $messages[] = [
            'type' => 'success',
            'text' => "Created 'themes' table."
        ];
        
        // Insert some default themes
        $default_themes = [
            ['Economic', 'indicator'],
            ['Social', 'indicator'],
            ['Environmental', 'indicator'],
            ['Governance', 'indicator']
        ];
        
        $stmt = $conn->prepare("INSERT INTO themes (theme_name, theme_type) VALUES (?, ?)");
        $stmt->bind_param("ss", $theme_name, $theme_type);
        
        foreach ($default_themes as $theme) {
            $theme_name = $theme[0];
            $theme_type = $theme[1];
            $stmt->execute();
        }
        
        $stmt->close();
        $messages[] = [
            'type' => 'info',
            'text' => "Added default themes: Economic, Social, Environmental, Governance"
        ];
    } else {
        $messages[] = [
            'type' => 'danger',
            'text' => "Error creating themes table: " . $conn->error
        ];
    }
}

// Add theme_id column to national_indicators if it doesn't exist
$column_exists = false;
$result = $conn->query("SHOW COLUMNS FROM national_indicators LIKE 'theme_id'");
if ($result && $result->num_rows > 0) {
    $column_exists = true;
    $messages[] = [
        'type' => 'success',
        'text' => "The 'theme_id' column already exists in the national_indicators table."
    ];
} else {
    $sql = "ALTER TABLE national_indicators ADD COLUMN theme_id INT(11) DEFAULT NULL";
    if ($conn->query($sql) === TRUE) {
        $column_exists = true;
        $messages[] = [
            'type' => 'success',
            'text' => "Added 'theme_id' column to national_indicators table."
        ];
    } else {
        $messages[] = [
            'type' => 'danger',
            'text' => "Error adding theme_id column: " . $conn->error
        ];
    }
}

// Get theme data
$themes = [];
if ($table_exists) {
    $result = $conn->query("SELECT * FROM themes ORDER BY theme_name");
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $themes[] = $row;
        }
    }
}

// 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>Theme Setup - 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;
        }
        
        .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 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>Setup Themes</h1>
        </div>
        <div class="text-end">
            <span class="me-2"><?php echo htmlspecialchars($_SESSION['username']); ?></span>
            <i class="fas fa-user-circle"></i>
        </div>
    </div>    <div class="container">
        <div class="row">
            <div class="col-md-8 offset-md-2">
                <div class="content-card">
                    <div class="card-body">
                        <h4 class="mb-4">Theme Configuration Status</h4>
                        
                        <?php foreach ($messages as $message): ?>
                            <div class="alert alert-<?php echo $message['type']; ?>">
                                <?php echo $message['text']; ?>
                            </div>
                        <?php endforeach; ?>
                        
                        <?php if ($table_exists && $column_exists): ?>
                            <div class="alert alert-success">
                                <h5><i class="fas fa-check-circle me-2"></i> Setup Complete!</h5>
                                <p class="mb-0">Theme configuration has been successfully set up. You can now use themes to categorize your indicators.</p>
                            </div>
                        <?php else: ?>
                            <div class="alert alert-warning">
                                <h5><i class="fas fa-exclamation-triangle me-2"></i> Setup Incomplete</h5>
                                <p class="mb-0">There were some issues with the theme setup. Please check the messages above.</p>
                            </div>
                        <?php endif; ?>
                        
                        <?php if (!empty($themes)): ?>
                            <h5 class="mt-4 mb-3">Available Themes</h5>
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>Theme Name</th>
                                            <th>Type</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($themes as $theme): ?>
                                            <tr>
                                                <td><?php echo $theme['theme_id']; ?></td>
                                                <td><?php echo htmlspecialchars($theme['theme_name']); ?></td>
                                                <td><?php echo htmlspecialchars($theme['theme_type'] ?? 'N/A'); ?></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php else: ?>
                            <div class="alert alert-info mt-4">
                                <p class="mb-0">No themes found in the database.</p>
                            </div>
                        <?php endif; ?>
                        
                        <div class="d-flex justify-content-between mt-4">
                            <a href="analyze_themes.php" class="btn btn-outline-secondary">
                                <i class="fas fa-search me-2"></i> Analyze Theme Structure
                            </a>
                            <a href="indicators.php" class="btn btn-primary">
                                <i class="fas fa-chart-line me-2"></i> Go to Indicators
                            </a>
                        </div>
                    </div>
                </div>
                
                <div class="content-card">
                    <div class="card-body">
                        <h4 class="mb-3">Navigation</h4>
                        <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> Return to Dashboard
                            </a>
                            <a href="indicators.php" class="list-group-item list-group-item-action">
                                <i class="fas fa-chart-line me-2"></i> Manage Indicators
                            </a>
                        </div>
                    </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>
?>