<?php

session_start();

// Check if admin is logged in
if (!isset($_SESSION['student_id']) || $_SESSION['role'] !== 'admin') {
    header("Location: login.php");
    exit();
}

// Database connection
// Database connection
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "school_db";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    error_log("Connection failed: " . $e->getMessage());
    $error = "Connection failed. Please check the server logs.";
}

// Fetch admin's student details (if student_id matches)
try {
    $stmt = $conn->prepare("SELECT name, grade, contact FROM students WHERE id = :student_id");
    $stmt->execute([':student_id' => $_SESSION['student_id']]);
    $admin_student = $stmt->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
    error_log("Admin student fetch error: " . $e->getMessage());
    $error = "Error fetching admin's student data.";
}

// Fetch all news
try {
    $news_stmt = $conn->query("SELECT id, title, date_posted FROM news ORDER BY date_posted DESC");
    $news = $news_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
    error_log("News fetch error: " . $e->getMessage());
    $error = "Error fetching news.";
}

// Handle add/edit news
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
    $action = $_POST['action'];
    $title = filter_input(INPUT_POST, 'title', FILTER_SANITIZE_STRING);
    $content = filter_input(INPUT_POST, 'content', FILTER_SANITIZE_STRING);
    $news_id = filter_input(INPUT_POST, 'news_id', FILTER_VALIDATE_INT);

    if ($action === 'add' || $action === 'edit') {
        if (empty($title) || empty($content)) {
            $error = "Title and content are required.";
        } else {
            try {
                // Handle image upload
                $image_path = null;
                if (!empty($_FILES['image']['name'])) {
                    $target_dir = "uploads/";
                    $image_path = $target_dir . basename($_FILES['image']['name']);
                    if (!move_uploaded_file($_FILES['image']['tmp_name'], $image_path)) {
                        $error = "Failed to upload image.";
                    }
                }

                if ($action === 'add') {
                    $stmt = $conn->prepare("INSERT INTO news (title, content, image, date_posted) VALUES (:title, :content, :image, NOW())");
                    $stmt->execute([':title' => $title, ':content' => $content, ':image' => $image_path]);
                    $success = "News added successfully.";
                } elseif ($action === 'edit' && $news_id) {
                    $stmt = $conn->prepare("UPDATE news SET title = :title, content = :content, image = :image WHERE id = :id");
                    $stmt->execute([':title' => $title, ':content' => $content, ':image' => $image_path, ':id' => $news_id]);
                    $success = "News updated successfully.";
                }
            } catch(PDOException $e) {
                error_log("News {$action} error: " . $e->getMessage());
                $error = "Error {$action}ing news.";
            }
        }
    } elseif ($action === 'delete' && $news_id) {
        try {
            $stmt = $conn->prepare("DELETE FROM news WHERE id = :id");
            $stmt->execute([':id' => $news_id]);
            $success = "News deleted successfully.";
        } catch(PDOException $e) {
            error_log("News delete error: " . $e->getMessage());
            $error = "Error deleting news.";
        }
    }
    // Refresh news list
    $news_stmt = $conn->query("SELECT id, title, date_posted FROM news ORDER BY date_posted DESC");
    $news = $news_stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Generate CSRF token
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf_token = $_SESSION['csrf_token'];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Manage news articles for Gakero E.L.C.K High School.">
    <meta name="keywords" content="Gakero E.L.C.K High School, admin, news management">
    <meta name="author" content="Gakero E.L.C.K High School">
    <title>Manage News - Gakero E.L.C.K High School</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
    <link rel="stylesheet" href="css/styles.css">
</head>
<body>
    <div class="d-flex">
        <!-- Sticky Sidebar -->
        <nav class="sidebar bg-primary text-white" id="sidebar">
            <div class="sidebar-header text-center p-3">
                <h4 class="mb-0">Gakero E.L.C.K</h4>
            </div>
            <div class="profile-card p-3">
                <div class="text-center">
                    <div class="avatar bg-light text-primary rounded-circle mx-auto mb-2">
                        <i class="bi bi-person-circle fs-2"></i>
                    </div>
                    <h6 class="mb-1">Admin</h6>
                    <small class="text-white-50">ID: <?php echo htmlspecialchars($_SESSION['student_id'] ?? 'N/A'); ?></small><br>
                    <?php if ($admin_student): ?>
                        <small class="text-white-50">Name: <?php echo htmlspecialchars($admin_student['name'] ?? 'N/A'); ?></small><br>
                        <small class="text-white-50">Grade: <?php echo htmlspecialchars($admin_student['grade'] ?? 'N/A'); ?></small><br>
                        <small class="text-white-50">Contact: <?php echo htmlspecialchars($admin_student['contact'] ?? 'N/A'); ?></small>
                    <?php else: ?>
                        <small class="text-white-50">No student profile found.</small>
                    <?php endif; ?>
                </div>
            </div>
            <ul class="nav flex-column p-3">
                <li class="nav-item">
                    <a class="nav-link text-white active" href="manage_news.php"><i class="bi bi-newspaper me-2"></i>Manage News</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-white" href="manage_students.php"><i class="bi bi-people me-2"></i>Manage Students</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link text-white" href="manage_timetables.php"><i class="bi bi-calendar me-2"></i>Manage Timetables</a>
                </li>
                <li class="nav-item">
                    <form method="POST" action="admin_page.php">
                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                        <button type="submit" name="logout" class="nav-link text-white bg-transparent border-0"><i class="bi bi-box-arrow-right me-2"></i>Logout</button>
                    </form>
                </li>
            </ul>
        </nav>

        <!-- Main Content -->
        <main class="flex-grow-1 p-4">
            <button class="btn btn-primary d-lg-none mb-3" type="button" data-bs-toggle="offcanvas" data-bs-target="#sidebarOffcanvas" aria-controls="sidebarOffcanvas">
                <i class="bi bi-list"></i> Menu
            </button>
            <div class="offcanvas offcanvas-start bg-primary text-white" tabindex="-1" id="sidebarOffcanvas" aria-labelledby="sidebarOffcanvasLabel">
                <div class="offcanvas-header">
                    <h5 class="offcanvas-title" id="sidebarOffcanvasLabel">Gakero E.L.C.K</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="offcanvas" aria-label="Close"></button>
                </div>
                <div class="offcanvas-body">
                    <div class="profile-card p-3">
                        <div class="text-center">
                            <div class="avatar bg-light text-primary rounded-circle mx-auto mb-2">
                                <i class="bi bi-person-circle fs-2"></i>
                            </div>
                            <h6 class="mb-1">Admin</h6>
                            <small class="text-white-50">ID: <?php echo htmlspecialchars($_SESSION['student_id'] ?? 'N/A'); ?></small><br>
                            <?php if ($admin_student): ?>
                                <small class="text-white-50">Name: <?php echo htmlspecialchars($admin_student['name'] ?? 'N/A'); ?></small><br>
                                <small class="text-white-50">Grade: <?php echo htmlspecialchars($admin_student['grade'] ?? 'N/A'); ?></small><br>
                                <small class="text-white-50">Contact: <?php echo htmlspecialchars($admin_student['contact'] ?? 'N/A'); ?></small>
                            <?php else: ?>
                                <small class="text-white-50">No student profile found.</small>
                            <?php endif; ?>
                        </div>
                    </div>
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link text-white active" href="manage_news.php"><i class="bi bi-newspaper me-2"></i>Manage News</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="manage_students.php"><i class="bi bi-people me-2"></i>Manage Students</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-white" href="manage_timetables.php"><i class="bi bi-calendar me-2"></i>Manage Timetables</a>
                        </li>
                        <li class="nav-item">
                            <form method="POST" action="admin_page.php">
                                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                                <button type="submit" name="logout" class="nav-link text-white bg-transparent border-0"><i class="bi bi-box-arrow-right me-2"></i>Logout</button>
                            </form>
                        </li>
                    </ul>
                </div>
            </div>

            <!-- Main Content -->
            <div class="container">
                <h2 class="section-title">Manage News</h2>
                <?php if (isset($error)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <?php echo htmlspecialchars($error); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>
                <?php if (isset($success)): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <?php echo htmlspecialchars($success); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>

                <!-- Add News Form -->
                <div class="card mb-4">
                    <div class="card-body">
                        <h5 class="card-title">Add News</h5>
                        <form method="POST" enctype="multipart/form-data">
                            <input type="hidden" name="action" value="add">
                            <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                            <div class="mb-3">
                                <label for="title" class="form-label">Title</label>
                                <input type="text" id="title" name="title" class="form-control" required>
                            </div>
                            <div class="mb-3">
                                <label for="content" class="form-label">Content</label>
                                <textarea id="content" name="content" class="form-control" rows="5" required></textarea>
                            </div>
                            <div class="mb-3">
                                <label for="image" class="form-label">Image (Optional)</label>
                                <input type="file" id="image" name="image" class="form-control" accept="image/*">
                            </div>
                            <button type="submit" class="btn btn-primary">Add News</button>
                        </form>
                    </div>
                </div>

                <!-- News Table -->
                <div class="table-responsive">
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th scope="col">ID</th>
                                <th scope="col">Title</th>
                                <th scope="col">Date Posted</th>
                                <th scope="col">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($news)): ?>
                                <?php foreach ($news as $item): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($item['id']); ?></td>
                                        <td><?php echo htmlspecialchars($item['title']); ?></td>
                                        <td><?php echo date('F j, Y', strtotime($item['date_posted'])); ?></td>
                                        <td>
                                            <button class="btn btn-outline-primary btn-sm" data-bs-toggle="modal" data-bs-target="#editNewsModal<?php echo $item['id']; ?>">Edit</button>
                                            <form method="POST" style="display:inline;">
                                                <input type="hidden" name="action" value="delete">
                                                <input type="hidden" name="news_id" value="<?php echo $item['id']; ?>">
                                                <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                                                <button type="submit" class="btn btn-outline-danger btn-sm" onclick="return confirm('Are you sure you want to delete this news?');">Delete</button>
                                            </form>
                                        </td>
                                    </tr>
                                    <!-- Edit News Modal -->
                                    <div class="modal fade" id="editNewsModal<?php echo $item['id']; ?>" tabindex="-1" aria-labelledby="editNewsModalLabel<?php echo $item['id']; ?>" aria-hidden="true">
                                        <div class="modal-dialog">
                                            <div class="modal-content">
                                                <div class="modal-header">
                                                    <h5 class="modal-title" id="editNewsModalLabel<?php echo $item['id']; ?>">Edit News</h5>
                                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                </div>
                                                <div class="modal-body">
                                                    <form method="POST" enctype="multipart/form-data">
                                                        <input type="hidden" name="action" value="edit">
                                                        <input type="hidden" name="news_id" value="<?php echo $item['id']; ?>">
                                                        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrf_token); ?>">
                                                        <div class="mb-3">
                                                            <label for="title<?php echo $item['id']; ?>" class="form-label">Title</label>
                                                            <input type="text" id="title<?php echo $item['id']; ?>" name="title" class="form-control" value="<?php echo htmlspecialchars($item['title']); ?>" required>
                                                        </div>
                                                        <div class="mb-3">
                                                            <label for="content<?php echo $item['id']; ?>" class="form-label">Content</label>
                                                            <textarea id="content<?php echo $item['id']; ?>" name="content" class="form-control" rows="5" required><?php
                                                                $stmt = $conn->prepare("SELECT content FROM news WHERE id = :id");
                                                                $stmt->execute([':id' => $item['id']]);
                                                                echo htmlspecialchars($stmt->fetchColumn());
                                                            ?></textarea>
                                                        </div>
                                                        <div class="mb-3">
                                                            <label for="image<?php echo $item['id']; ?>" class="form-label">Image (Optional)</label>
                                                            <input type="file" id="image<?php echo $item['id']; ?>" name="image" class="form-control" accept="image/*">
                                                        </div>
                                                        <button type="submit" class="btn btn-primary">Save Changes</button>
                                                    </form>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr><td colspan="4" class="text-center">No news articles found.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </main>
    </div>

    <!-- Footer -->
    <footer class="bg-dark text-white text-center py-4">
        <div class="container">
            <p>&copy; <?php echo date("Y"); ?> Gakero E.L.C.K High School. All rights reserved.</p>
            <p>Kisii County, Gucha Sub-cunty,Misesi Location</p>
            <p>Email: <a href="mailto:info@gakeroelckhigh.edu" class="text-white">info@gakeroelckhigh.edu</a> | Phone: <a href="tel:+1234567890" class="text-white">(123) 456-7890</a></p>
        </div>
    </footer>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>