<?php
require_once __DIR__ . '/../library/auth.php';
require_once __DIR__ . '/../library/audit_log.php';

$school_id = $_SESSION['school_id'];

allow_roles(['admin', 'teacher', 'accountant']);
$message = '';
$classes = [];

if ($_POST) {
    $title = trim($_POST['title']);
    $message_text = trim($_POST['message']);
    $for_role = $_POST['for_role'];
    $class_id = !empty($_POST['class_id']) ? intval($_POST['class_id']) : null;
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    
    if (empty($title) || empty($message_text)) {
        $message = '<div class="alert alert-danger">Title and Message are required!</div>';
    } else {
        // ✅ SCHOOL_ID ADDED IN QUERY
        $stmt = $pdo->prepare("INSERT INTO notifications (school_id, title, message, for_role, class_id, is_active) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->execute([$school_id, $title, $message_text, $for_role, $class_id, $is_active]);
        
        $notice_id = $pdo->lastInsertId();

        // Audit Log
        logActivity($pdo, [
            'school_id' => $school_id,
            'user_id'   => $_SESSION['user_id'],
            'module'    => 'Notices',
            'action'    => 'CREATE',
            'record_id' => $notice_id,
            'message'   => "Notice published: {$title}",
            'old_data'  => null,
            'new_data'  => [
                'title'      => $title,
                'message'    => $message_text,
                'for_role'   => $for_role,
                'class_id'   => $class_id,
                'is_active'  => $is_active
            ]
        ]);
        
        $message = '<div class="alert alert-success">Notice published successfully! <a href="list.php" class="btn btn-sm btn-success">View All Notices</a></div>';
    }
}

// Load Classes
$stmt = $pdo->query("SELECT id, class_name FROM classes ORDER BY id");
$classes = $stmt->fetchAll();

$page_title = 'Add Notice';
include __DIR__ . '/../include/header.php';
include __DIR__ . '/../include/sidebar.php';
?>

<div class="content-wrapper">
    <section class="content-header">
        <h1>Add New Notice / Circular</h1>
    </section>

    <section class="content">
        <div class="row">
            <div class="col-md-8">
                <div class="card card-primary">
                    <div class="card-header">
                        <h3 class="card-title">Publish Notification</h3>
                    </div>
                    <form method="POST">
                        <?php echo $message; ?>
                        
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-8">
                                    <div class="form-group">
                                        <label>Title <span class="text-danger">*</span></label>
                                        <input type="text" name="title" class="form-control" 
                                               placeholder="e.g., Fee Reminder, PTM Notice, Holiday" maxlength="255" required
                                               value="<?php echo htmlspecialchars($_POST['title'] ?? ''); ?>">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label>Target Audience <span class="text-danger">*</span></label>
                                        <select name="for_role" class="form-control" required>
                                            <option value="">Select Audience</option>
                                            <option value="all" <?php echo ($_POST['for_role'] ?? '') == 'all' ? 'selected' : ''; ?>>All (Everyone)</option>
                                            <option value="student" <?php echo ($_POST['for_role'] ?? '') == 'student' ? 'selected' : ''; ?>>Students</option>
                                            <option value="teacher" <?php echo ($_POST['for_role'] ?? '') == 'teacher' ? 'selected' : ''; ?>>Teachers</option>
                                            <option value="parent" <?php echo ($_POST['for_role'] ?? '') == 'parent' ? 'selected' : ''; ?>>Parents</option>
                                            <option value="admin" <?php echo ($_POST['for_role'] ?? '') == 'admin' ? 'selected' : ''; ?>>Admin Staff</option>
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <div class="form-group">
                                <label>Message <span class="text-danger">*</span></label>
                                <textarea name="message" class="form-control" rows="5" required
                                          placeholder="Write detailed message..."><?php echo htmlspecialchars($_POST['message'] ?? ''); ?></textarea>
                            </div>

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Class (Optional)</label>
                                        <select name="class_id" class="form-control">
                                            <option value="">All Classes</option>
                                            <?php foreach ($classes as $class): ?>
                                            <option value="<?php echo $class['id']; ?>" 
                                                    <?php echo ($_POST['class_id'] ?? '') == $class['id'] ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($class['class_name']); ?>
                                            </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label class="form-check-label">
                                            <input type="checkbox" name="is_active" value="1" <?php echo (!isset($_POST['is_active']) || $_POST['is_active']) ? 'checked' : ''; ?> class="form-check-input">
                                            Active / Visible
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="card-footer">
                            <button type="submit" class="btn btn-primary btn-lg">
                                <i class="fas fa-paper-plane"></i> Publish Notice
                            </button>
                            <a href="list.php" class="btn btn-secondary btn-lg">
                                <i class="fas fa-list"></i> View Notices
                            </a>
                        </div>
                    </form>
                </div>
            </div>

            <div class="col-md-4">
                <div class="card card-info">
                    <div class="card-header">
                        <h3 class="card-title">Quick Tips</h3>
                    </div>
                    <div class="card-body">
                        <ul class="list-unstyled">
                            <li><i class="fas fa-check-circle text-success"></i> Select "All" for everyone</li>
                            <li><i class="fas fa-check-circle text-success"></i> Use class filter for specific</li>
                            <li><i class="fas fa-check-circle text-success"></i> Keep active for dashboard</li>
                            <li><i class="fas fa-exclamation-triangle text-warning"></i> Max 255 chars title</li>
                        </ul>
                        <hr>
                        <div class="alert alert-light small">
                            <strong>Sample Titles:</strong><br>
                            • PTM Scheduled<br>
                            • Fee Due Reminder<br>
                            • Holiday Notice<br>
                            • Exam Timetable
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

<?php include __DIR__ . '/../include/footer.php'; ?>