<?php
// /elms/admin/announcements/student_notices.php
declare(strict_types=1);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

define('APP_ROOT', dirname(__DIR__, 2));

$PAGE_TITLE = 'Student Notices';
$ACTIVE = 'student_notices';

require_once APP_ROOT . '/includes/admin_auth.php';
require_once APP_ROOT . '/includes/db.php';

$mysqli = $mysqli ?? ($conn ?? null);
if (!$mysqli instanceof mysqli) {
    http_response_code(500);
    exit('Database connection failed.');
}
$mysqli->set_charset('utf8mb4');

if (!function_exists('h')) {
    function h($v): string {
        return htmlspecialchars((string)$v, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }
}

function sn_col_exists(mysqli $db, string $table, string $col): bool {
    $st = $db->prepare("
        SELECT COUNT(*) c
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = ?
          AND COLUMN_NAME = ?
    ");
    $st->bind_param('ss', $table, $col);
    $st->execute();
    $c = (int)($st->get_result()->fetch_assoc()['c'] ?? 0);
    $st->close();
    return $c > 0;
}

function sn_dt(?string $v): ?string {
    $v = trim((string)$v);
    if ($v === '') return null;
    $t = strtotime($v);
    return $t ? date('Y-m-d H:i:s', $t) : null;
}

function sn_upload_notice_image(): ?string {
    if (empty($_FILES['image']['name'])) {
        return null;
    }

    $uploadDir = APP_ROOT . '/uploads/notices/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }

    $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
    $allowed = ['jpg', 'jpeg', 'png', 'webp'];

    if (!in_array($ext, $allowed, true)) {
        return null;
    }

    $fileName = 'notice_' . time() . '_' . random_int(1000, 9999) . '.' . $ext;

    if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadDir . $fileName)) {
        return '/elms/uploads/notices/' . $fileName;
    }

    return null;
}

$mysqli->query("
CREATE TABLE IF NOT EXISTS lms_student_notices (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    message TEXT NULL,
    image_path VARCHAR(255) NULL,
    button_text VARCHAR(100) NULL,
    button_url VARCHAR(255) NULL,
    status ENUM('active','inactive') DEFAULT 'active',
    sort_order INT DEFAULT 0,
    starts_at DATETIME NULL,
    ends_at DATETIME NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
");

$cols = [
    'image_path'  => "ALTER TABLE lms_student_notices ADD COLUMN image_path VARCHAR(255) NULL",
    'button_text' => "ALTER TABLE lms_student_notices ADD COLUMN button_text VARCHAR(100) NULL",
    'button_url'  => "ALTER TABLE lms_student_notices ADD COLUMN button_url VARCHAR(255) NULL",
    'status'      => "ALTER TABLE lms_student_notices ADD COLUMN status ENUM('active','inactive') DEFAULT 'active'",
    'sort_order'  => "ALTER TABLE lms_student_notices ADD COLUMN sort_order INT DEFAULT 0",
    'starts_at'   => "ALTER TABLE lms_student_notices ADD COLUMN starts_at DATETIME NULL",
    'ends_at'     => "ALTER TABLE lms_student_notices ADD COLUMN ends_at DATETIME NULL",
    'created_at'  => "ALTER TABLE lms_student_notices ADD COLUMN created_at DATETIME DEFAULT CURRENT_TIMESTAMP",
];

foreach ($cols as $col => $sql) {
    if (!sn_col_exists($mysqli, 'lms_student_notices', $col)) {
        $mysqli->query($sql);
    }
}

$msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'create') {
        $title = trim((string)($_POST['title'] ?? ''));

        if ($title === '') {
            $msg = '<div class="alert alert-danger rounded-4 border-0">Title is required.</div>';
        } else {
            $message = trim((string)($_POST['message'] ?? ''));
            $buttonText = trim((string)($_POST['button_text'] ?? ''));
            $buttonUrl = trim((string)($_POST['button_url'] ?? ''));
            $status = ($_POST['status'] ?? '') === 'inactive' ? 'inactive' : 'active';
            $sortOrder = (int)($_POST['sort_order'] ?? 0);
            $startsAt = sn_dt($_POST['starts_at'] ?? '');
            $endsAt = sn_dt($_POST['ends_at'] ?? '');
            $imagePath = sn_upload_notice_image();

            $st = $mysqli->prepare("
                INSERT INTO lms_student_notices
                (title, message, image_path, button_text, button_url, status, sort_order, starts_at, ends_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $st->bind_param(
                'ssssssiss',
                $title,
                $message,
                $imagePath,
                $buttonText,
                $buttonUrl,
                $status,
                $sortOrder,
                $startsAt,
                $endsAt
            );
            $st->execute();
            $st->close();

            $msg = '<div class="alert alert-success rounded-4 border-0">Student notice added successfully.</div>';
        }
    }

    if ($action === 'update') {
        $id = (int)($_POST['id'] ?? 0);
        $title = trim((string)($_POST['title'] ?? ''));

        if ($id <= 0 || $title === '') {
            $msg = '<div class="alert alert-danger rounded-4 border-0">Title is required.</div>';
        } else {
            $message = trim((string)($_POST['message'] ?? ''));
            $buttonText = trim((string)($_POST['button_text'] ?? ''));
            $buttonUrl = trim((string)($_POST['button_url'] ?? ''));
            $status = ($_POST['status'] ?? '') === 'inactive' ? 'inactive' : 'active';
            $sortOrder = (int)($_POST['sort_order'] ?? 0);
            $startsAt = sn_dt($_POST['starts_at'] ?? '');
            $endsAt = sn_dt($_POST['ends_at'] ?? '');

            $imagePath = trim((string)($_POST['current_image'] ?? ''));
            $newImage = sn_upload_notice_image();
            if ($newImage !== null) {
                $imagePath = $newImage;
            }
            $imagePath = $imagePath !== '' ? $imagePath : null;

            $st = $mysqli->prepare("
                UPDATE lms_student_notices
                SET title = ?,
                    message = ?,
                    image_path = ?,
                    button_text = ?,
                    button_url = ?,
                    status = ?,
                    sort_order = ?,
                    starts_at = ?,
                    ends_at = ?
                WHERE id = ?
                LIMIT 1
            ");
            $st->bind_param(
                'ssssssissi',
                $title,
                $message,
                $imagePath,
                $buttonText,
                $buttonUrl,
                $status,
                $sortOrder,
                $startsAt,
                $endsAt,
                $id
            );
            $st->execute();
            $st->close();

            $msg = '<div class="alert alert-success rounded-4 border-0">Notice updated successfully.</div>';
        }
    }

    if ($action === 'toggle') {
        $id = (int)($_POST['id'] ?? 0);
        $newStatus = ($_POST['status'] ?? '') === 'active' ? 'active' : 'inactive';

        if ($id > 0) {
            $st = $mysqli->prepare("UPDATE lms_student_notices SET status=? WHERE id=? LIMIT 1");
            $st->bind_param('si', $newStatus, $id);
            $st->execute();
            $st->close();

            $msg = '<div class="alert alert-success rounded-4 border-0">Status updated.</div>';
        }
    }

    if ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);

        if ($id > 0) {
            $st = $mysqli->prepare("DELETE FROM lms_student_notices WHERE id=? LIMIT 1");
            $st->bind_param('i', $id);
            $st->execute();
            $st->close();

            $msg = '<div class="alert alert-warning rounded-4 border-0">Notice deleted.</div>';
        }
    }
}

$rows = [];
$res = $mysqli->query("SELECT * FROM lms_student_notices ORDER BY sort_order ASC, id DESC");
while ($res && $r = $res->fetch_assoc()) {
    $rows[] = $r;
}

require_once APP_ROOT . '/includes/admin_layout_top.php';
?>

<style>
.notice-card{
    background:#fff;
    border:1px solid #e5e7eb;
    border-radius:18px;
    box-shadow:0 8px 24px rgba(15,23,42,.055);
    overflow:hidden;
}
.notice-card-head{
    padding:18px 20px;
    border-bottom:1px solid #e5e7eb;
}
.notice-preview-img{
    width:140px;
    height:76px;
    object-fit:cover;
    border-radius:12px;
    border:1px solid #e5e7eb;
}
.notice-title{
    font-weight:900;
    color:#111827;
}
.notice-text{
    color:#64748b;
    font-size:13px;
    max-width:520px;
    white-space:pre-wrap;
}
.notice-actions{
    display:flex;
    gap:8px;
    justify-content:flex-end;
    flex-wrap:wrap;
}
.notice-actions form{
    margin:0;
}
</style>

<?= $msg ?>

<div class="notice-card mb-4">
    <div class="notice-card-head">
        <h5 class="mb-1 fw-bold">Add Student Dashboard Notice</h5>
        <div class="text-muted small">This will show on student dashboard only when active.</div>
    </div>

    <div class="p-4">
        <form method="post" enctype="multipart/form-data" class="row g-3">
            <input type="hidden" name="action" value="create">

            <div class="col-lg-6">
                <label class="form-label fw-semibold">Title</label>
                <input name="title" class="form-control" required>
            </div>

            <div class="col-lg-6">
                <label class="form-label fw-semibold">Image</label>
                <input type="file" name="image" class="form-control" accept="image/*">
            </div>

            <div class="col-12">
                <label class="form-label fw-semibold">Message</label>
                <textarea name="message" class="form-control" rows="3"></textarea>
            </div>

            <div class="col-lg-4">
                <label class="form-label fw-semibold">Button Text</label>
                <input name="button_text" class="form-control" placeholder="View More">
            </div>

            <div class="col-lg-4">
                <label class="form-label fw-semibold">Button URL</label>
                <input name="button_url" class="form-control" placeholder="/elms/student/modules.php">
            </div>

            <div class="col-lg-2">
                <label class="form-label fw-semibold">Status</label>
                <select name="status" class="form-select">
                    <option value="active">Active</option>
                    <option value="inactive">Inactive</option>
                </select>
            </div>

            <div class="col-lg-2">
                <label class="form-label fw-semibold">Sort</label>
                <input type="number" name="sort_order" class="form-control" value="0">
            </div>

            <div class="col-lg-4">
                <label class="form-label fw-semibold">Starts At</label>
                <input type="datetime-local" name="starts_at" class="form-control">
            </div>

            <div class="col-lg-4">
                <label class="form-label fw-semibold">Ends At</label>
                <input type="datetime-local" name="ends_at" class="form-control">
            </div>

            <div class="col-lg-4 d-flex align-items-end">
                <button type="submit" class="btn btn-admin-primary w-100">
                    <i class="bi bi-plus-circle me-1"></i>
                    Add Notice
                </button>
            </div>
        </form>
    </div>
</div>

<div class="notice-card">
    <div class="notice-card-head">
        <h5 class="mb-1 fw-bold">Student Notices</h5>
        <div class="text-muted small">Manage dashboard notices.</div>
    </div>

    <div class="table-responsive">
        <table class="table align-middle mb-0">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Image</th>
                    <th>Notice</th>
                    <th>Status</th>
                    <th>Sort</th>
                    <th>Dates</th>
                    <th class="text-end">Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php if (!$rows): ?>
                <tr>
                    <td colspan="7" class="text-center text-muted py-4">No notices added yet.</td>
                </tr>
            <?php else: ?>
                <?php foreach ($rows as $r): ?>
                    <tr>
                        <td><?= (int)$r['id'] ?></td>

                        <td>
                            <?php if (!empty($r['image_path'])): ?>
                                <img src="<?= h($r['image_path']) ?>" class="notice-preview-img" alt="">
                            <?php else: ?>
                                <span class="text-muted">No image</span>
                            <?php endif; ?>
                        </td>

                        <td>
                            <div class="notice-title"><?= h($r['title'] ?? '') ?></div>

                            <?php if (!empty($r['message'])): ?>
                                <div class="notice-text"><?= h($r['message']) ?></div>
                            <?php endif; ?>

                            <?php if (!empty($r['button_text']) || !empty($r['button_url'])): ?>
                                <div class="small text-muted mt-1">
                                    Button: <?= h($r['button_text'] ?? '') ?>
                                    <?= !empty($r['button_url']) ? ' → ' . h($r['button_url']) : '' ?>
                                </div>
                            <?php endif; ?>
                        </td>

                        <td>
                            <span class="badge <?= ($r['status'] ?? '') === 'active' ? 'bg-success' : 'bg-secondary' ?>">
                                <?= h($r['status'] ?? 'inactive') ?>
                            </span>
                        </td>

                        <td><?= (int)($r['sort_order'] ?? 0) ?></td>

                        <td class="small text-muted">
                            <?= h($r['starts_at'] ?: 'Anytime') ?><br>
                            <?= h($r['ends_at'] ?: 'No end') ?>
                        </td>

                        <td class="text-end">
                            <div class="notice-actions">
                                <button type="button"
                                        class="btn btn-sm btn-outline-dark rounded-pill"
                                        data-bs-toggle="modal"
                                        data-bs-target="#editNoticeModal<?= (int)$r['id'] ?>">
                                    Edit
                                </button>

                                <form method="post">
                                    <input type="hidden" name="action" value="toggle">
                                    <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                                    <input type="hidden" name="status" value="<?= ($r['status'] ?? '') === 'active' ? 'inactive' : 'active' ?>">
                                    <button type="submit" class="btn btn-sm btn-outline-primary rounded-pill">
                                        <?= ($r['status'] ?? '') === 'active' ? 'Deactivate' : 'Activate' ?>
                                    </button>
                                </form>

                                <form method="post" onsubmit="return confirm('Delete this notice?')">
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                                    <button type="submit" class="btn btn-sm btn-outline-danger rounded-pill">Delete</button>
                                </form>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php foreach ($rows as $r): ?>
<div class="modal fade" id="editNoticeModal<?= (int)$r['id'] ?>" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content rounded-4 border-0">
            <form method="post" enctype="multipart/form-data">
                <input type="hidden" name="action" value="update">
                <input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                <input type="hidden" name="current_image" value="<?= h($r['image_path'] ?? '') ?>">

                <div class="modal-header border-0">
                    <h5 class="modal-title fw-bold">Edit Notice #<?= (int)$r['id'] ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>

                <div class="modal-body row g-3">
                    <div class="col-lg-6">
                        <label class="form-label fw-semibold">Title</label>
                        <input name="title" class="form-control" value="<?= h($r['title'] ?? '') ?>" required>
                    </div>

                    <div class="col-lg-6">
                        <label class="form-label fw-semibold">Change Image</label>
                        <input type="file" name="image" class="form-control" accept="image/*">
                    </div>

                    <?php if (!empty($r['image_path'])): ?>
                        <div class="col-12">
                            <label class="form-label fw-semibold">Current Image</label><br>
                            <img src="<?= h($r['image_path']) ?>" class="notice-preview-img" alt="">
                        </div>
                    <?php endif; ?>

                    <div class="col-12">
                        <label class="form-label fw-semibold">Message</label>
                        <textarea name="message" class="form-control" rows="3"><?= h($r['message'] ?? '') ?></textarea>
                    </div>

                    <div class="col-lg-4">
                        <label class="form-label fw-semibold">Button Text</label>
                        <input name="button_text" class="form-control" value="<?= h($r['button_text'] ?? '') ?>">
                    </div>

                    <div class="col-lg-4">
                        <label class="form-label fw-semibold">Button URL</label>
                        <input name="button_url" class="form-control" value="<?= h($r['button_url'] ?? '') ?>">
                    </div>

                    <div class="col-lg-2">
                        <label class="form-label fw-semibold">Status</label>
                        <select name="status" class="form-select">
                            <option value="active" <?= ($r['status'] ?? '') === 'active' ? 'selected' : '' ?>>Active</option>
                            <option value="inactive" <?= ($r['status'] ?? '') === 'inactive' ? 'selected' : '' ?>>Inactive</option>
                        </select>
                    </div>

                    <div class="col-lg-2">
                        <label class="form-label fw-semibold">Sort</label>
                        <input type="number" name="sort_order" class="form-control" value="<?= (int)($r['sort_order'] ?? 0) ?>">
                    </div>

                    <div class="col-lg-6">
                        <label class="form-label fw-semibold">Starts At</label>
                        <input type="datetime-local"
                               name="starts_at"
                               class="form-control"
                               value="<?= !empty($r['starts_at']) ? h(date('Y-m-d\TH:i', strtotime($r['starts_at']))) : '' ?>">
                    </div>

                    <div class="col-lg-6">
                        <label class="form-label fw-semibold">Ends At</label>
                        <input type="datetime-local"
                               name="ends_at"
                               class="form-control"
                               value="<?= !empty($r['ends_at']) ? h(date('Y-m-d\TH:i', strtotime($r['ends_at']))) : '' ?>">
                    </div>
                </div>

                <div class="modal-footer border-0">
                    <button type="button" class="btn btn-light rounded-pill" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-admin-primary rounded-pill">
                        Update Notice
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php endforeach; ?>

<?php require_once APP_ROOT . '/includes/admin_layout_bottom.php'; ?>