<?php
// Include configuration file
require_once 'config.php';

// Require user to be logged in
require_login();

// Set the current page for navigation
$current_page = 'themes';

// Initialize connection
$conn = connect_db();

// Determine the action (list, add, edit, delete)
$action = isset($_GET['action']) ? sanitize_input($_GET['action']) : 'list';

// Initialize variables
$theme = [
    'theme_id' => '',
    'theme_name' => '',
    'theme_type' => ''
];

$error = '';
$success = '';

// Handle actions
switch ($action) {
    case 'add':
        // Display add form, actual addition handled in the 'save' case
        break;

    case 'edit':
        if (isset($_GET['id'])) {
            $id = (int)$_GET['id'];
            $stmt = $conn->prepare("SELECT * FROM indicator_themes WHERE theme_id = ?");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $result = $stmt->get_result();
            if ($result->num_rows > 0) {
                $theme = $result->fetch_assoc();
            } else {
                $error = "Theme not found.";
                $action = 'list';
            }
            $stmt->close();
        } else {
            $error = "No theme ID specified.";
            $action = 'list';
        }
        break;

    case 'save':
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            // Sanitize inputs
            $theme['theme_name'] = sanitize_input($_POST['theme_name']);
            $theme['theme_type'] = sanitize_input($_POST['theme_type'] ?? '');

            if (empty($theme['theme_name'])) {
                $error = "Theme name is required.";
            } else {
                // Check if the theme name already exists (for add or when name is changed)
                $check_name = $conn->prepare("SELECT theme_id FROM indicator_themes WHERE theme_name = ? AND theme_id != ?");
                $id_param = isset($_POST['theme_id']) ? (int)$_POST['theme_id'] : 0;
                $check_name->bind_param("si", $theme['theme_name'], $id_param);
                $check_name->execute();
                $check_result = $check_name->get_result();

                if ($check_result->num_rows > 0) {
                    $error = "A theme with this name already exists.";
                }
                $check_name->close();
            }

            // Database operation (insert or update)
            if (empty($error)) {
                if (isset($_POST['theme_id']) && !empty($_POST['theme_id'])) {
                    // Update existing theme
                    $theme['theme_id'] = (int)$_POST['theme_id'];
                    
                    $stmt = $conn->prepare("UPDATE indicator_themes SET theme_name = ?, theme_type = ? WHERE theme_id = ?");
                    $stmt->bind_param("ssi", $theme['theme_name'], $theme['theme_type'], $theme['theme_id']);
                    
                    if ($stmt->execute()) {
                        $success = "Theme updated successfully.";
                        log_action("Updated theme", "ID: " . $theme['theme_id']);
                    } else {
                        $error = "Error updating theme: " . $conn->error;
                    }
                    $stmt->close();
                } else {
                    // Insert new theme
                    $stmt = $conn->prepare("INSERT INTO indicator_themes (theme_name, theme_type) VALUES (?, ?)");
                    $stmt->bind_param("ss", $theme['theme_name'], $theme['theme_type']);
                    
                    if ($stmt->execute()) {
                        $theme['theme_id'] = $conn->insert_id;
                        $success = "Theme added successfully.";
                        log_action("Added new theme", "ID: " . $theme['theme_id']);
                    } else {
                        $error = "Error adding theme: " . $conn->error;
                    }
                    $stmt->close();
                }
            }
            
            if (empty($error)) {
                // Redirect back to list view after successful operation
                header("Location: indicator-themes.php?success=" . urlencode($success));
                exit;
            } else {
                // Stay on form in case of error
                $action = isset($_POST['theme_id']) && !empty($_POST['theme_id']) ? 'edit' : 'add';
            }
        }
        break;

    case 'delete':
        if (isset($_GET['id'])) {
            $id = (int)$_GET['id'];
            
            // First check if this theme is used by any indicators
            $stmt = $conn->prepare("SELECT COUNT(*) as count FROM national_indicators WHERE theme_id = ?");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $result = $stmt->get_result();
            $row = $result->fetch_assoc();
            $used_count = $row['count'];
            $stmt->close();
            
            if ($used_count > 0) {
                $error = "This theme is used by {$used_count} indicators and cannot be deleted. Please reassign these indicators first.";
                header("Location: indicator-themes.php?error=" . urlencode($error));
                exit;
            }
            
            // If not used, proceed with deletion
            $stmt = $conn->prepare("DELETE FROM indicator_themes WHERE theme_id = ?");
            $stmt->bind_param("i", $id);
            
            if ($stmt->execute()) {
                $success = "Theme deleted successfully.";
                log_action("Deleted theme", "ID: " . $id);
            } else {
                $error = "Error deleting theme: " . $conn->error;
            }
            $stmt->close();
            
            header("Location: indicator-themes.php?success=" . urlencode($success));
            exit;
        } else {
            $error = "No theme ID specified.";
        }
        break;

    default:
        // 'list' action is the default view
        break;
}

// Pagination setup for list view
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

// Count total records for pagination
$total_records = 0;
$result = $conn->query("SELECT COUNT(*) as count FROM indicator_themes");
if ($result && $row = $result->fetch_assoc()) {
    $total_records = $row['count'];
}
$total_pages = ceil($total_records / $limit);

// Get themes for list view
$themes = [];
$query = "SELECT t.*, (SELECT COUNT(*) FROM national_indicators WHERE theme_id = t.theme_id) as indicator_count FROM indicator_themes t ORDER BY t.theme_name LIMIT ? OFFSET ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("ii", $limit, $offset);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $themes[] = $row;
}
$stmt->close();

// 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>Indicator Themes - <?php echo $config['app_name']; ?></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;
        }
        
        .main-header h1 {
            color: var(--primary-color);
            font-size: 1.5rem;
            margin-bottom: 0;
        }
        
        /* Cards */
        .content-card {
            background-color: white;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
            margin-bottom: 20px;
        }
        
        .content-card .card-header {
            padding: 15px 20px;
            border-bottom: 1px solid #eee;
        }
        
        .content-card .card-body {
            padding: 20px;
        }
        
        /* Tables */
        .data-table th {
            background-color: #f8f9fa;
        }
        
        /* Buttons */
        .btn-primary {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }
        
        .btn-primary:hover, .btn-primary:focus {
            background-color: var(--primary-dark);
            border-color: var(--primary-dark);
        }
        
        .btn-secondary {
            background-color: var(--secondary-color);
            border-color: var(--secondary-color);
        }
        
        .btn-secondary:hover, .btn-secondary:focus {
            background-color: var(--secondary-dark);
            border-color: var(--secondary-dark);
        }
        
        /* Footer */
        .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;
        }
        
        .badge.bg-info {
            background-color: var(--primary-color) !important;
        }
    </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"><i class="fas fa-chart-line"></i> Indicators</a></li>
            <li><a href="indicator-themes.php" class="active"><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><?php echo ($action === 'add' ? 'Add New Theme' : ($action === 'edit' ? 'Edit Theme' : 'Indicator Themes')); ?></h1>
            <div class="user-info">
                <span class="me-2"><?php echo $_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 (isset($_GET['error'])): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?php echo htmlspecialchars($_GET['error']); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>
        
        <?php if (!empty($error)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <?php echo $error; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>
        
        <!-- Content based on action -->
        <?php if ($action === 'list'): ?>
            <div class="content-card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">All Themes</h5>
                    <a href="indicator-themes.php?action=add" class="btn btn-primary btn-sm">
                        <i class="fas fa-plus"></i> Add New Theme
                    </a>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover data-table">
                            <thead>
                                <tr>
                                    <th>Name</th>
                                    <th>Type</th>
                                    <th>Indicators</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($themes)): ?>
                                    <tr>
                                        <td colspan="4" class="text-center">No themes found.</td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($themes as $item): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($item['theme_name']); ?></td>
                                            <td><?php echo htmlspecialchars($item['theme_type'] ?? ''); ?></td>
                                            <td>
                                                <span class="badge bg-info"><?php echo $item['indicator_count']; ?></span>
                                            </td>
                                            <td>
                                                <a href="indicator-themes.php?action=edit&id=<?php echo $item['theme_id']; ?>" class="btn btn-sm btn-info">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <a href="#" class="btn btn-sm btn-danger <?php echo ($item['indicator_count'] > 0) ? 'disabled' : ''; ?>" 
                                                   <?php if ($item['indicator_count'] == 0): ?>data-bs-toggle="modal" data-bs-target="#deleteModal<?php echo $item['theme_id']; ?>"<?php endif; ?>
                                                   <?php if ($item['indicator_count'] > 0): ?>title="Cannot delete theme with associated indicators"<?php endif; ?>>
                                                    <i class="fas fa-trash"></i>
                                                </a>
                                                
                                                <!-- Delete Confirmation Modal -->
                                                <?php if ($item['indicator_count'] == 0): ?>
                                                <div class="modal fade" id="deleteModal<?php echo $item['theme_id']; ?>" tabindex="-1" aria-labelledby="deleteModalLabel<?php echo $item['theme_id']; ?>" aria-hidden="true">
                                                    <div class="modal-dialog">
                                                        <div class="modal-content">
                                                            <div class="modal-header">
                                                                <h5 class="modal-title" id="deleteModalLabel<?php echo $item['theme_id']; ?>">Confirm Delete</h5>
                                                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                            </div>
                                                            <div class="modal-body">
                                                                Are you sure you want to delete the theme: <strong><?php echo htmlspecialchars($item['theme_name']); ?></strong>?<br>
                                                                This action cannot be undone.
                                                            </div>
                                                            <div class="modal-footer">
                                                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                                                <a href="indicator-themes.php?action=delete&id=<?php echo $item['theme_id']; ?>" class="btn btn-danger">Delete</a>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- Pagination -->
                    <?php if ($total_pages > 1): ?>
                        <?php echo get_pagination($total_pages, $page, 'indicator-themes.php?action=list'); ?>
                    <?php endif; ?>
                </div>
            </div>
        <?php else: ?>
            <!-- Form for add/edit -->
            <div class="content-card">
                <div class="card-body">
                    <form action="indicator-themes.php?action=save" method="post">
                        <?php if ($action === 'edit'): ?>
                            <input type="hidden" name="theme_id" value="<?php echo $theme['theme_id']; ?>">
                        <?php endif; ?>
                        
                        <div class="mb-3">
                            <label for="theme_name" class="form-label">Theme Name *</label>
                            <input type="text" class="form-control" id="theme_name" name="theme_name" value="<?php echo htmlspecialchars($theme['theme_name']); ?>" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="theme_type" class="form-label">Theme Type</label>
                            <select class="form-select" id="theme_type" name="theme_type">
                                <option value="">-- Select Type --</option>
                                <option value="Economic" <?php echo ($theme['theme_type'] === 'Economic') ? 'selected' : ''; ?>>Economic</option>
                                <option value="Social" <?php echo ($theme['theme_type'] === 'Social') ? 'selected' : ''; ?>>Social</option>
                                <option value="Environmental" <?php echo ($theme['theme_type'] === 'Environmental') ? 'selected' : ''; ?>>Environmental</option>
                                <option value="Demographic" <?php echo ($theme['theme_type'] === 'Demographic') ? 'selected' : ''; ?>>Demographic</option>
                                <option value="Health" <?php echo ($theme['theme_type'] === 'Health') ? 'selected' : ''; ?>>Health</option>
                                <option value="Education" <?php echo ($theme['theme_type'] === 'Education') ? 'selected' : ''; ?>>Education</option>
                                <option value="Other" <?php echo ($theme['theme_type'] === 'Other') ? 'selected' : ''; ?>>Other</option>
                            </select>
                        </div>
                        
                        <div class="d-flex justify-content-between">
                            <a href="indicator-themes.php" class="btn btn-secondary">Cancel</a>
                            <button type="submit" class="btn btn-primary"><?php echo ($action === 'edit') ? 'Update Theme' : 'Add Theme'; ?></button>
                        </div>
                    </form>
                </div>
            </div>
        <?php endif; ?>
    </div>
    
    <!-- Footer -->
    <div class="footer">
        <p><?php echo $config['app_name']; ?> &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>
    <script>
        // Mobile sidebar toggle
        document.getElementById('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>