<?php
session_start();
ob_start();

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

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

$email = $_SESSION['email'];
$success = "";
$error   = "";

// Handle delete
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
    $delete = intval($_GET['id']); 

    // Get file path before deletion for cleanup
    $file_query = $conn->query("SELECT doc FROM notes WHERE id='$delete' AND teacher_email='$email'");
    if ($file_query->num_rows > 0) {
        $file_data = $file_query->fetch_assoc();
        $file_path = $file_data['doc'];
        
        $deletes = mysqli_query($conn, "DELETE FROM notes WHERE id='$delete' AND teacher_email='$email'");

        if ($deletes) {
            // Delete the physical file
            if (!empty($file_path) && file_exists($file_path)) {
                unlink($file_path);
            }
            header("Location: notes.php?success=Note Successfully Deleted");
            exit();
        } else {
            header("Location: notes.php?error=Failed to delete note");
            exit();
        }
    } else {
        header("Location: notes.php?error=Note not found or access denied");
        exit();
    }
}

// Handle add note with file upload
if (isset($_POST['add_note'])) {
    $program = $conn->real_escape_string($_POST['program']);
    $course_id = intval($_POST['course']);
    $title   = $conn->real_escape_string($_POST['title']);
    $note    = $conn->real_escape_string($_POST['note']);
    
    // Fetch course name from course ID
    $course_query = $conn->query("SELECT course FROM course WHERE id = '$course_id'");
    if ($course_query->num_rows > 0) {
        $course_row = $course_query->fetch_assoc();
        $course = $conn->real_escape_string($course_row['course']);
    } else {
        $error = "Invalid course selected";
    }
    
    $file_name = "";
    $file_path = "";
    
    // Handle file upload
    if (isset($_FILES['file_upload']) && $_FILES['file_upload']['error'] === UPLOAD_ERR_OK) {
        $upload_dir = "notes/";
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }
        
        $file_tmp = $_FILES['file_upload']['tmp_name'];
        $file_name = basename($_FILES['file_upload']['name']);
        $file_size = $_FILES['file_upload']['size'];
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
        
        // Validation
        $allowed_types = ['pdf', 'doc', 'docx', 'txt', 'jpg', 'png', 'pptx', 'zip'];
        $max_size = 10 * 1024 * 1024; // 10MB
        
        if (!in_array($file_ext, $allowed_types)) {
            $error = "Sorry, only PDF, DOC, DOCX, TXT, JPG, PNG, PPTX, ZIP files are allowed.";
        } elseif ($file_size > $max_size) {
            $error = "Sorry, your file is too large. Maximum size is 10MB.";
        } else {
            // Generate unique filename
            $new_filename = uniqid() . "_" . $file_name;
            $file_path = $upload_dir . $new_filename;
            
            if (!move_uploaded_file($file_tmp, $file_path)) {
                $error = "Sorry, there was an error uploading your file.";
            }
        }
    }
    
    if (empty($error)) {
        $insert = $conn->query("INSERT INTO notes (teacher_email, program, course, title, note, doc) 
                                VALUES ('$email', '$program', '$course', '$title', '$note', '$file_path')");
        if ($insert) {
            $success = "Note posted successfully!";

            // === START: Send email notification to students ===
            $adminResult = mysqli_query($conn, "SELECT * FROM admin LIMIT 1");
            $admin = $adminResult ? mysqli_fetch_assoc($adminResult) : ['sname' => 'School Administration'];

            $sname = $admin['sname'];

            $students = $conn->query("SELECT studentname, email 
                                      FROM students 
                                      WHERE program='$program'");

            if ($students && $students->num_rows > 0) {
                require_once __DIR__ . '/email/class.phpmailer.php';
                require_once __DIR__ . '/email/class.smtp.php';

                while ($student = $students->fetch_assoc()) {
                    $studentEmail = $student['email'];
                    $studentName  = $student['studentname'];

                    $mail = new PHPMailer(true);
                    try {
                        $mail->isSMTP();
                        $mail->Host       = 'unicohsuniversity.com';
                        $mail->SMTPAuth   = true;
                        $mail->Username   = 'contact@unicohsuniversity.com';
                        $mail->Password   = '@mypass1996';
                        $mail->SMTPSecure = 'tls';
                        $mail->Port       = 587;

                        $mail->setFrom('contact@unicohsuniversity.com', 'Makeni School of Health Sciences');
                        $mail->addAddress($studentEmail, $studentName);

                        $mail->isHTML(true);
                        $mail->Subject = "New Note Posted - $title";
                        $mail->Body    = "
                            Dear <strong>$studentName</strong>,<br><br>
                            A new note has been posted by your teacher:<br>
                            <strong>Title:</strong> $title<br>
                            <strong>Course:</strong> $course<br>
                            <strong>Program:</strong> $program<br><br>
                            " . (!empty($file_name) ? "<strong>Attachment:</strong> $file_name<br><br>" : "") . "
                            Please log in to the student portal to view all notes.<br><br>
                            Regards,<br>
                            $sname
                        ";

                        $mail->send();
                    } catch (Exception $e) {
                        error_log("Mailer Error to $studentEmail: " . $mail->ErrorInfo);
                    }
                }
            }
            // === END: Send email notification to students ===
        } else {
            $error = "Error posting note: " . $conn->error;
        }
    }
}

// Handle URL parameters for success/error messages
if (isset($_GET['success'])) {
    $success = $_GET['success'];
}
if (isset($_GET['error'])) {
    $error = $_GET['error'];
}

// ✅ Fetch programs and courses for dropdowns
$programs = $conn->query("SELECT DISTINCT program FROM programs ORDER BY program ASC");
$courses  = $conn->query("SELECT DISTINCT course FROM course ORDER BY course ASC");

// ✅ Fetch notes for current teacher
$notes = $conn->query("SELECT * FROM notes WHERE teacher_email='$email' ORDER BY posted_at DESC");
?>
<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Notes - Teacher Portal</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">
    <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>

<!-- TinyMCE for rich text editor -->
<script src="https://cdn.tiny.cloud/1/2mneaw1qjzanqgfmh23h72kldgoa6cy2bpgquxyfw9ey4cfq/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>
</head>

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

<div class="content">
<div class="container ">
  <h3 class="mb-4 text-danger"><i class="fa fa-sticky-note"></i> Manage Study Notes</h3>

  <?php if ($success) { ?>
    <div class="alert alert-success alert-dismissible fade show">
      <i class="fa fa-check-circle"></i> <?= htmlspecialchars($success); ?>
      <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
  <?php } ?>

  <?php if ($error) { ?>
    <div class="alert alert-danger alert-dismissible fade show">
      <i class="fa fa-exclamation-triangle"></i> <?= htmlspecialchars($error); ?>
      <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
  <?php } ?>

  <!-- Add Note Form -->
  <div class="card mb-4 shadow-sm">
    <div class="card-header bg-dark text-white">
      <h5 class="mb-0"><i class="fa fa-plus-circle"></i> Add New Note</h5>
    </div>
    <div class="card-body">
      <form method="POST" action="notes.php" enctype="multipart/form-data">
        <div class="row g-3">
          <div class="col-md-6">
            <label for="program" class="form-label">Program <span class="text-danger">*</span></label>
            <select name="program" id="programs" class="form-select" required>
              <option value="">Select Program</option>
              <?php
              $query = mysqli_query($conn, "SELECT * FROM programs ORDER BY id DESC");
              while ($row = mysqli_fetch_array($query)) {
                  echo "<option value='" . htmlspecialchars($row['program']) . "'>" . htmlspecialchars($row['program']) . "</option>";
              }
              ?>
            </select>
          </div>
          <div class="col-md-6">
            <label for="course" class="form-label">Course <span class="text-danger">*</span></label>
               <select name="course" id="courses" class="form-select" required>
    <option value="">Select Program first</option>
</select>

          </div>
          
          <div class="col-md-12">
            <label class="form-label">Title <span class="text-danger">*</span></label>
            <input type="text" name="title" class="form-control" placeholder="Enter note title" required>
          </div>
          
          <div class="col-md-12">
            <label class="form-label">Note Content <span class="text-danger">*</span></label>
            <textarea id="edito" name="note" class="form-control" rows="10" placeholder="Enter note content here..." required></textarea>
          </div>
          
          <div class="col-md-12">
            <label class="form-label">Attach File (Optional)</label>
            <input type="file" name="file_upload" class="form-control" accept=".pdf,.doc,.docx,.txt,.jpg,.png,.pptx,.zip">
            <div class="form-text">Allowed formats: PDF, DOC, DOCX, TXT, JPG, PNG, PPTX, ZIP (Max: 10MB)</div>
          </div>
          
          <div class="col-md-12 text-end">
            <button type="submit" name="add_note" class="btn btn-danger btn-lg">
              <i class="fa fa-paper-plane"></i> Post Note
            </button>
          </div>
        </div>
      </form>
    </div>
  </div>

  <!-- Notes Table -->
  <div class="card shadow-sm">
    <div class="card-header bg-secondary text-white">
      <h5 class="mb-0"><i class="fa fa-list"></i> My Notes (<?= $notes->num_rows ?>)</h5>
    </div>
    <div class="card-body">
      <!-- Search -->
      <div class="row mb-3">
        <div class="col-md-6">
          <input type="text" id="notesSearch" class="form-control" placeholder="Search by program, course, or title...">
        </div>
        <div class="col-md-6 text-end">
          <span class="text-muted">Showing <?= $notes->num_rows ?> notes</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>Program</th>
              <th>Course</th>
              <th>Title</th>
              <th>Attachment</th>
              <th>Posted At</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php if ($notes->num_rows > 0) {
              $sn = 1;
              while($row = $notes->fetch_assoc()) { 
                $has_file = !empty($row['doc']) && file_exists($row['doc']);
              ?>
                <tr>
                  <td><?= $sn++; ?></td>
                  <td><?= htmlspecialchars($row['program']); ?></td>
                  <td><?php echo $row['course']; ?></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(basename($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-danger" href="viewnotes.php?id=<?= $row['id']; ?>">   <i class="fa fa-eye"></i></a>
                      <a class="btn btn-danger" href="notes.php?id=<?= $row['id']; ?>" 
                         onclick="return confirm('Are you sure you want to delete this note? This action cannot be undone.');"
                         title="Delete">
                        <i class="fa fa-trash"></i>
                      </a>
                    </div>
                  </td>
                </tr>
            <?php } } else { ?>
              <tr>
                <td colspan="7" class="text-center text-muted py-4">
                  <i class="fa fa-inbox fa-3x mb-3"></i><br>
                  No notes posted yet. Start by adding your first note above.
                </td>
              </tr>
            <?php } ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

</div>
</div>

<script>
// Initialize TinyMCE
tinymce.init({
  selector: '#editor',
  plugins: 'lists link image table code help wordcount',
  toolbar: 'undo redo | bold italic underline | bullist numlist | link image | table | code | help',
  menubar: false,
  height: 300,
  promotion: false,
  branding: false
});

// AJAX for dynamic course loading
$(document).ready(function() {
    function loadCourses() {
        var program = $("#programs").val();

        if (program) {
            $.ajax({
                url: "fetch_course.php",
                type: "POST",
                data: { program: program },
                success: function(data) {
                    $("#courses").html(data);
                },
                error: function() {
                    $("#courses").html('<option value="">Error loading courses</option>');
                }
            });
        } else {
            $("#courses").html('<option value="">Select Program first</option>');
        }
    }

    $("#programs").change(loadCourses);
});

// Search functionality
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";
  });
});
</script>

</body>
</html>