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

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

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

// Initialize connection
$conn = connect_db();

// Function to ensure admin user exists in the database
function ensure_admin_user_exists($conn) {
    // Check if users table exists
    $table_check = $conn->query("SHOW TABLES LIKE 'users'");
    if ($table_check->num_rows == 0) {
        return false; // Table doesn't exist
    }
    
    // Check if admin user exists
    $admin_check = $conn->prepare("SELECT id FROM users WHERE id = 1");
    $admin_check->execute();
    $admin_result = $admin_check->get_result();
    
    if ($admin_result->num_rows == 0) {
        // Admin doesn't exist, try to create it
        try {
            $conn->query("INSERT INTO users (id, username, password, email, role, created_at) 
                VALUES (1, 'admin', '" . password_hash('admin123', PASSWORD_DEFAULT) . "', 'admin@example.com', 'admin', NOW())");
            return true;
        } catch (Exception $e) {
            return false;
        }
    }
    
    return true; // Admin exists
}

// Ensure admin user exists
$admin_exists = ensure_admin_user_exists($conn);

// Check if reports table has foreign key constraint issues
function check_reports_table_constraint($conn) {
    try {
        // Try a simple operation to see if we can disable foreign key checks temporarily
        $conn->query("SET foreign_key_checks = 0");
        
        // See if we can modify the constraint
        $alter_result = $conn->query("
            ALTER TABLE reports 
            DROP FOREIGN KEY IF EXISTS fk_reports_user,
            ADD CONSTRAINT fk_reports_user 
            FOREIGN KEY (user_id) REFERENCES users (id) 
            ON DELETE SET NULL ON UPDATE CASCADE
        ");
        
        // Re-enable foreign key checks
        $conn->query("SET foreign_key_checks = 1");
        
        return $alter_result !== false;
    } catch (Exception $e) {
        // If there's an error, log it but continue
        error_log("Error modifying reports table: " . $e->getMessage());
        return false;
    }
}

// Try to fix table constraints
$table_fixed = check_reports_table_constraint($conn);

// Determine the action (list, add, edit, delete, save)
$action = 'list'; // Default action

if (isset($_POST['action'])) {
    $action = sanitize_input($_POST['action']);
} elseif (isset($_GET['action'])) {
    $action = sanitize_input($_GET['action']);
}

// Initialize variables
$report = [
    'id' => '',
    'title' => '',
    'description' => '',
    'report_date' => date('Y-m-d'),
    'file_url' => '',
    'category' => '',
    'user_id' => get_current_user_id()
];

$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 reports WHERE id = ?");
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $result = $stmt->get_result();
            if ($result->num_rows > 0) {
                $report = $result->fetch_assoc();
            } else {
                $error = "Report not found.";
                $action = 'list';
            }
            $stmt->close();
        } else {
            $error = "No report ID specified.";
            $action = 'list';
        }
        break;

    case 'save':
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                try {
                    // Sanitize and validate inputs
                    $report['title'] = isset($_POST['title']) ? sanitize_input($_POST['title']) : '';
                    $report['description'] = isset($_POST['description']) ? sanitize_input($_POST['description']) : '';
                    $report['report_date'] = isset($_POST['report_date']) ? sanitize_input($_POST['report_date']) : date('Y-m-d');
                    $report['category'] = isset($_POST['category']) ? (int)$_POST['category'] : 0;
                    
                    // Handle user_id for foreign key constraint
                    if ($admin_exists) {
                        // Use admin ID (1) which we know exists
                        $report['user_id'] = 1;
                    } else {
                        // Find ANY user ID that exists
                        $user_query = $conn->query("SELECT id FROM users LIMIT 1");
                        if ($user_query && $user_row = $user_query->fetch_assoc()) {
                            $report['user_id'] = $user_row['id'];
                        } else {
                            // No users at all in the system
                            $report['user_id'] = null;
                        }
                    }                // Validation
                if (empty($report['title'])) {
                    $error = "Report title is required.";
                }
                
                // URL handling
                if (!$error && isset($_POST['file_url'])) {
                    $url = sanitize_input($_POST['file_url']);
                    
                    // Allow URLs or local paths for flexibility
                    if (!empty($url)) {
                        $report['file_url'] = $url;
                    } else {
                        $error = "Report URL is required.";
                    }
                } else {
                    $error = "Report URL field is missing.";
                }
            } catch (Exception $e) {
                $error = "Error processing form: " . $e->getMessage();
            }

            // Database operation (insert or update)
            if (empty($error)) {
                if (isset($_POST['id']) && !empty($_POST['id'])) {
                    try {
                        // Update existing report
                        $report['id'] = (int)$_POST['id'];
                        
                        // Always include the file_url in the update, but don't touch user_id
                        $sql = "UPDATE reports SET 
                                title = ?, 
                                description = ?, 
                                report_date = ?, 
                                category = ?, 
                                file_url = ? 
                                WHERE id = ?";
                                
                        $stmt = $conn->prepare($sql);
                        
                        if (!$stmt) {
                            throw new Exception("Prepare failed: " . $conn->error);
                        }
                        
                        // Default values
                        $category = $report['category'] ?: 0;
                        
                        $stmt->bind_param("sssisi", 
                            $report['title'], 
                            $report['description'], 
                            $report['report_date'], 
                            $category,
                            $report['file_url'],
                            $report['id']
                        );
                        
                        if ($stmt->execute()) {
                            $success = "Report updated successfully.";
                            log_action("Updated report", "ID: " . $report['id']);
                        } else {
                            $error = "Error updating report: " . $stmt->error;
                        }
                        $stmt->close();
                    } catch (Exception $e) {
                        $error = "Database error: " . $e->getMessage();
                    }
                } else {
                    try {
                        // Last resort approach - try direct SQL with NULL user_id if we've been having foreign key issues
                        if (!$admin_exists || $report['user_id'] === null) {
                            // Try raw SQL with explicit NULL for user_id
                            $title = $conn->real_escape_string($report['title']);
                            $description = $conn->real_escape_string($report['description']);
                            $report_date = $conn->real_escape_string($report['report_date']);
                            $file_url = $conn->real_escape_string($report['file_url']);
                            $category = (int)($report['category'] ?: 0);
                            
                            $raw_sql = "INSERT INTO reports (title, description, report_date, file_url, category, user_id, created_at) 
                                       VALUES ('$title', '$description', '$report_date', '$file_url', $category, NULL, NOW())";
                            
                            $result = $conn->query($raw_sql);
                            if (!$result) {
                                throw new Exception("Raw SQL insert failed: " . $conn->error);
                            } else {
                                $report['id'] = $conn->insert_id;
                                $success = "Report added successfully.";
                                log_action("Added new report", "ID: " . $report['id']);
                                return; // Skip the rest of the function since we already handled success
                            }
                        } else {
                            // Regular approach with prepared statement
                            $sql = "INSERT INTO reports (title, description, report_date, file_url, category, user_id, created_at) 
                                   VALUES (?, ?, ?, ?, ?, ?, NOW())";
                            $stmt = $conn->prepare($sql);
                            
                            if (!$stmt) {
                                throw new Exception("Prepare failed: " . $conn->error);
                            }
                            
                            // Default values
                            $category = $report['category'] ?: 0;
                            
                            $stmt->bind_param("ssssis", 
                                $report['title'], 
                                $report['description'], 
                                $report['report_date'], 
                                $report['file_url'], 
                                $category, 
                                $report['user_id']
                            );
                            
                            if (!$stmt->execute()) {
                                // If prepared statement fails, try the direct SQL approach with NULL user_id
                                $stmt->close();
                                
                                $title = $conn->real_escape_string($report['title']);
                                $description = $conn->real_escape_string($report['description']);
                                $report_date = $conn->real_escape_string($report['report_date']);
                                $file_url = $conn->real_escape_string($report['file_url']);
                                $category = (int)($report['category'] ?: 0);
                                
                                $raw_sql = "INSERT INTO reports (title, description, report_date, file_url, category, user_id, created_at) 
                                           VALUES ('$title', '$description', '$report_date', '$file_url', $category, NULL, NOW())";
                                
                                $result = $conn->query($raw_sql);
                                if (!$result) {
                                    throw new Exception("Raw SQL insert failed: " . $conn->error);
                                }
                                return; // Skip the rest of the function since we already executed the query
                            }
                        }
                        
                        if ($stmt->execute()) {
                            $report['id'] = $conn->insert_id;
                            $success = "Report added successfully.";
                            log_action("Added new report", "ID: " . $report['id']);
                        } else {
                            $error = "Error executing insert: " . $stmt->error;
                        }
                        $stmt->close();
                    } catch (Exception $e) {
                        $error = "Database error: " . $e->getMessage();
                    }
                }
            }
            
            if (empty($error)) {
                // Redirect back to list view after successful operation
                header("Location: reports.php?success=" . urlencode($success));
                exit;
            } else {
                // Stay on form in case of error
                $action = isset($_POST['id']) && !empty($_POST['id']) ? 'edit' : 'add';
                
                // Add diagnostic info to the error message for easier debugging
                if (strpos($error, 'foreign key constraint') !== false) {
                    // Query users table for IDs
                    $users_info = '';
                    $user_query = $conn->query("SELECT id FROM users ORDER BY id LIMIT 10");
                    if ($user_query) {
                        while ($user_row = $user_query->fetch_assoc()) {
                            $users_info .= "User ID: " . $user_row['id'] . ", ";
                        }
                    }
                    
                    $error .= "\n\nDiagnostic info: Admin exists: " . ($admin_exists ? 'Yes' : 'No') . 
                              ", User ID attempted: " . ($report['user_id'] ?? 'NULL') .
                              ", Available users: " . ($users_info ? $users_info : 'None found');
                }
                
                // Log the error for debugging
                error_log("Report form error: " . $error);
            }
        } else {
            $error = "Invalid request method. POST required.";
        }
        break;

    case 'delete':
        if (isset($_GET['id'])) {
            $id = (int)$_GET['id'];
            
            // Delete the record
            $stmt = $conn->prepare("DELETE FROM reports WHERE id = ?");
            $stmt->bind_param("i", $id);
            
            if ($stmt->execute()) {
                $success = "Report deleted successfully.";
                log_action("Deleted report", "ID: " . $id);
            } else {
                $error = "Error deleting report: " . $conn->error;
            }
            $stmt->close();
            
            header("Location: reports.php?success=" . urlencode($success));
            exit;
        } else {
            $error = "No report ID specified.";
        }
        break;

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

// Fetch categories for dropdowns
$categories = [];
$result = $conn->query("SELECT id, name FROM report_categories ORDER BY name");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $categories[] = $row;
    }
}

// Create default categories if none exist
if (empty($categories)) {
    $default_categories = [
        'Annual Reports',
        'Statistical Reports',
        'Research Papers',
        'Press Releases',
        'Newsletters'
    ];
    
    foreach ($default_categories as $cat_name) {
        $stmt = $conn->prepare("INSERT INTO report_categories (name) VALUES (?)");
        if ($stmt) {
            $stmt->bind_param("s", $cat_name);
            $stmt->execute();
            $stmt->close();
        }
    }
    
    // Fetch categories again
    $categories = [];
    $result = $conn->query("SELECT id, name FROM report_categories ORDER BY name");
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $categories[] = $row;
        }
    }
}

// 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 reports");
if ($result && $row = $result->fetch_assoc()) {
    $total_records = $row['count'];
}
$total_pages = ceil($total_records / $limit);

// Get reports for list view
$reports = [];
$query = "SELECT r.*, rc.name as category_name FROM reports r 
          LEFT JOIN report_categories rc ON r.category = rc.id 
          ORDER BY r.report_date DESC LIMIT ? OFFSET ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("ii", $limit, $offset);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    $reports[] = $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>Reports - <?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">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.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;
        }
        
        .file-preview {
            max-width: 100%;
            max-height: 200px;
            margin-top: 10px;
        }
        
        .report-description {
            white-space: pre-line;
        }
    </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" class="active"><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"><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 Report' : ($action === 'edit' ? 'Edit Report' : 'Reports')); ?></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 (!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 Reports</h5>
                    <a href="reports.php?action=add" class="btn btn-primary btn-sm">
                        <i class="fas fa-plus"></i> Add New Report
                    </a>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover data-table">
                            <thead>
                                <tr>
                                    <th>Title</th>
                                    <th>Category</th>
                                    <th>Date</th>
                                    <th>Link</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($reports)): ?>
                                    <tr>
                                        <td colspan="5" class="text-center">No reports found.</td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($reports as $item): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($item['title']); ?></td>
                                            <td><?php echo htmlspecialchars($item['category_name'] ?? 'Uncategorized'); ?></td>
                                            <td><?php echo htmlspecialchars($item['report_date']); ?></td>
                                            <td>
                                                <?php if (!empty($item['file_url'])): ?>
                                                    <a href="<?php echo htmlspecialchars($item['file_url']); ?>" target="_blank" class="btn btn-sm btn-outline-primary">
                                                        <i class="fas fa-external-link-alt"></i> Open Link
                                                    </a>
                                                <?php else: ?>
                                                    <span class="badge bg-secondary">No link</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <a href="reports.php?action=edit&id=<?php echo $item['id']; ?>" class="btn btn-sm btn-info">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <a href="#" class="btn btn-sm btn-danger" data-bs-toggle="modal" data-bs-target="#deleteModal<?php echo $item['id']; ?>">
                                                    <i class="fas fa-trash"></i>
                                                </a>
                                                
                                                <!-- Delete Confirmation Modal -->
                                                <div class="modal fade" id="deleteModal<?php echo $item['id']; ?>" tabindex="-1" aria-labelledby="deleteModalLabel<?php echo $item['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['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 report: <strong><?php echo htmlspecialchars($item['title']); ?></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="reports.php?action=delete&id=<?php echo $item['id']; ?>" class="btn btn-danger">Delete</a>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- Pagination -->
                    <?php if ($total_pages > 1): ?>
                        <?php echo get_pagination($total_pages, $page, 'reports.php?'); ?>
                    <?php endif; ?>
                </div>
            </div>
        <?php else: ?>
            <!-- Form for add/edit -->
            <div class="content-card">
                <div class="card-body">
                    <?php if (!empty($error)): ?>
                    <div class="alert alert-danger mb-4">
                        <strong>Error:</strong> <?php echo htmlspecialchars($error); ?>
                    </div>
                    <?php endif; ?>
                    
                    <form action="reports.php" method="post">
                        <input type="hidden" name="action" value="save">
                        <?php if ($action === 'edit'): ?>
                            <input type="hidden" name="id" value="<?php echo $report['id']; ?>">
                        <?php endif; ?>
                        
                        <div class="mb-3">
                            <label for="title" class="form-label">Report Title *</label>
                            <input type="text" class="form-control" id="title" name="title" value="<?php echo htmlspecialchars($report['title']); ?>" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="category" class="form-label">Category *</label>
                            <div class="input-group">
                                <select class="form-select" id="category" name="category" required>
                                    <option value="">-- Select Category --</option>
                                    <?php foreach ($categories as $cat): ?>
                                        <option value="<?php echo $cat['id']; ?>" <?php echo ($report['category'] == $cat['id']) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($cat['name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <a href="report-categories.php?action=add" class="btn btn-outline-secondary" title="Add New Category" target="_blank">
                                    <i class="fas fa-plus"></i>
                                </a>
                            </div>
                            <small class="text-muted">Choose a category for this report or add a new one</small>
                        </div>
                        
                        <div class="mb-3">
                            <label for="report_date" class="form-label">Report Date *</label>
                            <input type="date" class="form-control datepicker" id="report_date" name="report_date" value="<?php echo htmlspecialchars($report['report_date']); ?>" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="description" class="form-label">Description</label>
                            <textarea class="form-control" id="description" name="description" rows="4"><?php echo htmlspecialchars($report['description']); ?></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label for="file_url" class="form-label">Report URL *</label>
                            <input type="text" class="form-control" id="file_url" name="file_url" 
                                value="<?php echo htmlspecialchars($report['file_url']); ?>" 
                                placeholder="https://www.example.com/report.pdf" 
                                required>
                            <small class="form-text text-muted">Enter the full URL to the report (e.g., https://www.nsa.org.na/reports/annual-report-2024.pdf)</small>
                            
                            <?php if ($action === 'edit' && !empty($report['file_url'])): ?>
                                <div class="mt-2">
                                    <p>Current URL: 
                                        <a href="<?php echo htmlspecialchars($report['file_url']); ?>" target="_blank">
                                            View Report
                                        </a>
                                    </p>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="d-flex justify-content-between">
                            <a href="reports.php" class="btn btn-secondary">Cancel</a>
                            <button type="submit" class="btn btn-primary"><?php echo ($action === 'edit') ? 'Update Report' : 'Add Report'; ?></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 src="https://cdn.jsdelivr.net/npm/flatpickr"></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');
        });
        
        // Initialize datepicker
        flatpickr(".datepicker", {
            dateFormat: "Y-m-d"
        });
        
        // Form validation
        document.addEventListener('DOMContentLoaded', function() {
            const reportForm = document.querySelector('form[action="reports.php"]');
            if (reportForm) {
                reportForm.addEventListener('submit', function(event) {
                    let valid = true;
                    let errorMessage = '';
                    
                    // Title validation
                    const titleInput = document.getElementById('title');
                    if (titleInput && !titleInput.value.trim()) {
                        errorMessage += 'Report title is required.\n';
                        valid = false;
                        titleInput.classList.add('is-invalid');
                    } else if (titleInput) {
                        titleInput.classList.remove('is-invalid');
                    }
                    
                    // Category validation
                    const categorySelect = document.getElementById('category');
                    if (categorySelect && !categorySelect.value) {
                        errorMessage += 'Report category is required.\n';
                        valid = false;
                        categorySelect.classList.add('is-invalid');
                    } else if (categorySelect) {
                        categorySelect.classList.remove('is-invalid');
                    }
                    
                    // Report date validation
                    const dateInput = document.getElementById('report_date');
                    if (dateInput && !dateInput.value.trim()) {
                        errorMessage += 'Report date is required.\n';
                        valid = false;
                        dateInput.classList.add('is-invalid');
                    } else if (dateInput) {
                        dateInput.classList.remove('is-invalid');
                    }
                    
                    // URL validation
                    const urlInput = document.getElementById('file_url');
                    if (urlInput && !urlInput.value.trim()) {
                        errorMessage += 'Report URL is required.\n';
                        valid = false;
                        urlInput.classList.add('is-invalid');
                    } else if (urlInput) {
                        urlInput.classList.remove('is-invalid');
                    }
                    
                    if (!valid) {
                        event.preventDefault();
                        alert('Please fix the following errors:\n\n' + errorMessage);
                    }
                });
            }
        });
    </script>
</body>
</html>