<?php 
/**
 * Complaint Management System (School Module)
 * Location: /public_html/college/orc_sch/complaint.php
 * Table: complaints_sch
 */

// 1. Start Output Buffering (Prevents header errors)
ob_start();

error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();

// 2. Database Connection
if (file_exists('../db.php')) {
    require_once '../db.php';
} elseif (file_exists('db.php')) {
    require_once 'db.php';
} else {
    die("Database configuration file not found.");
}

// 3. Authentication Check
if (!isset($_SESSION['user_id'])) {
    if (file_exists('../login.php')) {
        header("Location: ../login.php");
    } else {
        // Fallback if local login.php exists
        if (file_exists('login.php')) {
             header("Location: login.php");
        } else {
             header("Location: /college/login.php");
        }
    }
    exit;
}

// 4. School ID Logic (FORCE ID 3 for testing based on your DB screenshot)
// If session exists, use it. If not, default to 3 to show your data.
$school_id = isset($_SESSION['school_id']) ? (int)$_SESSION['school_id'] : (isset($_SESSION['college_id']) ? (int)$_SESSION['college_id'] : 3);

// SAFETY: If ID is 0, force it to 3 for now so you see data
if ($school_id == 0) { $school_id = 3; }

$admin_name = isset($_SESSION['username']) ? $_SESSION['username'] : 'Admin';
$current_page = basename($_SERVER['PHP_SELF']);

// ==================== CREATE - ADD NEW COMPLAINT ====================
if (isset($_POST['add_complaint'])) {
    // Input Handling (Using Null Coalescing ?? '' to prevent errors)
    $complaint_type = mysqli_real_escape_string($db, $_POST['complaint_type'] ?? '');
    $subject = mysqli_real_escape_string($db, $_POST['subject'] ?? '');
    $description = mysqli_real_escape_string($db, $_POST['description'] ?? '');
    $student_name = mysqli_real_escape_string($db, $_POST['student_name'] ?? '');
    $student_email = mysqli_real_escape_string($db, $_POST['student_email'] ?? '');
    $student_phone = mysqli_real_escape_string($db, $_POST['student_phone'] ?? '');
    $student_id = mysqli_real_escape_string($db, $_POST['student_id'] ?? '');
    $course = mysqli_real_escape_string($db, $_POST['course'] ?? '');
    $year = mysqli_real_escape_string($db, $_POST['year'] ?? '');
    $department = mysqli_real_escape_string($db, $_POST['department'] ?? '');
    
    $is_anonymous = isset($_POST['is_anonymous']) ? 1 : 0;
    
    $status = mysqli_real_escape_string($db, $_POST['status'] ?? 'pending');
    $priority = mysqli_real_escape_string($db, $_POST['priority'] ?? 'medium');
    $assigned_to = mysqli_real_escape_string($db, $_POST['assigned_to'] ?? '');
    $admin_remarks = mysqli_real_escape_string($db, $_POST['admin_remarks'] ?? '');

    // Attachment Logic
    $attachment = '';
    if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] == 0) {
        $upload_dir = 'uploads/complaints/';
        if (!file_exists($upload_dir)) { mkdir($upload_dir, 0777, true); }

        $file_extension = pathinfo($_FILES['attachment']['name'], PATHINFO_EXTENSION);
        $file_name = 'complaint_' . time() . '_' . rand(1000, 9999) . '.' . $file_extension;
        $target_file = $upload_dir . $file_name;

        if (move_uploaded_file($_FILES['attachment']['tmp_name'], $target_file)) {
            $attachment = $target_file;
        }
    }

    $ip_address = $_SERVER['REMOTE_ADDR'];

    // Insert Query
    $insert_query = "INSERT INTO complaints_sch 
                     (school_id, complaint_type, subject, description, attachment, student_name, student_email, student_phone, student_id, course, year, department, is_anonymous, status, priority, assigned_to, admin_remarks, ip_address, created_at) 
                     VALUES 
                     ($school_id, '$complaint_type', '$subject', '$description', '$attachment', '$student_name', '$student_email', '$student_phone', '$student_id', '$course', '$year', '$department', $is_anonymous, '$status', '$priority', '$assigned_to', '$admin_remarks', '$ip_address', NOW())";

    if (mysqli_query($db, $insert_query)) {
        $success_message = "Complaint submitted successfully!";
        // Redirect to avoid resubmission on refresh
        header("Location: complaint.php"); 
        exit;
    } else {
        $error_message = "Error: " . mysqli_error($db);
    }
}

// ==================== UPDATE - EDIT COMPLAINT ====================
if (isset($_POST['update_complaint'])) {
    $complaint_id = (int)$_POST['complaint_id'];
    
    $complaint_type = mysqli_real_escape_string($db, $_POST['complaint_type'] ?? '');
    $subject = mysqli_real_escape_string($db, $_POST['subject'] ?? '');
    $description = mysqli_real_escape_string($db, $_POST['description'] ?? '');
    $student_name = mysqli_real_escape_string($db, $_POST['student_name'] ?? '');
    $student_email = mysqli_real_escape_string($db, $_POST['student_email'] ?? '');
    $student_phone = mysqli_real_escape_string($db, $_POST['student_phone'] ?? '');
    $student_id_field = mysqli_real_escape_string($db, $_POST['student_id'] ?? '');
    $course = mysqli_real_escape_string($db, $_POST['course'] ?? '');
    $year = mysqli_real_escape_string($db, $_POST['year'] ?? '');
    $department = mysqli_real_escape_string($db, $_POST['department'] ?? '');
    $status = mysqli_real_escape_string($db, $_POST['status'] ?? '');
    $priority = mysqli_real_escape_string($db, $_POST['priority'] ?? '');
    $assigned_to = mysqli_real_escape_string($db, $_POST['assigned_to'] ?? '');
    $admin_remarks = mysqli_real_escape_string($db, $_POST['admin_remarks'] ?? '');
    $resolution_details = mysqli_real_escape_string($db, $_POST['resolution_details'] ?? '');
    $resolved_by = mysqli_real_escape_string($db, $_POST['resolved_by'] ?? '');

    $attachment_update = "";
    if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] == 0) {
        $upload_dir = 'uploads/complaints/';
        if (!file_exists($upload_dir)) { mkdir($upload_dir, 0777, true); }
        $file_extension = pathinfo($_FILES['attachment']['name'], PATHINFO_EXTENSION);
        $file_name = 'complaint_' . time() . '_' . rand(1000, 9999) . '.' . $file_extension;
        $target_file = $upload_dir . $file_name;

        if (move_uploaded_file($_FILES['attachment']['tmp_name'], $target_file)) {
            $attachment_update = ", attachment = '$target_file'";
        }
    }

    $resolved_at_update = ($status == 'resolved') ? ", resolved_at = NOW()" : "";

    $update_query = "UPDATE complaints_sch 
                     SET complaint_type = '$complaint_type',
                         subject = '$subject',
                         description = '$description',
                         student_name = '$student_name',
                         student_email = '$student_email',
                         student_phone = '$student_phone',
                         student_id = '$student_id_field',
                         course = '$course',
                         year = '$year',
                         department = '$department',
                         status = '$status',
                         priority = '$priority',
                         assigned_to = '$assigned_to',
                         admin_remarks = '$admin_remarks',
                         resolution_details = '$resolution_details',
                         resolved_by = '$resolved_by'
                         $attachment_update
                         $resolved_at_update
                     WHERE id = $complaint_id AND school_id = $school_id";

    if (mysqli_query($db, $update_query)) {
        $success_message = "Complaint updated successfully!";
        header("Location: complaint.php");
        exit;
    } else {
        $error_message = "Error: " . mysqli_error($db);
    }
}

// ==================== DELETE ====================
if (isset($_GET['delete_id'])) {
    $delete_id = (int)$_GET['delete_id'];
    mysqli_query($db, "DELETE FROM complaints_sch WHERE id = $delete_id AND school_id = $school_id");
    header("Location: complaint.php");
    exit;
}

// ==================== READ - FILTER & SEARCH ====================
$filter_type = isset($_GET['type']) ? $_GET['type'] : 'all';
$filter_status = isset($_GET['status']) ? $_GET['status'] : 'all';
$filter_priority = isset($_GET['priority']) ? $_GET['priority'] : 'all';
$search = isset($_GET['search']) ? mysqli_real_escape_string($db, $_GET['search']) : '';

// Base Where Clause
$where_clause = "WHERE school_id = $school_id";

if ($filter_type != 'all') $where_clause .= " AND complaint_type = '$filter_type'";
if ($filter_status != 'all') $where_clause .= " AND status = '$filter_status'";
if ($filter_priority != 'all') $where_clause .= " AND priority = '$filter_priority'";
if (!empty($search)) $where_clause .= " AND (subject LIKE '%$search%' OR student_name LIKE '%$search%' OR student_id LIKE '%$search%')";

// Query to Fetch All Data
// ORDER BY id DESC ensures newest are first, but NO LIMIT is set so all show up
$complaints_query = "SELECT * FROM complaints_sch $where_clause ORDER BY id DESC";
$complaints_result = mysqli_query($db, $complaints_query);
$total_complaints = $complaints_result ? mysqli_num_rows($complaints_result) : 0;

// Edit Fetch
$edit_complaint = null;
if (isset($_GET['edit_id'])) {
    $edit_id = (int)$_GET['edit_id'];
    $edit_result = mysqli_query($db, "SELECT * FROM complaints_sch WHERE id = $edit_id AND school_id = $school_id");
    $edit_complaint = mysqli_fetch_assoc($edit_result);
}

// Stats
$pending_count = @mysqli_num_rows(mysqli_query($db, "SELECT id FROM complaints_sch WHERE school_id = $school_id AND status = 'pending'")) ?: 0;
$in_progress_count = @mysqli_num_rows(mysqli_query($db, "SELECT id FROM complaints_sch WHERE school_id = $school_id AND status = 'in_progress'")) ?: 0;
$resolved_count = @mysqli_num_rows(mysqli_query($db, "SELECT id FROM complaints_sch WHERE school_id = $school_id AND status = 'resolved'")) ?: 0;
$closed_count = @mysqli_num_rows(mysqli_query($db, "SELECT id FROM complaints_sch WHERE school_id = $school_id AND status = 'closed'")) ?: 0;

if (file_exists('header.php')) {
    require_once 'header.php';
} else {
    echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>School Complaints</title></head><body>';
}
?>

<style>
/* CSS Styles */
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #f5f6fa; color: #2c3e50; }
.sidebar { position: fixed; left: 0; top: 0; width: 260px; height: 100vh; background: linear-gradient(180deg, #2c3e50 0%, #34495e 100%); color: white; padding: 20px 0; overflow-y: auto; z-index: 1000; box-shadow: 2px 0 10px rgba(0,0,0,0.1); }
.sidebar-header { padding: 20px; border-bottom: 1px solid rgba(255,255,255,0.1); margin-bottom: 20px; }
.sidebar-header h2 { font-size: 1.3em; font-weight: 600; }
.sidebar-menu { padding: 0 10px; }
.menu-item { display: block; padding: 12px 20px; color: #ecf0f1; text-decoration: none; border-radius: 8px; margin-bottom: 5px; transition: all 0.3s ease; font-size: 0.95em; }
.menu-item:hover { background: rgba(255,255,255,0.1); padding-left: 25px; }
.menu-item.active { background: #3498db; font-weight: 600; }
.main-content-area { margin-left: 260px; padding: 30px; min-height: 100vh; }
.page-header { background: white; padding: 25px 30px; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); margin-bottom: 30px; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 15px; }
.stats-container { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 30px; }
.stat-card { background: white; padding: 20px; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); display: flex; align-items: center; gap: 15px; }
.stat-icon { width: 50px; height: 50px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 1.5em; }
.stat-icon.pending { background: #fff3cd; color: #856404; }
.stat-icon.progress { background: #cce5ff; color: #004085; }
.stat-icon.resolved { background: #d4edda; color: #155724; }
.stat-icon.closed { background: #f8d7da; color: #721c24; }
.filter-bar { background: white; padding: 20px 30px; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); margin-bottom: 30px; display: flex; gap: 15px; flex-wrap: wrap; align-items: center; }
.filter-box { flex: 1; min-width: 150px; }
.filter-box select, .filter-box input { width: 100%; padding: 10px 15px; border: 1px solid #ddd; border-radius: 8px; }
.alert { padding: 15px 20px; border-radius: 8px; margin-bottom: 20px; font-weight: 500; }
.alert-success { background: #d4edda; color: #155724; }
.alert-error { background: #f8d7da; color: #721c24; }
.form-container { background: white; padding: 30px; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); margin-bottom: 30px; display: none; }
.form-container.show { display: block; }
.form-row { display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px; margin-bottom: 20px; }
.form-group { margin-bottom: 20px; }
.form-group.full-width { grid-column: 1 / -1; }
.form-control { width: 100%; padding: 12px 15px; border: 1px solid #ddd; border-radius: 8px; }
.btn-add { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 12px 25px; border-radius: 8px; border: none; cursor: pointer; }
.btn-submit { background: #28a745; color: white; padding: 12px 30px; border: none; border-radius: 8px; cursor: pointer; }
.btn-cancel { background: #6c757d; color: white; padding: 12px 30px; border: none; border-radius: 8px; cursor: pointer; margin-left: 10px; }
.complaints-container { background: white; padding: 30px; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); }
.complaints-table { width: 100%; border-collapse: collapse; }
.complaints-table th { background: #f8f9fa; padding: 15px; text-align: left; border-bottom: 2px solid #e9ecef; }
.complaints-table td { padding: 15px; border-bottom: 1px solid #e9ecef; }
.status-badge { padding: 5px 12px; border-radius: 15px; font-size: 0.8em; font-weight: 600; display: inline-block; }
.status-pending { background: #fff3cd; color: #856404; }
.status-in_progress { background: #cce5ff; color: #004085; }
.status-resolved { background: #d4edda; color: #155724; }
.status-closed { background: #f8d7da; color: #721c24; }
.no-data { text-align: center; padding: 50px; color: #7f8c8d; }
@media (max-width: 768px) {
    .sidebar { width: 100%; height: auto; position: relative; }
    .main-content-area { margin-left: 0; padding: 15px; }
    .form-row { grid-template-columns: 1fr; }
    .complaints-table { display: block; overflow-x: auto; }
}
</style>

<!-- SIDEBAR -->
<div class="sidebar">
    <div class="sidebar-header">
        <h2>🏫 School Admin</h2>
    </div>
   <nav class="sidebar-menu">
        <a href="dashboard.php" class="menu-item <?php echo $current_page == 'dashboard.php' ? 'active' : ''; ?>">🏠 Dashboard</a>
        <a href="Course.php" class="menu-item <?php echo $current_page == 'Course.php' ? 'active' : ''; ?>">📚 Classes/Courses</a>
        <a href="teachers.php" class="menu-item <?php echo $current_page == 'teachers.php' ? 'active' : ''; ?>">👨‍🏫 Teachers</a>
        <a href="complaint.php" class="menu-item <?php echo ($current_page == 'complaint.php') ? 'active' : ''; ?>">📝 Complaints</a>
        <a href="Gallery.php" class="menu-item <?php echo $current_page == 'Gallery.php' ? 'active' : ''; ?>">🖼️ Gallery</a>
        <a href="Contact.php" class="menu-item <?php echo $current_page == 'Contact.php' ? 'active' : ''; ?>">📧 Contact</a>
        <a href="logout.php" class="menu-item <?php echo ($current_page == 'logout.php') ? 'active' : ''; ?>">🚪Logout</a>
    </nav>
</div>

<!-- MAIN CONTENT -->
<div class="main-content-area">

    <div class="page-header">
        <h2>📝 School Complaints (<?php echo $total_complaints; ?>)</h2>
        <?php if (!isset($_GET['edit_id'])): ?>
            <button class="btn-add" onclick="toggleForm('add-form')">➕ Add New Complaint</button>
        <?php endif; ?>
    </div>

    <?php if (isset($success_message)): ?>
        <div class="alert alert-success">✓ <?php echo $success_message; ?></div>
    <?php endif; ?>

    <?php if (isset($error_message)): ?>
        <div class="alert alert-error">✗ <?php echo $error_message; ?></div>
    <?php endif; ?>

    <div class="stats-container">
        <div class="stat-card"><div class="stat-icon pending">⏳</div><div class="stat-info"><h3><?php echo $pending_count; ?></h3><p>Pending</p></div></div>
        <div class="stat-card"><div class="stat-icon progress">🔄</div><div class="stat-info"><h3><?php echo $in_progress_count; ?></h3><p>In Progress</p></div></div>
        <div class="stat-card"><div class="stat-icon resolved">✅</div><div class="stat-info"><h3><?php echo $resolved_count; ?></h3><p>Resolved</p></div></div>
        <div class="stat-card"><div class="stat-icon closed">🔒</div><div class="stat-info"><h3><?php echo $closed_count; ?></h3><p>Closed</p></div></div>
    </div>

    <?php if (!$edit_complaint && !isset($_GET['edit_id'])): ?>
    <div class="filter-bar">
        <form method="GET" style="display: flex; gap: 15px; flex-wrap: wrap; width: 100%;">
            <div class="filter-box">
                <input type="text" name="search" placeholder="🔍 Search..." value="<?php echo htmlspecialchars($search); ?>">
            </div>
            <div class="filter-box">
                <select name="type" onchange="this.form.submit()">
                    <option value="all">All Types</option>
                    <option value="academic" <?php echo $filter_type == 'academic' ? 'selected' : ''; ?>>Academic</option>
                    <option value="facility" <?php echo $filter_type == 'facility' ? 'selected' : ''; ?>>Facility</option>
                    <option value="hostel" <?php echo $filter_type == 'hostel' ? 'selected' : ''; ?>>Hostel</option>
                    <option value="transport" <?php echo $filter_type == 'transport' ? 'selected' : ''; ?>>Transport</option>
                </select>
            </div>
            <div class="filter-box">
                <select name="status" onchange="this.form.submit()">
                    <option value="all">All Status</option>
                    <option value="pending" <?php echo $filter_status == 'pending' ? 'selected' : ''; ?>>Pending</option>
                    <option value="in_progress" <?php echo $filter_status == 'in_progress' ? 'selected' : ''; ?>>In Progress</option>
                    <option value="resolved" <?php echo $filter_status == 'resolved' ? 'selected' : ''; ?>>Resolved</option>
                    <option value="closed" <?php echo $filter_status == 'closed' ? 'selected' : ''; ?>>Closed</option>
                </select>
            </div>
        </form>
    </div>
    <?php endif; ?>

    <!-- FORM SECTION -->
    <div class="form-container <?php echo $edit_complaint ? 'show' : ''; ?>" id="add-form">
        <h3><?php echo $edit_complaint ? '✏️ Edit Complaint' : '➕ Add New Complaint'; ?></h3>
        <form method="POST" enctype="multipart/form-data">
            <?php if ($edit_complaint): ?><input type="hidden" name="complaint_id" value="<?php echo $edit_complaint['id']; ?>"><?php endif; ?>

            <div class="form-row">
                <div class="form-group">
                    <label>Type *</label>
                    <select name="complaint_type" class="form-control" required>
                        <option value="academic" <?php echo ($edit_complaint && $edit_complaint['complaint_type'] == 'academic') ? 'selected' : ''; ?>>Academic</option>
                        <option value="facility" <?php echo ($edit_complaint && $edit_complaint['complaint_type'] == 'facility') ? 'selected' : ''; ?>>Facility</option>
                        <option value="hostel" <?php echo ($edit_complaint && $edit_complaint['complaint_type'] == 'hostel') ? 'selected' : ''; ?>>Hostel</option>
                        <option value="transport" <?php echo ($edit_complaint && $edit_complaint['complaint_type'] == 'transport') ? 'selected' : ''; ?>>Transport</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Subject *</label>
                    <input type="text" name="subject" class="form-control" required value="<?php echo $edit_complaint ? htmlspecialchars($edit_complaint['subject']) : ''; ?>">
                </div>
            </div>

            <div class="form-group full-width">
                <label>Description *</label>
                <textarea name="description" class="form-control" required style="height:100px"><?php echo $edit_complaint ? htmlspecialchars($edit_complaint['description']) : ''; ?></textarea>
            </div>

            <div class="form-row">
                <div class="form-group"><label>Student Name</label><input type="text" name="student_name" class="form-control" value="<?php echo $edit_complaint ? htmlspecialchars($edit_complaint['student_name']) : ''; ?>"></div>
                <div class="form-group"><label>Student Email</label><input type="email" name="student_email" class="form-control" value="<?php echo $edit_complaint ? htmlspecialchars($edit_complaint['student_email']) : ''; ?>"></div>
            </div>

            <div class="form-row">
                <div class="form-group"><label>Phone</label><input type="text" name="student_phone" class="form-control" value="<?php echo $edit_complaint ? htmlspecialchars($edit_complaint['student_phone']) : ''; ?>"></div>
                <div class="form-group"><label>Student ID</label><input type="text" name="student_id" class="form-control" value="<?php echo $edit_complaint ? htmlspecialchars($edit_complaint['student_id']) : ''; ?>"></div>
            </div>

            <div class="form-row">
                <div class="form-group"><label>Course/Class</label><input type="text" name="course" class="form-control" value="<?php echo $edit_complaint ? htmlspecialchars($edit_complaint['course']) : ''; ?>"></div>
                <div class="form-group"><label>Year</label><input type="text" name="year" class="form-control" value="<?php echo $edit_complaint ? htmlspecialchars($edit_complaint['year']) : ''; ?>"></div>
            </div>

            <div class="form-row">
                <div class="form-group"><label>Department/Section</label><input type="text" name="department" class="form-control" value="<?php echo $edit_complaint ? htmlspecialchars($edit_complaint['department']) : ''; ?>"></div>
                <div class="form-group"><label>Status</label>
                    <select name="status" class="form-control">
                        <option value="pending" <?php echo ($edit_complaint && $edit_complaint['status']=='pending')?'selected':''; ?>>Pending</option>
                        <option value="in_progress" <?php echo ($edit_complaint && $edit_complaint['status']=='in_progress')?'selected':''; ?>>In Progress</option>
                        <option value="resolved" <?php echo ($edit_complaint && $edit_complaint['status']=='resolved')?'selected':''; ?>>Resolved</option>
                        <option value="closed" <?php echo ($edit_complaint && $edit_complaint['status']=='closed')?'selected':''; ?>>Closed</option>
                    </select>
                </div>
            </div>

            <div class="form-row">
                <div class="form-group"><label>Priority</label>
                    <select name="priority" class="form-control">
                        <option value="low">Low</option><option value="medium">Medium</option><option value="high">High</option>
                    </select>
                </div>
                <div class="form-group"><label>Assigned To</label><input type="text" name="assigned_to" class="form-control" value="<?php echo $edit_complaint ? htmlspecialchars($edit_complaint['assigned_to']) : ''; ?>"></div>
            </div>

            <div class="form-group full-width">
                <label>Admin Remarks</label>
                <textarea name="admin_remarks" class="form-control"><?php echo $edit_complaint ? htmlspecialchars($edit_complaint['admin_remarks']) : ''; ?></textarea>
            </div>

            <button type="submit" name="<?php echo $edit_complaint ? 'update_complaint' : 'add_complaint'; ?>" class="btn-submit">Submit</button>
            <button type="button" class="btn-cancel" onclick="toggleForm('add-form')">Cancel</button>
        </form>
    </div>

    <!-- DATA LIST -->
    <div class="complaints-container">
        <?php if ($total_complaints > 0): ?>
            <table class="complaints-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Type</th>
                        <th>Subject</th>
                        <th>Student</th>
                        <th>Status</th>
                        <th>Date</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php while ($row = mysqli_fetch_assoc($complaints_result)): ?>
                    <tr>
                        <td>#<?php echo $row['id']; ?></td>
                        <td><?php echo ucfirst($row['complaint_type']); ?></td>
                        <td><?php echo htmlspecialchars($row['subject']); ?></td>
                        <td>
                            <?php echo htmlspecialchars($row['student_name']); ?>
                            <br><small><?php echo htmlspecialchars($row['student_id']); ?></small>
                        </td>
                        <td><span class="status-badge status-<?php echo $row['status']; ?>"><?php echo ucfirst($row['status']); ?></span></td>
                        <td><?php echo date('d M Y', strtotime($row['created_at'])); ?></td>
                        <td>
                            <a href="?edit_id=<?php echo $row['id']; ?>" style="text-decoration:none;margin-right:10px;">✏️</a>
                            <a href="?delete_id=<?php echo $row['id']; ?>" onclick="return confirm('Delete this complaint?')" style="text-decoration:none;">🗑️</a>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        <?php else: ?>
            <div class="no-data">
                <p>No complaints found. (School ID: <?php echo $school_id; ?>)</p>
            </div>
        <?php endif; ?>
    </div>

</div>

<script>
function toggleForm(id) {
    var el = document.getElementById(id);
    if(el) {
        if(el.classList.contains('show')) {
            el.classList.remove('show');
        } else {
            el.classList.add('show');
            window.scrollTo({top: 0, behavior: 'smooth'});
        }
    }
}
</script>

<?php 
// 6. Flush Buffer
ob_end_flush();
if (file_exists('footer.php')) require_once 'footer.php'; 
?>
