<?php
// coordinator/announcements.php
declare(strict_types=1);

require_once __DIR__ . '/../includes/coordinator_auth.php';

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

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

function can_table_exists(mysqli $db, string $table): bool {
    $safe = $db->real_escape_string($table);
    $res = $db->query("SHOW TABLES LIKE '{$safe}'");
    return $res && $res->num_rows > 0;
}

function can_col_exists(mysqli $db, string $table, string $col): bool {
    $safeTable = preg_replace('/[^a-zA-Z0-9_]/', '', $table);
    $safeCol = $db->real_escape_string($col);
    $res = $db->query("SHOW COLUMNS FROM `{$safeTable}` LIKE '{$safeCol}'");
    return $res && $res->num_rows > 0;
}

function can_first_col(mysqli $db, string $table, array $cols): ?string {
    foreach ($cols as $col) {
        if (can_col_exists($db, $table, $col)) return $col;
    }
    return null;
}

$error = '';
$ok = '';

$table = can_table_exists($db, 'lms_announcements') ? 'lms_announcements' : '';

if ($table === '') {
    $error = 'lms_announcements table not found.';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $table !== '') {
    $title = trim((string)($_POST['title'] ?? ''));
    $body  = trim((string)($_POST['body'] ?? ''));
    $target = trim((string)($_POST['target'] ?? 'all'));

    if ($title === '' || $body === '') {
        $error = 'Please enter title and message.';
    } else {
        $cols = [];
        $vals = [];
        $types = '';

        if (can_col_exists($db, $table, 'title')) {
            $cols[] = 'title';
            $vals[] = $title;
            $types .= 's';
        }

        if (can_col_exists($db, $table, 'body')) {
            $cols[] = 'body';
            $vals[] = $body;
            $types .= 's';
        } elseif (can_col_exists($db, $table, 'message')) {
            $cols[] = 'message';
            $vals[] = $body;
            $types .= 's';
        } elseif (can_col_exists($db, $table, 'content')) {
            $cols[] = 'content';
            $vals[] = $body;
            $types .= 's';
        }

        if (can_col_exists($db, $table, 'target')) {
            $cols[] = 'target';
            $vals[] = $target;
            $types .= 's';
        } elseif (can_col_exists($db, $table, 'audience')) {
            $cols[] = 'audience';
            $vals[] = $target;
            $types .= 's';
        }

        if (can_col_exists($db, $table, 'created_by')) {
            $cols[] = 'created_by';
            $vals[] = (int)($_SESSION['user_id'] ?? 0);
            $types .= 'i';
        }

        if (can_col_exists($db, $table, 'created_at')) {
            $cols[] = 'created_at';
            $vals[] = date('Y-m-d H:i:s');
            $types .= 's';
        }

        if (can_col_exists($db, $table, 'status')) {
            $cols[] = 'status';
            $vals[] = 'active';
            $types .= 's';
        }

        if (!$cols) {
            $error = 'No supported columns found in lms_announcements.';
        } else {
            $placeholders = implode(',', array_fill(0, count($cols), '?'));
            $sql = "INSERT INTO `{$table}` (`" . implode('`,`', $cols) . "`) VALUES ({$placeholders})";
            $stmt = $db->prepare($sql);

            if (!$stmt) {
                $error = 'Announcement SQL error: ' . $db->error;
            } else {
                $stmt->bind_param($types, ...$vals);
                if ($stmt->execute()) {
                    $ok = 'Announcement published successfully.';
                } else {
                    $error = 'Save failed: ' . $stmt->error;
                }
                $stmt->close();
            }
        }
    }
}

$rows = [];

if ($table !== '') {
    $titleCol = can_first_col($db, $table, ['title']);
    $bodyCol = can_first_col($db, $table, ['body', 'message', 'content']);
    $targetCol = can_first_col($db, $table, ['target', 'audience']);
    $statusCol = can_first_col($db, $table, ['status']);
    $createdCol = can_first_col($db, $table, ['created_at', 'date_created', 'created_on']);

    $select = [
        "id",
        $titleCol ? "`{$titleCol}` AS title" : "CONCAT('Announcement #', id) AS title",
        $bodyCol ? "`{$bodyCol}` AS body" : "'' AS body",
        $targetCol ? "`{$targetCol}` AS target" : "'all' AS target",
        $statusCol ? "`{$statusCol}` AS status" : "'active' AS status",
        $createdCol ? "`{$createdCol}` AS created_at" : "NULL AS created_at"
    ];

    $orderCol = $createdCol ? "`{$createdCol}` DESC" : "id DESC";

    $res = $db->query("SELECT " . implode(', ', $select) . " FROM `{$table}` ORDER BY {$orderCol} LIMIT 300");
    if ($res) {
        $rows = $res->fetch_all(MYSQLI_ASSOC);
    }
}

require_once __DIR__ . '/../includes/coordinator_layout_top.php';
?>

<div class="d-flex justify-content-between align-items-start mb-4">
    <div>
        <h1 class="page-title">Announcements</h1>
        <div class="page-subtitle">Create and view ELMS notices</div>
    </div>

    <a href="/elms/coordinator/dashboard.php" class="btn btn-light border rounded-4">
        <i class="bi bi-arrow-left me-1"></i> Dashboard
    </a>
</div>

<?php if ($ok): ?>
    <div class="alert alert-success rounded-4"><?= h($ok) ?></div>
<?php endif; ?>

<?php if ($error): ?>
    <div class="alert alert-warning rounded-4"><strong>Notice:</strong> <?= h($error) ?></div>
<?php endif; ?>

<div class="row g-4">
    <div class="col-lg-5">
        <div class="eden-card p-4">
            <h5 class="fw-bold mb-3">New Announcement</h5>

            <form method="post">
                <div class="mb-3">
                    <label class="form-label fw-semibold">Title</label>
                    <input type="text" name="title" class="form-control rounded-4" required>
                </div>

                <div class="mb-3">
                    <label class="form-label fw-semibold">Target</label>
                    <select name="target" class="form-select rounded-4">
                        <option value="all">All</option>
                        <option value="students">Students</option>
                        <option value="lecturers">Lecturers</option>
                        <option value="coordinators">Coordinators</option>
                    </select>
                </div>

                <div class="mb-3">
                    <label class="form-label fw-semibold">Message</label>
                    <textarea name="body" rows="6" class="form-control rounded-4" required></textarea>
                </div>

                <button type="submit" class="btn btn-eden w-100">
                    <i class="bi bi-megaphone me-1"></i> Publish
                </button>
            </form>
        </div>
    </div>

    <div class="col-lg-7">
        <div class="eden-card overflow-hidden">
            <div class="px-3 py-3 border-bottom bg-white d-flex justify-content-between align-items-center">
                <strong>Recent Announcements</strong>
                <span class="badge text-bg-danger rounded-pill"><?= number_format(count($rows)) ?></span>
            </div>

            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>ID</th>
                            <th>Announcement</th>
                            <th>Target</th>
                            <th>Status</th>
                            <th>Created</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php if (!$rows): ?>
                        <tr><td colspan="5" class="text-center text-muted py-5"><i class="bi bi-inbox fs-2 d-block mb-2"></i>No announcements found.</td></tr>
                    <?php else: foreach ($rows as $r): ?>
                        <?php
                            $status = strtolower((string)($r['status'] ?? 'active'));
                            $badge = in_array($status, ['active', 'published', '1'], true) ? 'text-bg-success' : 'text-bg-secondary';
                        ?>
                        <tr>
                            <td class="text-muted">#<?= (int)$r['id'] ?></td>
                            <td>
                                <div class="fw-bold"><?= h($r['title']) ?></div>
                                <div class="small text-muted text-truncate" style="max-width:360px;"><?= h($r['body']) ?></div>
                            </td>
                            <td><span class="badge text-bg-light border rounded-pill"><?= h(ucwords((string)$r['target'])) ?></span></td>
                            <td><span class="badge <?= h($badge) ?> rounded-pill"><?= h(ucwords($status)) ?></span></td>
                            <td><?= !empty($r['created_at']) ? h(date('Y-m-d H:i', strtotime((string)$r['created_at']))) : '<span class="text-muted">-</span>' ?></td>
                        </tr>
                    <?php endforeach; endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../includes/coordinator_layout_bottom.php'; ?>