<?php
include('includes/auth.php');

$table_name = 'note';
$page = 'note.php';

// Fetch record for update
$resU = null;
if (isset($_GET['update'])) {
    $resU = $db->select($table_name, '*', 'id = :id', '', [':id' => (int) $_GET['update']]);
}

// Handle update
if (isset($_POST['submitU'])) {
    if (!verify_token($_POST['csrf_token'] ?? '')) {
        header("Location: {$page}?status=4");
        exit;
    }
    $updateData = [
        'note_title' => trim($_POST['note_title'] ?? ''),
        'note_content' => trim($_POST['note_content'] ?? ''),
        'start_time' => trim($_POST['start_time'] ?? ''),
        'end_time' => trim($_POST['end_time'] ?? ''),
    ];
    $db->update($table_name, $updateData, 'id = :id', [':id' => (int) $_GET['update']]);
    header("Location: {$page}?status=1");
    exit;
}

// Handle create
if (isset($_POST['submit'])) {
    if (!verify_token($_POST['csrf_token'] ?? '')) {
        header("Location: {$page}?status=4");
        exit;
    }
    $insertData = [
        'note_title' => trim($_POST['note_title'] ?? ''),
        'note_content' => trim($_POST['note_content'] ?? ''),
        'start_time' => trim($_POST['start_time'] ?? ''),
        'end_time' => trim($_POST['end_time'] ?? ''),
        'createdate' => date('Y-m-d H:i:s'),
    ];
    $db->insert($table_name, $insertData);
    header("Location: {$page}?status=1");
    exit;
}

// Handle delete
if (isset($_GET['delete'])) {
    $db->delete($table_name, 'id = :id', [':id' => (int) $_GET['delete']]);
    $db->delete('note_seen', 'note_id = :note_id', [':note_id' => (int) $_GET['delete']]);
    header("Location: {$page}?status=2");
    exit;
}

// Handle reset seen (re-broadcast to all devices)
if (isset($_GET['reset_seen'])) {
    $noteId = (int) $_GET['reset_seen'];
    // Update the createdate to force a new broadcast key for app-side dedup
    $db->update('note', [
        'createdate' => date('Y-m-d H:i:s'),
    ], 'id = :id', [':id' => $noteId]);
    $db->delete('note_seen', 'note_id = :note_id', [':note_id' => $noteId]);
    header("Location: {$page}?status=1");
    exit;
}

// Handle clear ALL seen records
if (isset($_GET['clear_all_seen'])) {
    // Update all announcements' createdate to force new broadcast keys
    $allNotes = $db->select('note', 'id', '', '');
    foreach ($allNotes as $n) {
        $db->update('note', [
            'createdate' => date('Y-m-d H:i:s'),
        ], 'id = :id', [':id' => (int) $n['id']]);
    }
    $db->delete('note_seen');
    header("Location: {$page}?status=1");
    exit;
}

// --- All redirects handled, now output HTML ---
include('includes/header.php');

$res = $db->select($table_name, '*', '', 'createdate DESC');
$csrfToken = generate_token();

// Helper to determine announcement status
function getAnnouncementStatus(array $row): string {
    $now = time();
    $start = !empty($row['start_time']) ? strtotime($row['start_time']) : null;
    $end = !empty($row['end_time']) ? strtotime($row['end_time']) : null;

    if ($start && $now < $start) return 'scheduled';
    if ($end && $now > $end) return 'expired';
    if ($start && (!$end || $now <= $end)) return 'active';
    if (!$start && !$end) return 'active';
    return 'unknown';
}
?>

<?php if (isset($_GET['create'])): ?>
<!-- Create Form -->
<div class="md-card md-card--elevated" style="max-width: 700px; margin: 0 auto;">
    <div class="md-card__header">
        <?= icon('add_circle', 'md-card__header-icon') ?>
        <h2 class="md-card__title">New Announcement</h2>
    </div>
    <div class="md-card__content">
        <form method="post">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken) ?>">
            <div class="md-text-field md-text-field--outlined">
                <input type="text" name="note_title" id="note_title" class="md-text-field__input" placeholder=" " required>
                <label for="note_title" class="md-text-field__label">Title</label>
                <div class="md-text-field__indicator"></div>
            </div>
            <div class="md-text-field md-text-field--outlined md-text-field--textarea">
                <textarea name="note_content" id="note_content" class="md-text-field__input md-text-field__textarea" placeholder=" " rows="5" required></textarea>
                <label for="note_content" class="md-text-field__label">Message Content</label>
                <div class="md-text-field__indicator"></div>
            </div>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                <div class="md-text-field md-text-field--outlined">
                    <input type="datetime-local" name="start_time" id="start_time" class="md-text-field__input" placeholder=" ">
                    <label for="start_time" class="md-text-field__label">Start Time</label>
                    <div class="md-text-field__indicator"></div>
                </div>
                <div class="md-text-field md-text-field--outlined">
                    <input type="datetime-local" name="end_time" id="end_time" class="md-text-field__input" placeholder=" ">
                    <label for="end_time" class="md-text-field__label">End Time</label>
                    <div class="md-text-field__indicator"></div>
                </div>
            </div>
            <p class="md-helper-text" style="margin-top: 0.5rem;">
                Leave times empty for immediate and indefinite delivery. Each device only sees each announcement once.
            </p>
            <div class="md-card__actions">
                <a href="<?= $page ?>" class="md-button md-button--text">Cancel</a>
                <button type="submit" name="submit" class="md-button md-button--filled">
                    <?= icon('check') ?>
                    <span class="md-button__label">Publish</span>
                </button>
            </div>
        </form>
    </div>
</div>

<?php elseif (isset($_GET['update']) && $resU): ?>
<!-- Update Form -->
<div class="md-card md-card--elevated" style="max-width: 700px; margin: 0 auto;">
    <div class="md-card__header">
        <?= icon('edit', 'md-card__header-icon') ?>
        <h2 class="md-card__title">Edit Announcement</h2>
    </div>
    <div class="md-card__content">
        <form method="post">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken) ?>">
            <div class="md-text-field md-text-field--outlined">
                <input type="text" name="note_title" id="note_title" class="md-text-field__input" placeholder=" " required
                       value="<?= htmlspecialchars($resU[0]['note_title'] ?? '') ?>">
                <label for="note_title" class="md-text-field__label">Title</label>
                <div class="md-text-field__indicator"></div>
            </div>
            <div class="md-text-field md-text-field--outlined md-text-field--textarea">
                <textarea name="note_content" id="note_content" class="md-text-field__input md-text-field__textarea" placeholder=" " rows="5" required><?= htmlspecialchars($resU[0]['note_content'] ?? '') ?></textarea>
                <label for="note_content" class="md-text-field__label">Message Content</label>
                <div class="md-text-field__indicator"></div>
            </div>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                <div class="md-text-field md-text-field--outlined">
                    <input type="datetime-local" name="start_time" id="start_time" class="md-text-field__input" placeholder=" "
                           value="<?= htmlspecialchars(!empty($resU[0]['start_time']) ? date('Y-m-d\TH:i', strtotime($resU[0]['start_time'])) : '') ?>">
                    <label for="start_time" class="md-text-field__label">Start Time</label>
                    <div class="md-text-field__indicator"></div>
                </div>
                <div class="md-text-field md-text-field--outlined">
                    <input type="datetime-local" name="end_time" id="end_time" class="md-text-field__input" placeholder=" "
                           value="<?= htmlspecialchars(!empty($resU[0]['end_time']) ? date('Y-m-d\TH:i', strtotime($resU[0]['end_time'])) : '') ?>">
                    <label for="end_time" class="md-text-field__label">End Time</label>
                    <div class="md-text-field__indicator"></div>
                </div>
            </div>
            <div class="md-card__actions">
                <a href="<?= $page ?>" class="md-button md-button--text">Cancel</a>
                <button type="submit" name="submitU" class="md-button md-button--filled">
                    <?= icon('check') ?>
                    <span class="md-button__label">Update</span>
                </button>
            </div>
        </form>
    </div>
</div>

<?php else: ?>
<!-- Announcements List -->
<div class="md-card md-card--elevated">
    <div class="md-card__header">
        <?= icon('campaign', 'md-card__header-icon') ?>
        <h2 class="md-card__title">Announcements</h2>
        <a href="<?= $page ?>?create" class="md-button md-button--filled-tonal md-button--icon-right">
            <?= icon('add') ?>
            <span class="md-button__label">New</span>
        </a>
        <button class="md-button md-button--outlined"
                onclick="if(confirm('Re-send all announcements to all devices?')) window.location='<?= $page ?>?clear_all_seen=1'">
            <?= icon('restart_alt') ?>
            <span class="md-button__label">Reset All Seen</span>
        </button>
    </div>
    <div class="md-card__content md-card__content--table">
        <?php if (empty($res)): ?>
            <div class="md-empty-state">
                <?= icon('campaign', 'md-empty-state__icon') ?>
                <p class="md-empty-state__text">No announcements yet.</p>
            </div>
        <?php else: ?>
        <div class="md-table-container">
            <table class="md-table">
                <thead>
                    <tr>
                        <th>Title</th>
                        <th>Message</th>
                        <th>Window</th>
                        <th>Status</th>
                        <th class="md-table__actions-col">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($res as $row):
                        $status = getAnnouncementStatus($row);
                        $statusClass = match($status) {
                            'active' => 'success',
                            'scheduled' => 'info',
                            'expired' => 'error',
                            default => 'primary',
                        };
                    ?>
                    <tr>
                        <td><strong><?= htmlspecialchars($row['note_title'] ?? '') ?></strong></td>
                        <td><?= htmlspecialchars(substr($row['note_content'] ?? '', 0, 60)) ?><?= strlen($row['note_content'] ?? '') > 60 ? '…' : '' ?></td>
                        <td style="font-size: 0.8rem;">
                            <?php if (!empty($row['start_time'])): ?>
                                <?= htmlspecialchars($row['start_time']) ?><br>→ <?= htmlspecialchars($row['end_time'] ?: 'No end') ?>
                            <?php else: ?>
                                Immediate
                            <?php endif; ?>
                        </td>
                        <td>
                            <span class="md-chip md-chip--<?= $statusClass ?>">
                                <?= $status ?>
                            </span>
                        </td>
                        <td class="md-table__actions">
                            <a href="<?= $page ?>?reset_seen=<?= (int) $row['id'] ?>" class="md-icon-button" title="Re-broadcast to all devices">
                                <?= icon('send') ?>
                            </a>
                            <a href="<?= $page ?>?update=<?= (int) $row['id'] ?>" class="md-icon-button" title="Edit">
                                <?= icon('edit') ?>
                            </a>
                            <button class="md-icon-button md-icon-button--error" title="Delete"
                                    onclick="showDeleteDialog('<?= $page ?>?delete=<?= (int) $row['id'] ?>')">
                                <?= icon('delete') ?>
                            </button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

<?php include('includes/footer.php'); ?>
