<?php
include "../include/config.php";
session_start();

if (isset($_SESSION['email'])) {
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>College Article Management</title>
        <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
        <script src="https://cdn.tiny.cloud/1/2mneaw1qjzanqgfmh23h72kldgoa6cy2bpgquxyfw9ey4cfq/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>
        <style>
            :root {
                --primary-color: #1a4b8c;
                --secondary-color: #b31b1b;
                --accent-color: #ffc72c;
                --light-bg: #f5f7fb;
                --card-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
                --university-dark: #0a2a5a;
            }
            
            body {
                background-color: var(--light-bg);
                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
                color: #333;
                line-height: 1.6;
                background-image: linear-gradient(to bottom, rgba(255,255,255,0.9), rgba(255,255,255,0.9)), url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><rect fill="none" stroke="%231a4b8c" stroke-width="0.5" x="0" y="0" width="100" height="100"/></svg>');
            }
            
            .navbar {
                box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
                background-color: var(--university-dark) !important;
            }
            
            .content {
                margin-left: 200px;
                padding: 20px;
                transition: all 0.3s;
            }
            
            @media (max-width: 768px) {
                .content {
                    margin-left: 0;
                }
            }
            
            .page-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 25px;
                padding: 20px 0;
                border-bottom: 1px solid #eaeaea;
                background: linear-gradient(135deg, var(--primary-color), var(--university-dark));
                color: white;
                padding: 20px;
                border-radius: 8px;
                box-shadow: var(--card-shadow);
            }
            
            .page-title {
                color: white;
                font-weight: 600;
                margin: 0;
                font-size: 1.8rem;
            }
            
            .btn-primary-custom {
                background-color: var(--accent-color);
                border-color: var(--accent-color);
                color: var(--university-dark);
                padding: 10px 25px;
                border-radius: 4px;
                font-weight: 600;
                transition: all 0.3s;
                box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
            }
            
            .btn-primary-custom:hover {
                background-color: #e6b400;
                border-color: #e6b400;
                transform: translateY(-2px);
                box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
                color: var(--university-dark);
            }
            
            .card-custom {
                border: none;
                border-radius: 8px;
                box-shadow: var(--card-shadow);
                margin-bottom: 20px;
                overflow: hidden;
                border-top: 4px solid var(--primary-color);
            }
            
            .card-header-custom {
                background-color: white;
                border-bottom: 1px solid #eaeaea;
                padding: 15px 20px;
                font-weight: 600;
                color: var(--primary-color);
            }
            
            .table-container {
                background: white;
                border-radius: 8px;
                overflow: hidden;
                box-shadow: var(--card-shadow);
                border: 1px solid #e0e0e0;
            }
            
            .table thead th {
                background: linear-gradient(to right, var(--primary-color), var(--university-dark));
                color: white;
                border: none;
                padding: 15px 12px;
                font-weight: 500;
            }
            
            .table tbody tr {
                transition: all 0.2s;
            }
            
            .table tbody tr:hover {
                background-color: rgba(26, 75, 140, 0.05);
            }
            
            .table tbody td {
                padding: 12px;
                vertical-align: middle;
                border-color: #eaeaea;
            }
            
            .action-buttons {
                display: flex;
                gap: 8px;
            }
            
            .btn-action {
                padding: 6px 12px;
                border-radius: 4px;
                font-size: 14px;
                transition: all 0.2s;
                font-weight: 500;
            }
            
            .btn-edit {
                background-color: var(--primary-color);
                color: white;
                border: none;
            }
            
            .btn-delete {
                background-color: var(--secondary-color);
                color: white;
                border: none;
            }
            
            .btn-action:hover {
                transform: translateY(-1px);
                box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            }
            
            .alert-custom {
                border-radius: 8px;
                border: none;
                padding: 12px 20px;
                margin-bottom: 20px;
            }
            
            .alert-success {
                background-color: rgba(26, 75, 140, 0.1);
                color: var(--primary-color);
                border-left: 4px solid var(--primary-color);
            }
            
            .alert-danger {
                background-color: rgba(179, 27, 27, 0.1);
                color: var(--secondary-color);
                border-left: 4px solid var(--secondary-color);
            }
            
            .modal-content {
                border: none;
                border-radius: 10px;
                overflow: hidden;
                box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            }
            
            .modal-header {
                background: linear-gradient(to right, var(--primary-color), var(--university-dark));
                color: white;
                border-bottom: none;
                padding: 15px 20px;
            }
            
            .modal-title {
                font-weight: 500;
            }
            
            .close {
                color: white;
                opacity: 0.8;
            }
            
            .close:hover {
                color: white;
                opacity: 1;
            }
            
            .form-label {
                font-weight: 500;
                margin-bottom: 8px;
                color: #555;
            }
            
            .form-control {
                border-radius: 4px;
                border: 1px solid #ddd;
                padding: 10px 12px;
                transition: all 0.3s;
            }
            
            .form-control:focus {
                border-color: var(--primary-color);
                box-shadow: 0 0 0 0.2rem rgba(26, 75, 140, 0.25);
            }
            
            .link-cell {
                max-width: 200px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }
            
            .link-cell a {
                color: var(--primary-color);
                text-decoration: none;
                font-weight: 500;
            }
            
            .link-cell a:hover {
                text-decoration: underline;
                color: var(--university-dark);
            }
            
            .university-badge {
                background-color: var(--accent-color);
                color: var(--university-dark);
                padding: 4px 8px;
                border-radius: 4px;
                font-size: 12px;
                font-weight: 600;
            }
            
            @media (max-width: 768px) {
                .mobile-hidden {
                    display: none;
                }
                
                .action-buttons {
                    flex-direction: column;
                }
                
                .btn-action {
                    width: 100%;
                    margin-bottom: 5px;
                }
            }
            
            .article-preview {
                background: white;
                border-radius: 8px;
                padding: 20px;
                margin-top: 20px;
                box-shadow: var(--card-shadow);
                border-left: 4px solid var(--accent-color);
            }
            
            .article-preview h4 {
                color: var(--primary-color);
                margin-bottom: 15px;
            }
            
            .stats-card {
                background: white;
                border-radius: 8px;
                padding: 15px;
                text-align: center;
                box-shadow: var(--card-shadow);
                margin-bottom: 20px;
                border-top: 4px solid var(--primary-color);
            }
            
            .stats-number {
                font-size: 2rem;
                font-weight: 700;
                color: var(--primary-color);
            }
            
            .stats-label {
                color: #666;
                font-size: 0.9rem;
            }
        </style>
    </head>
    <body>
        <?php include "../include/nav.php"; ?>
        
        <div class="content">
            <div class="page-header">
                <h1 class="page-title"><i class="fas fa-newspaper mr-2"></i>College Article Management</h1>
                <button type="button" class="btn btn-primary-custom" data-toggle="modal" data-target="#articleModal">
                    <i class="fas fa-plus"></i> Post New Article
                </button>
            </div>
            
            <?php
            // Get article count for stats
            $articleCountQuery = mysqli_query($conn, "SELECT COUNT(*) as total FROM articles");
            $articleCount = mysqli_fetch_assoc($articleCountQuery)['total'];
            ?>
            
            <div class="row mb-4">
                <div class="col-md-3">
                    <div class="stats-card">
                        <div class="stats-number"><?php echo $articleCount; ?></div>
                        <div class="stats-label">Total Articles</div>
                    </div>
                </div>
                <div class="col-md-9">
                    <div class="article-preview">
                        <h4><i class="fas fa-bullhorn text-warning mr-2"></i>Article Guidelines</h4>
                        <p>All articles should follow the university's content guidelines. Ensure proper formatting, accurate information, and appropriate language for an academic audience.</p>
                    </div>
                </div>
            </div>
            
            <?php if (isset($_GET['danger'])): ?>
            <div class="alert alert-danger alert-custom">
                <i class="fas fa-exclamation-circle"></i> <?php echo $_GET['danger']; ?>
            </div>
            <?php endif; ?>
            
            <?php if (isset($_GET['post'])): ?>
            <div class="alert alert-success alert-custom">
                <i class="fas fa-check-circle"></i> <?php echo $_GET['post']; ?>
            </div>
            <?php endif; ?>
            
            <div class="table-container">
                <div class="card-header-custom">
                    <i class="fas fa-list mr-2"></i>Published Articles
                </div>
                <div class="table-responsive">
                    <table id="articlesTable" class="table table-hover">
                        <thead>
                            <tr>
                                <th>Title</th>
                                <th class="link-cell">Link</th>
                                <th class="mobile-hidden">Author</th>
                                <th class="mobile-hidden">Date Posted</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $query = mysqli_query($conn, "SELECT * FROM articles ORDER BY time DESC");
                            while($row = mysqli_fetch_array($query)): 
                            ?>
                            <tr>
                                <td class="font-weight-medium"><?php echo $row['title']; ?></td>
                                <td class="link-cell">
                                    <a href="https://portal.unicohsuniversity.com/view_article.php?id=<?php echo $row['id']; ?>" target="_blank">
                                        <i class="fas fa-external-link-alt mr-1"></i> View Article
                                    </a>
                                </td>
                                <td class="mobile-hidden">
                                    <span class="university-badge"><?php echo $row['postby']; ?></span>
                                </td>
                                <td class="mobile-hidden"><?php echo date('M j, Y', strtotime($row['time'])); ?></td>
                                <td>
                                    <div class="action-buttons">
                                        <a href="editteacher?id=<?php echo $row['id']; ?>" class="btn btn-action btn-edit">
                                            <i class="fas fa-share"></i> Share
                                        </a>
                                        <a onclick="return confirmDelete()" href="deletelogic?id=<?php echo $row['id']; ?>" class="btn btn-action btn-delete">
                                            <i class="fas fa-trash"></i> Delete
                                        </a>
                                    </div>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        
        <!-- Article Modal -->
        <div class="modal fade" id="articleModal" tabindex="-1" role="dialog" aria-labelledby="articleModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="articleModalLabel"><i class="fas fa-edit mr-2"></i>Create New Article</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <form action="" method="POST" enctype="multipart/form-data">
                            <div class="form-group">
                                <label class="form-label" for="image">Featured Image</label>
                                <input type="file" name="image" class="form-control" id="image" accept="image/*">
                                <small class="form-text text-muted">Recommended size: 1200x630 pixels for optimal display</small>
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label" for="title">Article Title</label>
                                <input type="text" name="title" class="form-control" id="title" placeholder="Enter article title" required>
                            </div>
                            
                            <input type="hidden" name="postby" value="<?php echo $_SESSION['staffname'] . ' ' . $_SESSION['surname']; ?>">
                            
                            <div class="form-group">
                                <label class="form-label" for="main">Article Content</label>
                                <textarea name="main" id="main" class="form-control" rows="10" placeholder="Write your article content here..."></textarea>
                            </div>
                            
                            <div class="d-flex justify-content-end mt-4">
                                <button type="button" class="btn btn-light mr-2" data-dismiss="modal">Cancel</button>
                                <button type="submit" name="post" class="btn btn-primary-custom">
                                    <i class="fas fa-paper-plane mr-1"></i> Publish Article
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        
        <script>
            tinymce.init({
                selector: 'textarea',
                plugins: 'advlist autolink lists link image charmap print preview anchor',
                toolbar: 'undo redo | formatselect | bold italic backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat | link image',
                height: 300
            });
            
            function confirmDelete() {
                return confirm("Are you sure you want to delete this article? This action cannot be undone.");
            }
            
            // Initialize DataTable if needed
            $(document).ready(function() {
                // You can initialize DataTables here if you include the library
                // $('#articlesTable').DataTable();
            });
        </script>
        
        <?php
        include "../include/config.php";
        
        if (isset($_POST['post'])) {
            $main = $_POST['main'];
            $by = $_POST['postby'];
            $title = $_POST['title'];
            $image_name = $_FILES['image']['name'];
            $tmp_image_name = $_FILES['image']['tmp_name'];
            $folder = 'journal/';
            
            if (!empty($image_name)) {
                move_uploaded_file($tmp_image_name, $folder . $image_name);
            }
            
            $check = mysqli_query($conn, "SELECT * FROM articles WHERE title='$title'");
            if(mysqli_num_rows($check) > 0) {
                header("Location: articles.php?post=An article with a similar title has already been posted");
            } else {
                $stmt = $conn->prepare("INSERT INTO articles (image, title, main, postby) VALUES (?, ?, ?, ?)");
                $stmt->bind_param("ssss", $image_name, $title, $main, $by);
                
                if ($stmt->execute()) {
                    header("Location: articles.php?post=Article successfully published");
                } else {
                    echo "Error: " . $stmt->error;
                }
                
                $stmt->close();
                $conn->close();
            }
        }
        ?>
    </body>
    </html>
    <?php
} else {
    header("Location: index.php");
}
?>