<?php
session_start();
ob_start();

include "../include/config.php";

// Check login FIRST
if (!isset($_SESSION['studentid'])) {
    header("location:../index.php");
    exit();
}

$program = $_SESSION['program'];
$course_filter = isset($_GET['course']) ? $conn->real_escape_string($_GET['course']) : '';
$search_filter = isset($_GET['search']) ? $conn->real_escape_string($_GET['search']) : '';

// Build query with filters
$where_conditions = ["program='$program'"];

if (!empty($course_filter)) {
    $where_conditions[] = "course='$course_filter'";
}

if (!empty($search_filter)) {
    $where_conditions[] = "(title LIKE '%$search_filter%' OR note LIKE '%$search_filter%')";
}

$where_clause = implode(' AND ', $where_conditions);
$notes_query = $conn->query("SELECT * FROM notes WHERE $where_clause ORDER BY posted_at DESC");
$notes_count = $notes_query ? $notes_query->num_rows : 0;

// Get unique courses for filter dropdown
$courses_query = $conn->query("SELECT DISTINCT course FROM notes WHERE program='$program' ORDER BY course ASC");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Student Notes</title>
    <link rel="stylesheet" href="../../boostrap/1.css">
    <link rel="stylesheet" href="../../boostrap/2.css">
      <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300&family=Source+Sans+Pro:wght@300&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
   <link rel="icon" href="favicon.png" type="image/png">
   <!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<!-- Bootstrap JS -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

    <meta name="theme-color" content="var(--primary)">
      <script src='https://kit.fontawesome.com/a076d05399.js' crossorigin='anonymous'></script>
      <script src='https://kit.fontawesome.com/a076d05399.js' crossorigin='anonymous'></script>
      <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
      <script src='https://kit.fontawesome.com/a076d05399.js' crossorigin='anonymous'></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Signika+Negative:wght@300..700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="res/bootstrap@5.2.0.min.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Rowdies:wght@300;400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<style>
body { padding:0; margin:0; font-family: 'Montserrat', sans-serif; background:white; }
.content { margin-left:210px; padding:10px; }
.btn{
background:var(--primary);
color:white;
}
.table-container { padding:20px; background:white; border-radius:6px; box-shadow: rgba(0,0,0,0.16) 0px 1px 4px; }
.filter-card { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.filter-badge { background: rgba(255,255,255,0.2); color: white; }
</style>
<body>

<?php include "../include/nav.php";?>

<div class="content" style="padding:20px">
    
    <!-- Filter Section -->
    <div class="card mb-4 shadow-sm filter-card text-white">
        <div class="card-body">
            <h5 class="card-title"><i class="fa fa-filter"></i> Filter Notes</h5>
            <form method="GET" action="" class="row g-3 align-items-end">
                <div class="col-md-4">
                    <label class="form-label">Course</label>
                    <select name="course" class="form-select">
                        <option value="">All Courses</option>
                        <?php while($course_row = $courses_query->fetch_assoc()): ?>
                            <option value="<?= htmlspecialchars($course_row['course']) ?>" 
                                <?= $course_filter == $course_row['course'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($course_row['course']) ?>
                            </option>
                        <?php endwhile; ?>
                    </select>
                </div>
                <div class="col-md-4">
                    <label class="form-label">Search</label>
                    <input type="text" name="search" class="form-control" 
                           placeholder="Search by title or content..." 
                           value="<?= htmlspecialchars($search_filter) ?>">
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-light w-100">
                        <i class="fa fa-search"></i> Apply
                    </button>
                </div>
                <div class="col-md-2">
                    <a href="notes.php" class="btn btn-outline-light w-100">
                        <i class="fa fa-refresh"></i> Reset
                    </a>
                </div>
            </form>
            
            <!-- Active Filters Display -->
            <?php if (!empty($course_filter) || !empty($search_filter)): ?>
            <div class="mt-3">
                <small class="filter-badge px-3 py-1 rounded-pill">
                    <i class="fa fa-info-circle"></i> Active Filters:
                    <?php if (!empty($course_filter)): ?>
                        <span class="badge bg-light text-dark mx-1">Course: <?= htmlspecialchars($course_filter) ?></span>
                    <?php endif; ?>
                    <?php if (!empty($search_filter)): ?>
                        <span class="badge bg-light text-dark mx-1">Search: "<?= htmlspecialchars($search_filter) ?>"</span>
                    <?php endif; ?>
                    <span class="badge bg-light text-dark mx-1">Results: <?= $notes_count ?></span>
                </small>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Notes Table -->
    <div class="card shadow-sm">
        <div class="card-header bg-secondary text-white d-flex justify-content-between align-items-center">
            <h5 class="mb-0"><i class="fa fa-list"></i> My Notes (<?= $notes_count ?>)</h5>
            <?php if (!empty($course_filter) || !empty($search_filter)): ?>
                <small class="text-light">
                    Filtered Results
                </small>
            <?php endif; ?>
        </div>
        <div class="card-body">
            <!-- Quick Stats -->
            <div class="row mb-3">
                <div class="col-md-6">
                    <div class="d-flex gap-2">
                        <span class="badge bg-primary">
                            <i class="fa fa-book"></i> Program: <?= htmlspecialchars($program) ?>
                        </span>
                        <?php if ($courses_query->num_rows > 0): ?>
                            <span class="badge bg-info">
                                <i class="fa fa-graduation-cap"></i> <?= $courses_query->num_rows ?> Courses Available
                            </span>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="col-md-6 text-end">
                    <span class="text-muted">
                        <?php if (!empty($course_filter) || !empty($search_filter)): ?>
                            Showing <?= $notes_count ?> filtered notes
                        <?php else: ?>
                            Showing all <?= $notes_count ?> notes
                        <?php endif; ?>
                    </span>
                </div>
            </div>

            <div class="table-responsive">
                <table class="table table-bordered table-hover align-middle" id="notesTable">
                    <thead class="table-dark">
                        <tr>
                            <th>#</th>
                            <th>Course</th>
                            <th>Title</th>
                            <th>Attachment</th>
                            <th>Posted At</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($notes_count > 0) {
                            $sn = 1;
                            while($row = $notes_query->fetch_assoc()) { 
                                // ✅ FIXED: Correct file path - files are in 'notes/' folder
                                $file_path = "notes/" . $row['doc'];
                                $has_file = !empty($row['doc']) && file_exists($file_path);
                            ?>
                                <tr>
                                    <td><?= $sn++; ?></td>
                                    <td>
                                        <span class="badge bg-primary"><?= htmlspecialchars($row['course']) ?></span>
                                    </td>
                                    <td>
                                        <strong><?= htmlspecialchars($row['title']) ?></strong>
                                        <?php if (strlen($row['note']) > 100): ?>
                                            <br><small class="text-muted"><?= htmlspecialchars(substr($row['note'], 0, 100)) ?>...</small>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-center">
                                        <?php if ($has_file): ?>
                                            <span class="badge bg-success">
                                                <i class="fa fa-paperclip"></i> <?= htmlspecialchars($row['doc']) ?>
                                            </span>
                                        <?php else: ?>
                                            <span class="badge bg-secondary">No file</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <small><?= date('M j, Y g:i A', strtotime($row['posted_at'])) ?></small>
                                    </td>
                                    <td>
                                        <div class="btn-group btn-group-sm">
                                            <?php if ($has_file): ?>
                                                <a href="download_note.php?id=<?= $row['id'] ?>" class="btn btn-success" title="Download">
                                                    <i class="fa fa-download"></i>
                                                </a>
                                            <?php endif; ?>
                                            <a class="btn btn-info" href="view_note.php?id=<?= $row['id'] ?>" title="View Details">
                                                <i class="fa fa-eye"></i>
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                        <?php } } else { ?>
                            <tr>
                                <td colspan="6" class="text-center text-muted py-4">
                                    <i class="fa fa-inbox fa-3x mb-3"></i><br>
                                    <?php if (!empty($course_filter) || !empty($search_filter)): ?>
                                        No notes found matching your filters.
                                        <br><a href="notes.php" class="btn btn-sm btn-outline-primary mt-2">Clear Filters</a>
                                    <?php else: ?>
                                        No notes available for your program (<?= htmlspecialchars($program) ?>).
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
// ✅ Search functionality for table (client-side)
document.getElementById("notesSearch").addEventListener("keyup", function() {
    let filter = this.value.toLowerCase();
    document.querySelectorAll("#notesTable tbody tr").forEach(row => {
        let text = row.textContent.toLowerCase();
        row.style.display = text.includes(filter) ? "" : "none";
    });
});

// ✅ Auto-submit form when course selection changes
document.querySelector('select[name="course"]').addEventListener('change', function() {
    this.form.submit();
});
</script>

</body>
</html>