<?php
session_start();
require_once '../config/database.php';

// Only admin and teacher can add notices
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['user_role'], ['admin','teacher'])) {
    header('Location: ../login.php');
    exit();
}

$success_message = '';
$error_message = '';

// Ensure notices table exists (matches notices/index.php expectations)
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS notices (
        id INT AUTO_INCREMENT PRIMARY KEY,
        title VARCHAR(255) NOT NULL,
        content TEXT NOT NULL,
        target_audience ENUM('all','students','teachers','parents','specific_class') DEFAULT 'all',
        class_id INT NULL,
        publish_date DATE NOT NULL,
        expiry_date DATE NULL,
        priority ENUM('urgent','high','medium','low') DEFAULT 'low',
        status ENUM('active','inactive') DEFAULT 'active',
        created_by INT NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        INDEX (publish_date),
        INDEX (status)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    
    // Fix priority column if it exists with wrong type
    try {
        $pdo->exec("ALTER TABLE notices MODIFY COLUMN priority ENUM('urgent','high','medium','low') DEFAULT 'low'");
    } catch (Exception $e) {
        // Column might not exist or already correct
    }
} catch (Exception $e) {
    // table create failure shouldn't block page rendering; will show error on submit
}

// Ensure attachments table exists
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS notices_attachments (
        id INT AUTO_INCREMENT PRIMARY KEY,
        notice_id INT NOT NULL,
        file_path VARCHAR(500) NOT NULL,
        original_name VARCHAR(255) NOT NULL,
        mime_type VARCHAR(150) NULL,
        file_size INT NULL,
        uploaded_by INT NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        INDEX (notice_id),
        CONSTRAINT fk_notices_attachments_notice FOREIGN KEY (notice_id) REFERENCES notices(id) ON DELETE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
} catch (Exception $e) {
    // ignore
}

// Load classes for specific_class selection
$classes = [];
try {
    $stmt = $pdo->query("SELECT id, name, section FROM classes WHERE status='active' ORDER BY name, section");
    $classes = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_notice'])) {
    $title = trim($_POST['title'] ?? '');
    $content = trim($_POST['content'] ?? '');
    $target_audience = $_POST['target_audience'] ?? 'all';
    $class_id = !empty($_POST['class_id']) ? (int)$_POST['class_id'] : null;
    $priority = $_POST['priority'] ?? 'low';
    $status = $_POST['status'] ?? 'active';
    $publish_date = $_POST['publish_date'] ?? date('Y-m-d');
    $expiry_date = !empty($_POST['expiry_date']) ? $_POST['expiry_date'] : null;

    if ($title === '' || $content === '') {
        $error_message = 'শিরোনাম এবং বিবরণ দেওয়া আবশ্যক';
    } elseif ($target_audience === 'specific_class' && !$class_id) {
        $error_message = 'নির্দিষ্ট ক্লাসের জন্য ক্লাস নির্বাচন করুন';
    } else {
        try {
            $pdo->beginTransaction();
            $stmt = $pdo->prepare("INSERT INTO notices 
                (title, content, target_audience, class_id, publish_date, expiry_date, priority, status, created_by)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([
                $title,
                $content,
                $target_audience,
                $class_id,
                $publish_date,
                $expiry_date,
                $priority,
                $status,
                $_SESSION['user_id']
            ]);
            $notice_id = (int)$pdo->lastInsertId();

            // Handle file uploads
            if (!empty($_FILES['attachments']['name'][0])) {
                $baseDir = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'notices';
                if (!is_dir($baseDir)) { @mkdir($baseDir, 0777, true); }
                $allowed = [
                    'application/pdf','image/jpeg','image/png','image/gif','application/msword','application/vnd.openxmlformats-officedocument.wordprocessingml.document'
                ];
                foreach ($_FILES['attachments']['name'] as $i => $orig) {
                    if ($_FILES['attachments']['error'][$i] !== UPLOAD_ERR_OK) { continue; }
                    $tmp = $_FILES['attachments']['tmp_name'][$i];
                    $type = $_FILES['attachments']['type'][$i] ?? '';
                    $size = (int)($_FILES['attachments']['size'][$i] ?? 0);
                    if ($size > 20*1024*1024) { continue; } // 20MB limit
                    if ($type && !in_array($type, $allowed)) { continue; }
                    $ext = pathinfo($orig, PATHINFO_EXTENSION);
                    $safeName = preg_replace('/[^A-Za-z0-9_\.-]/','_', pathinfo($orig, PATHINFO_FILENAME));
                    $newName = date('Ymd_His') . '_' . bin2hex(random_bytes(4)) . '_' . $safeName . ($ext?'.'.$ext:'');
                    $dest = $baseDir . DIRECTORY_SEPARATOR . $newName;
                    if (move_uploaded_file($tmp, $dest)) {
                        $relPath = 'uploads/notices/' . $newName; // relative from web root
                        $stmtA = $pdo->prepare("INSERT INTO notices_attachments (notice_id, file_path, original_name, mime_type, file_size, uploaded_by) VALUES (?, ?, ?, ?, ?, ?)");
                        $stmtA->execute([$notice_id, $relPath, $orig, $type, $size, $_SESSION['user_id']]);
                    }
                }
            }

            $pdo->commit();
            $success_message = 'নোটিশ সফলভাবে তৈরি হয়েছে';
            $_POST = [];
        } catch (Exception $e) {
            if ($pdo->inTransaction()) { $pdo->rollBack(); }
            $error_message = 'নোটিশ তৈরি করতে সমস্যা হয়েছে: ' . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>নতুন নোটিশ যোগ</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
    <div class="container-fluid">
        <a class="navbar-brand" href="../index.php"><i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট সিস্টেম</a>
        <div class="navbar-nav ms-auto">
            <a class="nav-link" href="index.php"><i class="fas fa-bullhorn"></i> নোটিশ বোর্ড</a>
            <a class="nav-link" href="../index.php"><i class="fas fa-home"></i> হোম</a>
            <a class="nav-link" href="../logout.php"><i class="fas fa-sign-out-alt"></i> লগআউট</a>
        </div>
    </div>
</nav>

<div class="container-fluid mt-4">
    <div class="row">
        <div class="col-md-8 mx-auto">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5><i class="fas fa-plus"></i> নতুন নোটিশ</h5>
                    <a href="index.php" class="btn btn-secondary btn-sm"><i class="fas fa-arrow-left"></i> তালিকায় ফিরুন</a>
                </div>
                <div class="card-body">
                    <?php if ($success_message): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <i class="fas fa-check-circle"></i> <?= htmlspecialchars($success_message) ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    <?php if ($error_message): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="fas fa-exclamation-triangle"></i> <?= htmlspecialchars($error_message) ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <form method="POST" action="" enctype="multipart/form-data">
                        <div class="mb-3">
                            <label class="form-label">শিরোনাম <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="title" value="<?= htmlspecialchars($_POST['title'] ?? '') ?>" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">বিবরণ <span class="text-danger">*</span></label>
                            <textarea class="form-control" name="content" rows="6" required><?= htmlspecialchars($_POST['content'] ?? '') ?></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">ডকুমেন্ট/ছবি আপলোড (একাধিক)</label>
                            <input type="file" class="form-control" name="attachments[]" multiple accept=".pdf,.jpg,.jpeg,.png,.gif,.doc,.docx">
                            <small class="text-muted">সর্বোচ্চ ফাইল সাইজ: 20MB; অনুমোদিত: PDF, JPG, PNG, GIF, DOC, DOCX</small>
                        </div>
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="form-label">লক্ষ্য দর্শক</label>
                                <select class="form-select" id="target_audience" name="target_audience">
                                    <option value="all" <?= (($_POST['target_audience'] ?? '')==='all')?'selected':''; ?>>সবার জন্য</option>
                                    <option value="students" <?= (($_POST['target_audience'] ?? '')==='students')?'selected':''; ?>>ছাত্র-ছাত্রী</option>
                                    <option value="teachers" <?= (($_POST['target_audience'] ?? '')==='teachers')?'selected':''; ?>>শিক্ষক</option>
                                    <option value="parents" <?= (($_POST['target_audience'] ?? '')==='parents')?'selected':''; ?>>অভিভাবক</option>
                                    <option value="specific_class" <?= (($_POST['target_audience'] ?? '')==='specific_class')?'selected':''; ?>>নির্দিষ্ট ক্লাস</option>
                                </select>
                            </div>
                            <div class="col-md-4 mb-3" id="class_select_wrapper" style="display: none;">
                                <label class="form-label">ক্লাস</label>
                                <select class="form-select" name="class_id">
                                    <option value="">ক্লাস নির্বাচন করুন</option>
                                    <?php foreach ($classes as $c): ?>
                                        <option value="<?= (int)$c['id'] ?>" <?= (isset($_POST['class_id']) && (int)$_POST['class_id']===(int)$c['id'])?'selected':''; ?>>
                                            <?= htmlspecialchars($c['name'] . ' - ' . $c['section']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">অগ্রাধিকার</label>
                                <select class="form-select" name="priority">
                                    <option value="urgent" <?= (($_POST['priority'] ?? '')==='urgent')?'selected':''; ?>>জরুরি</option>
                                    <option value="high" <?= (($_POST['priority'] ?? '')==='high')?'selected':''; ?>>উচ্চ</option>
                                    <option value="medium" <?= (($_POST['priority'] ?? '')==='medium')?'selected':''; ?>>মাধ্যম</option>
                                    <option value="low" <?= (($_POST['priority'] ?? 'low')==='low')?'selected':''; ?>>নিম্ন</option>
                                </select>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="form-label">স্ট্যাটাস</label>
                                <select class="form-select" name="status">
                                    <option value="active" <?= (($_POST['status'] ?? '')==='active' || !isset($_POST['status']))?'selected':''; ?>>Active</option>
                                    <option value="inactive" <?= (($_POST['status'] ?? '')==='inactive')?'selected':''; ?>>Inactive</option>
                                </select>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">প্রকাশের তারিখ</label>
                                <input type="date" class="form-control" name="publish_date" value="<?= htmlspecialchars($_POST['publish_date'] ?? date('Y-m-d')) ?>" required>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">মেয়াদ শেষের তারিখ (ঐচ্ছিক)</label>
                                <input type="date" class="form-control" name="expiry_date" value="<?= htmlspecialchars($_POST['expiry_date'] ?? '') ?>">
                            </div>
                        </div>
                        <button type="submit" name="create_notice" class="btn btn-primary"><i class="fas fa-save"></i> নোটিশ সংরক্ষণ</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
    function toggleClassSelect() {
        const ta = document.getElementById('target_audience').value;
        document.getElementById('class_select_wrapper').style.display = (ta === 'specific_class') ? '' : 'none';
    }
    document.getElementById('target_audience').addEventListener('change', toggleClassSelect);
    toggleClassSelect();
</script>
</body>
</html>