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

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

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id <= 0) { header('Location: index.php'); exit(); }

// Load classes
$classes = $pdo->query("SELECT id, name, section FROM classes WHERE status='active' ORDER BY name, section")->fetchAll(PDO::FETCH_ASSOC);

// Load notice
$stmt = $pdo->prepare("SELECT * FROM notices WHERE id = ?");
$stmt->execute([$id]);
$notice = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$notice) { header('Location: index.php'); exit(); }

// Load attachments
$stmt = $pdo->prepare("SELECT * FROM notices_attachments WHERE notice_id = ? ORDER BY id DESC");
$stmt->execute([$id]);
$attachments = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_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("UPDATE notices SET title=?, content=?, target_audience=?, class_id=?, publish_date=?, expiry_date=?, priority=?, status=? WHERE id=?");
            $stmt->execute([$title,$content,$target_audience,$class_id,$publish_date,$expiry_date,$priority,$status,$id]);

            // New attachments (optional)
            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; }
                    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;
                        $stmtA = $pdo->prepare("INSERT INTO notices_attachments (notice_id, file_path, original_name, mime_type, file_size, uploaded_by) VALUES (?, ?, ?, ?, ?, ?)");
                        $stmtA->execute([$id, $relPath, $orig, $type, $size, $_SESSION['user_id']]);
                    }
                }
            }

            $pdo->commit();
            $success_message = 'নোটিশ আপডেট হয়েছে';
            // Reload data
            $stmt = $pdo->prepare("SELECT * FROM notices WHERE id = ?");
            $stmt->execute([$id]);
            $notice = $stmt->fetch(PDO::FETCH_ASSOC);
            $stmt = $pdo->prepare("SELECT * FROM notices_attachments WHERE notice_id = ? ORDER BY id DESC");
            $stmt->execute([$id]);
            $attachments = $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (Exception $e) {
            if ($pdo->inTransaction()) { $pdo->rollBack(); }
            $error_message = 'আপডেট ব্যর্থ: ' . $e->getMessage();
        }
    }
}

// Delete attachment
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_attachment'])) {
    $attId = (int)($_POST['att_id'] ?? 0);
    if ($attId>0) {
        try {
            $stmt = $pdo->prepare("SELECT file_path FROM notices_attachments WHERE id=? AND notice_id=?");
            $stmt->execute([$attId,$id]);
            $fp = $stmt->fetchColumn();
            $stmt = $pdo->prepare("DELETE FROM notices_attachments WHERE id=? AND notice_id=?");
            $stmt->execute([$attId,$id]);
            if ($fp) { @unlink(dirname(__DIR__) . DIRECTORY_SEPARATOR . $fp); }
            $success_message = 'অ্যাটাচমেন্ট ডিলিট হয়েছে';
        } catch (Exception $e) { $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="../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-10 mx-auto">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5><i class="fas fa-edit"></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"><?=$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"><?=$error_message?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

                    <form method="POST" enctype="multipart/form-data">
                        <div class="mb-3">
                            <label class="form-label">শিরোনাম</label>
                            <input type="text" class="form-control" name="title" value="<?=htmlspecialchars($notice['title'])?>" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">বিবরণ</label>
                            <textarea class="form-control" name="content" rows="6" required><?=htmlspecialchars($notice['content'])?></textarea>
                        </div>
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label class="form-label">লক্ষ্য দর্শক</label>
                                <select class="form-select" name="target_audience">
                                    <?php $ta=$notice['target_audience']; ?>
                                    <option value="all" <?=$ta==='all'?'selected':''?>>সবার জন্য</option>
                                    <option value="students" <?=$ta==='students'?'selected':''?>>ছাত্র-ছাত্রী</option>
                                    <option value="teachers" <?=$ta==='teachers'?'selected':''?>>শিক্ষক</option>
                                    <option value="parents" <?=$ta==='parents'?'selected':''?>>অভিভাবক</option>
                                    <option value="specific_class" <?=$ta==='specific_class'?'selected':''?>>নির্দিষ্ট ক্লাস</option>
                                </select>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label class="form-label">ক্লাস (যদি নির্দিষ্ট ক্লাস)</label>
                                <select class="form-select" name="class_id">
                                    <option value="">নির্বাচন করুন</option>
                                    <?php foreach ($classes as $c): ?>
                                        <option value="<?=$c['id']?>" <?=((int)$notice['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>
                                <?php $pr=$notice['priority']; ?>
                                <select class="form-select" name="priority">
                                    <option value="urgent" <?=$pr==='urgent'?'selected':''?>>জরুরি</option>
                                    <option value="high" <?=$pr==='high'?'selected':''?>>উচ্চ</option>
                                    <option value="medium" <?=$pr==='medium'?'selected':''?>>মাধ্যম</option>
                                    <option value="low" <?=$pr==='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" <?=$notice['status']==='active'?'selected':''?>>Active</option>
                                    <option value="inactive" <?=$notice['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($notice['publish_date'])?>" 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($notice['expiry_date'])?>">
                            </div>
                        </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">
                        </div>
                        <button type="submit" name="update_notice" class="btn btn-primary"><i class="fas fa-save"></i> আপডেট</button>
                    </form>

                    <hr>
                    <h6><i class="fas fa-paperclip"></i> বিদ্যমান অ্যাটাচমেন্ট</h6>
                    <div class="table-responsive">
                        <table class="table table-sm">
                            <thead><tr><th>ফাইল</th><th>টাইপ</th><th>সাইজ</th><th class="text-end">অ্যাকশন</th></tr></thead>
                            <tbody>
                                <?php if (empty($attachments)): ?>
                                <tr><td colspan="4" class="text-muted text-center">কোন অ্যাটাচমেন্ট নেই</td></tr>
                                <?php else: foreach ($attachments as $att): ?>
                                <tr>
                                    <td><a href="../<?=$att['file_path']?>" target="_blank"><?=htmlspecialchars($att['original_name'])?></a></td>
                                    <td><?=htmlspecialchars($att['mime_type'])?></td>
                                    <td><?= number_format((int)$att['file_size']/1024,1) ?> KB</td>
                                    <td class="text-end">
                                        <form method="POST" onsubmit="return confirm('ডিলিট করবেন?');" style="display:inline-block;">
                                            <input type="hidden" name="att_id" value="<?=$att['id']?>">
                                            <button type="submit" name="delete_attachment" class="btn btn-sm btn-danger">
                                                <i class="fas fa-trash"></i> ডিলিট
                                            </button>
                                        </form>
                                    </td>
                                </tr>
                                <?php endforeach; endif; ?>
                            </tbody>
                        </table>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>