<?php
session_start();
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include "../include/config.php";

// Check if user is logged in
if (!isset($_SESSION['email'])) {
    header("location:../index.php");
    exit();
}

$userlogin = $_SESSION['email'];
$email = $_SESSION['email'];
$role = $_SESSION['role'] ?? 'User';
$intake = $_SESSION['department'] ?? '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>News Management</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;600;700&family=Source+Sans+Pro:wght@300;400;600&display=swap" rel="stylesheet">
    <link rel="icon" href="favicon.png" type="image/png">
    <meta name="theme-color" content="var(--primary)">
    <style>
        :root {
            --primary-color: var(--primary);
            --primary-light: #2da578;
            --secondary-color: #f8f9fa;
            --accent-color: #ff7b00;
            --text-color: #333;
            --light-text: #6c757d;
            --border-color: #dee2e6;
            --success-color: #28a745;
            --danger-color: #dc3545;
            --card-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
            --card-hover-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);
        }
        
        body {
            font-family: 'Source Sans Pro', sans-serif;
            background-color: #f5f7f9;
            color: var(--text-color);
            line-height: 1.6;
        }
        
        .page-container {
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        
        .main-content {
            flex: 1;
            padding: 20px;
            margin-top: 70px;
        }
        
        .card {
            border: none;
            border-radius: 12px;
            box-shadow: var(--card-shadow);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
            margin-bottom: 24px;
        }
        
        .card:hover {
            transform: translateY(-5px);
            box-shadow: var(--card-hover-shadow);
        }
        
        .card-header {
            background-color: white;
            border-bottom: 1px solid var(--border-color);
            padding: 1.25rem 1.5rem;
            border-radius: 12px 12px 0 0 !important;
        }
        
        .card-title {
            font-family: 'Montserrat', sans-serif;
            font-weight: 600;
            color: var(--primary-color);
            margin-bottom: 0;
        }
        
        .btn-primary {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
            padding: 0.5rem 1.5rem;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        
        .btn-primary:hover {
            background-color: var(--primary-light);
            border-color: var(--primary-light);
            transform: translateY(-2px);
        }
        
        .btn-danger {
            padding: 0.375rem 0.75rem;
            font-size: 0.875rem;
        }
        
        .form-label {
            font-weight: 600;
            color: var(--text-color);
            margin-bottom: 0.5rem;
        }
        
        .form-control, .form-select {
            border-radius: 8px;
            padding: 0.75rem 1rem;
            border: 1px solid var(--border-color);
            transition: border-color 0.3s ease, box-shadow 0.3s ease;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.25rem rgba(35, 134, 101, 0.25);
        }
        
        .news-img {
            width: 60px;
            height: 60px;
            object-fit: cover;
            border-radius: 8px;
            border: 1px solid var(--border-color);
        }
        
        .news-table {
            border-radius: 12px;
            overflow: hidden;
        }
        
        .news-table thead th {
            background-color: var(--primary-color);
            color: white;
            font-weight: 600;
            border: none;
            padding: 1rem;
        }
        
        .news-table tbody td {
            padding: 1rem;
            vertical-align: middle;
            border-color: var(--border-color);
        }
        
        .news-table tbody tr:hover {
            background-color: rgba(35, 134, 101, 0.05);
        }
        
        .alert-success {
            background-color: rgba(40, 167, 69, 0.1);
            border-color: rgba(40, 167, 69, 0.2);
            color: var(--success-color);
            border-radius: 8px;
        }
        
        .alert-danger {
            background-color: rgba(220, 53, 69, 0.1);
            border-color: rgba(220, 53, 69, 0.2);
            color: var(--danger-color);
            border-radius: 8px;
        }
        
        .search-box {
            position: relative;
        }
        
        .search-box .form-control {
            padding-left: 2.5rem;
        }
        
        .search-box i {
            position: absolute;
            left: 1rem;
            top: 50%;
            transform: translateY(-50%);
            color: var(--light-text);
        }
        
        .empty-state {
            text-align: center;
            padding: 3rem 1rem;
            color: var(--light-text);
        }
        
        .empty-state i {
            font-size: 3rem;
            margin-bottom: 1rem;
            color: var(--border-color);
        }
        
        .news-preview {
            max-height: 80px;
            overflow: hidden;
            display: -webkit-box;
            -webkit-line-clamp: 3;
            -webkit-box-orient: vertical;
        }
        
        @media (max-width: 768px) {
            .main-content {
                padding: 15px;
                margin-top: 60px;
            }
            
            .card-header {
                padding: 1rem;
            }
            
            .news-table thead {
                display: none;
            }
            
            .news-table tbody, .news-table tr, .news-table td {
                display: block;
                width: 100%;
            }
            
            .news-table tr {
                margin-bottom: 1rem;
                border: 1px solid var(--border-color);
                border-radius: 8px;
                overflow: hidden;
            }
            
            .news-table td {
                text-align: right;
                padding: 0.75rem;
                position: relative;
                border: none;
                border-bottom: 1px solid var(--border-color);
            }
            
            .news-table td:last-child {
                border-bottom: none;
            }
            
            .news-table td::before {
                content: attr(data-label);
                position: absolute;
                left: 0.75rem;
                width: 45%;
                padding-right: 10px;
                font-weight: 600;
                text-align: left;
                color: var(--primary-color);
            }
        }
    </style>
</head>
<body>
    <?php include "../include/nav.php"; ?>
    
    <div class="content">
        <div class="container-fluid">
            <div class="row mb-4">
                <div class="col-12">
                    <h1 class="h3 mb-0" style="color: var(--primary-color); font-family: 'Montserrat', sans-serif;">News Management</h1>
                    <p class="text-muted">Manage and publish news articles</p>
                </div>
            </div>
            
            <?php
            $message = "";
            
            // Insert News - FIXED with mysqli_real_escape_string
            if (isset($_POST['submit'])) {
                $title   = mysqli_real_escape_string($conn, $_POST['title']);
                $msg     = mysqli_real_escape_string($conn, $_POST['message']);
                $date    = mysqli_real_escape_string($conn, $_POST['date']);
                $image   = basename($_FILES['image']['name']);

                // Create directory if it doesn't exist
                $target_dir = "../../students/img/";
                if (!is_dir($target_dir)) {
                    mkdir($target_dir, 0777, true);
                }
                
                // Upload image
                $target = $target_dir . $image;
                
                // Check if file is uploaded
                if ($_FILES['image']['error'] === UPLOAD_ERR_OK) {
                    // Move uploaded file
                    if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
                        // Insert into database - ESCAPED VALUES
                        $sql = "INSERT INTO news (image, title, message, date) 
                                VALUES ('$image','$title','$msg','$date')";
                        
                        if ($conn->query($sql)) {
                            $message = "<div class='alert alert-success' role='alert'><i class='fas fa-check-circle me-2'></i>News added successfully!</div>";
                        } else {
                            $message = "<div class='alert alert-danger' role='alert'><i class='fas fa-exclamation-circle me-2'></i>Error: " . htmlspecialchars($conn->error) . "</div>";
                        }
                    } else {
                        $message = "<div class='alert alert-danger' role='alert'><i class='fas fa-exclamation-circle me-2'></i>Failed to upload image.</div>";
                    }
                } else {
                    $message = "<div class='alert alert-danger' role='alert'><i class='fas fa-exclamation-circle me-2'></i>Please select an image to upload.</div>";
                }
            }

            // Delete News
            if (isset($_GET['delete'])) {
                $id = intval($_GET['delete']);
                $conn->query("DELETE FROM news WHERE id = $id");
                header("Location: news.php?msg=deleted");
                exit();
            }
            
            // Show success message after delete
            if (isset($_GET['msg']) && $_GET['msg'] == 'deleted') {
                $message = "<div class='alert alert-success' role='alert'><i class='fas fa-check-circle me-2'></i>News deleted successfully!</div>";
            }
            ?>
            
            <div class="row">
                <!-- Add News Box -->
                <?php if($role == "Admin") { ?>
                <div class="col-lg-6 mb-4">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="card-title"><i class="fas fa-plus-circle me-2"></i>Add News</h5>
                        </div>
                        <div class="card-body">
                            <?php echo $message; ?>
                            <form method="POST" enctype="multipart/form-data">
                                <div class="mb-3">
                                    <label for="title" class="form-label">News Title</label>
                                    <input type="text" class="form-control" id="title" name="title" required>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="message" class="form-label">Message</label>
                                    <textarea class="form-control" id="message" name="message" rows="4" required></textarea>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="image" class="form-label">Image</label>
                                        <input type="file" class="form-control" id="image" name="image" required accept="image/*">
                                    </div>
                                    
                                    <div class="col-md-6 mb-3">
                                        <label for="date" class="form-label">Date</label>
                                        <input type="date" class="form-control" id="date" name="date" value="<?= date('Y-m-d'); ?>" required>
                                    </div>
                                </div>
                                
                                <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                                    <button type="submit" name="submit" class="btn btn-primary"><i class="fas fa-save me-2"></i>Save News</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
                <?php } ?>
                
                <!-- News List Box -->
                <div class="<?php echo ($role == "Admin") ? 'col-lg-6' : 'col-12'; ?>">
                    <div class="card">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h5 class="card-title"><i class="fas fa-newspaper me-2"></i>News Records</h5>
                            <span class="badge bg-primary rounded-pill">
                                <?php 
                                $count_sql = "SELECT COUNT(*) as total FROM news";
                                $count_result = $conn->query($count_sql);
                                if ($count_result) {
                                    $count_row = $count_result->fetch_assoc();
                                    echo $count_row['total'];
                                } else {
                                    echo "0";
                                }
                                ?>
                            </span>
                        </div>
                        <div class="card-body">
                            <div class="search-box mb-3">
                                <i class="fas fa-search"></i>
                                <input type="text" id="newsSearch" class="form-control" placeholder="Search news...">
                            </div>
                            
                            <div class="table-responsive" style="max-height:400px; overflow-y:auto">
                                <table class="table table-hover news-table" id="newsTable">
                                    <thead>
                                        <tr>
                                            <th>Image</th>
                                            <th>Title</th>
                                            <th>Message</th>
                                            <th>Date</th>
                                            <?php if($role == "Admin") { ?>
                                            <th>Action</th>
                                            <?php } ?>
                                        </tr>
                                    </thead>
                                    <tbody>
                                    <?php 
                                    $sql = "SELECT id, image, title, message, date FROM news ORDER BY id DESC";
                                    $result = $conn->query($sql);
                                    
                                    if ($result && $result->num_rows > 0) { 
                                        while($row = $result->fetch_assoc()) { ?>
                                            <tr>
                                                <td data-label="Image">
                                                    <?php if(!empty($row['image'])) { ?>
                                                        <img src="../../students/img/<?= htmlspecialchars($row['image']); ?>" class="news-img" alt="News Image" onerror="this.src='https://via.placeholder.com/60?text=Image+Not+Found'">
                                                    <?php } else { ?>
                                                        <div class="text-center text-muted">
                                                            <i class="fas fa-image"></i>
                                                            <div class="small">No Image</div>
                                                        </div>
                                                    <?php } ?>
                                                </td>
                                                <td data-label="Title"><?= htmlspecialchars($row['title']); ?></td>
                                                <td data-label="Message">
                                                    <div class="news-preview"><?= htmlspecialchars(substr($row['message'], 0, 100)) . (strlen($row['message']) > 100 ? '...' : ''); ?></div>
                                                </td>
                                                <td data-label="Date"><?= htmlspecialchars($row['date']); ?></td>
                                                <?php if($role == "Admin") { ?>
                                                <td data-label="Action">
                                                    <a href="?delete=<?= $row['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure you want to delete this news item?');">
                                                        <i class="fas fa-trash-alt me-1"></i>Delete
                                                    </a>
                                                </td>
                                                <?php } ?>
                                            </tr>
                                    <?php } } else { ?>
                                            <tr>
                                                <td colspan="<?php echo ($role == "Admin") ? '5' : '4'; ?>" class="text-center">
                                                    <div class="empty-state">
                                                        <i class="fas fa-newspaper"></i>
                                                        <h5>No News Found</h5>
                                                        <p>There are no news articles to display.</p>
                                                    </div>
                                                </td>
                                            </tr>
                                    <?php } ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        document.getElementById('newsSearch').addEventListener('keyup', function() {
            let filter = this.value.toLowerCase();
            let rows = document.querySelectorAll('#newsTable tbody tr');
            rows.forEach(row => {
                let text = row.textContent.toLowerCase();
                row.style.display = text.includes(filter) ? '' : 'none';
            });
        });
        
        // Add responsive labels for mobile view
        document.addEventListener('DOMContentLoaded', function() {
            if (window.innerWidth <= 768) {
                const headers = document.querySelectorAll('#newsTable thead th');
                const headerTexts = Array.from(headers).map(header => header.textContent.trim());
                
                document.querySelectorAll('#newsTable tbody tr').forEach(row => {
                    const cells = row.querySelectorAll('td');
                    cells.forEach((cell, index) => {
                        if (headerTexts[index]) {
                            cell.setAttribute('data-label', headerTexts[index]);
                        }
                    });
                });
            }
        });
    </script>
</body>
</html>