<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/admin-auth.php';

$pdo = db();
requireAdmin();

if (isPost()) { requireCsrf(); }

$success = flash('success') ?: '';
$error = '';
$admin = currentAdmin($pdo);
if(isPost()){$action=(string)($_POST['action']??'');try{
 if($action==='delete'){$id=(int)($_POST['delete_id']??0);if(!safeFetch($pdo,'SELECT id FROM core_announcements WHERE id=?',[$id]))throw new RuntimeException('Announcement not found.');mustExecute($pdo,'DELETE FROM core_announcements WHERE id=?',[$id]);logActivity($pdo,'admin',(int)($admin['id']??0),'Announcement deleted','Announcement ID '.$id);flash('success','Announcement deleted.');redirect('admin/announcements.php');}
 if($action==='create'){$title=trim((string)($_POST['title']??''));$message=trim((string)($_POST['message']??''));$type=(string)($_POST['announcement_type']??'general');$priority=(string)($_POST['priority']??'normal');$status=(string)($_POST['status']??'active');$expires=trim((string)($_POST['expires_at']??''));if($title===''||$message==='')throw new RuntimeException('Title and message are required.');if(!in_array($type,['general','exam','urgent'],true)||!in_array($priority,['high','normal','low'],true)||!in_array($status,['active','hidden'],true))throw new RuntimeException('Invalid announcement options.');if($expires!==''){$dt=DateTimeImmutable::createFromFormat('Y-m-d\\TH:i',$expires)?:DateTimeImmutable::createFromFormat('Y-m-d H:i:s',$expires);if(!$dt)throw new RuntimeException('Expiry date is invalid.');$expires=$dt->format('Y-m-d H:i:s');}mustExecute($pdo,'INSERT INTO core_announcements (title,message,announcement_type,priority,status,expires_at,created_at) VALUES (?,?,?,?,?,?,NOW())',[$title,$message,$type,$priority,$status,$expires?:null]);logActivity($pdo,'admin',(int)($admin['id']??0),'Announcement created','Published announcement: '.$title);flash('success','Announcement published.');redirect('admin/announcements.php');}
 }catch(Throwable $e){error_log('[SMI announcements] '.$e->getMessage());$error=APP_DEBUG?$e->getMessage():$e->getMessage();}}

/*
|--------------------------------------------------------------------------
| Announcements
|--------------------------------------------------------------------------
*/

$announcements = [];

if (tableExists($pdo, 'core_announcements')) {

    $stmt = $pdo->query("
        SELECT *
        FROM core_announcements
        ORDER BY id DESC
    ");

    $announcements =
        $stmt->fetchAll();
}

?>

<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="UTF-8">

<meta
name="viewport"
content="width=device-width, initial-scale=1.0">

<title>
Announcements Management
</title>

<link
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap"
rel="stylesheet">

<style>

*{
    margin:0;
    padding:0;
    box-sizing:border-box;
}

body{
    font-family:'Inter',sans-serif;
    background:#f1f5f9;
    color:#0f172a;
}

.page{
    padding:34px;
}

.topbar{
    display:flex;
    justify-content:space-between;
    align-items:center;
    margin-bottom:30px;
}

.page-title{
    font-size:42px;
    font-weight:900;
}

.back-btn{
    background:#dbeafe;
    color:#1d4ed8;
    text-decoration:none;
    padding:14px 20px;
    border-radius:18px;
    font-weight:900;
}

.grid{
    display:grid;
    grid-template-columns:420px 1fr;
    gap:26px;
}

.card{
    background:#fff;
    border-radius:34px;
    padding:30px;
    border:1px solid #e2e8f0;
    box-shadow:0 18px 45px rgba(15,23,42,.05);
}

.card h2{
    font-size:30px;
    margin-bottom:22px;
    font-weight:900;
}

.form-group{
    margin-bottom:18px;
}

.form-group label{
    display:block;
    margin-bottom:10px;
    font-weight:800;
}

.form-control{
    width:100%;
    padding:16px;
    border-radius:18px;
    border:1px solid #cbd5e1;
}

textarea.form-control{
    min-height:180px;
}

.submit-btn{
    width:100%;
    border:none;

    background:
    linear-gradient(
        135deg,
        #f59e0b,
        #ea580c
    );

    color:#fff;

    padding:18px;

    border-radius:20px;

    font-weight:900;

    cursor:pointer;
}

.table-wrap{
    overflow:auto;
}

table{
    width:100%;
    border-collapse:collapse;
}

th{
    background:#f8fafc;

    padding:18px;

    text-align:left;

    font-size:13px;

    text-transform:uppercase;

    color:#64748b;
}

td{
    padding:18px;

    border-top:1px solid #e2e8f0;

    font-size:14px;

    vertical-align:top;
}

.badge{
    display:inline-block;

    padding:8px 12px;

    border-radius:999px;

    font-size:12px;

    font-weight:900;
}

.general{
    background:#dbeafe;
    color:#1d4ed8;
}

.exam{
    background:#fee2e2;
    color:#b91c1c;
}

.urgent{
    background:#fef3c7;
    color:#b45309;
}

.action-btn{
    padding:10px 14px;

    border-radius:14px;

    text-decoration:none;

    font-size:12px;

    font-weight:900;
}

.delete-btn{
    background:#fee2e2;
    color:#b91c1c;
}

.alert{
    padding:18px;

    border-radius:18px;

    margin-bottom:24px;

    font-weight:800;
}

.alert-success{
    background:#dcfce7;
    color:#166534;
}

.alert-danger{
    background:#fee2e2;
    color:#991b1b;
}

.priority-high{
    color:#dc2626;
    font-weight:900;
}

.priority-normal{
    color:#2563eb;
    font-weight:700;
}

.priority-low{
    color:#64748b;
}

@media(max-width:1100px){

    .grid{
        grid-template-columns:1fr;
    }
}

</style>

</head>

<body>

<div class="page">

    <div class="topbar">

        <h1 class="page-title">
            Announcements Management
        </h1>

        <a
        href="dashboard.php"
        class="back-btn">

            ← Dashboard

        </a>

    </div>

    <?php if($success): ?>

        <div class="alert alert-success">

            <?php echo e($success); ?>

        </div>

    <?php endif; ?>

    <?php if($error): ?>

        <div class="alert alert-danger">

            <?php echo e($error); ?>

        </div>

    <?php endif; ?>

    <div class="grid">

        <div class="card">

            <h2>
                Publish Announcement
            </h2>

            <form method="POST">
<input type="hidden" name="action" value="create">
<?php echo csrfField(); ?>

                <div class="form-group">

                    <label>
                        Title
                    </label>

                    <input
                    type="text"
                    name="title"
                    class="form-control"
                    required>

                </div>

                <div class="form-group">

                    <label>
                        Message
                    </label>

                    <textarea
                    name="message"
                    class="form-control"
                    required></textarea>

                </div>

                <div class="form-group">

                    <label>
                        Announcement Type
                    </label>

                    <select
                    name="announcement_type"
                    class="form-control">

                        <option value="general">
                            General
                        </option>

                        <option value="exam">
                            Exam
                        </option>

                        <option value="urgent">
                            Urgent
                        </option>

                    </select>

                </div>

                <div class="form-group">

                    <label>
                        Priority
                    </label>

                    <select
                    name="priority"
                    class="form-control">

                        <option value="high">
                            High
                        </option>

                        <option value="normal">
                            Normal
                        </option>

                        <option value="low">
                            Low
                        </option>

                    </select>

                </div>

                <div class="form-group">

                    <label>
                        Status
                    </label>

                    <select
                    name="status"
                    class="form-control">

                        <option value="active">
                            Active
                        </option>

                        <option value="hidden">
                            Hidden
                        </option>

                    </select>

                </div>

                <div class="form-group">

                    <label>
                        Expiry Date
                    </label>

                    <input
                    type="datetime-local"
                    name="expires_at"
                    class="form-control">

                </div>

                <button
                type="submit"
                class="submit-btn">

                    Publish Announcement

                </button>

            </form>

        </div>

        <div class="card">

            <h2>
                Announcements List
            </h2>

            <div class="table-wrap">

                <table>

                    <thead>

                        <tr>

                            <th>Type</th>
                            <th>Title</th>
                            <th>Message</th>
                            <th>Priority</th>
                            <th>Status</th>
                            <th>Date</th>
                            <th>Action</th>

                        </tr>

                    </thead>

                    <tbody>

                    <?php if($announcements): ?>

                        <?php foreach($announcements as $row): ?>

                            <tr>

                                <td>

                                    <span class="badge <?php echo e($row['announcement_type']); ?>">

                                        <?php
                                        echo e(
                                            ucfirst(
                                                $row['announcement_type']
                                            )
                                        );
                                        ?>

                                    </span>

                                </td>

                                <td>

                                    <strong>

                                        <?php
                                        echo e(
                                            $row['title']
                                        );
                                        ?>

                                    </strong>

                                </td>

                                <td>

                                    <?php
                                    echo nl2br(
                                        e(
                                            $row['message']
                                        )
                                    );
                                    ?>

                                </td>

                                <td>

                                    <span class="priority-<?php echo e($row['priority']); ?>">

                                        <?php
                                        echo e(
                                            ucfirst(
                                                $row['priority']
                                            )
                                        );
                                        ?>

                                    </span>

                                </td>

                                <td>

                                    <?php
                                    echo e(
                                        ucfirst(
                                            $row['status']
                                        )
                                    );
                                    ?>

                                </td>

                                <td>

                                    <?php
                                    echo e(
                                        $row['created_at']
                                    );
                                    ?>

                                </td>

                                <td>

                                    <form method="post" style="display:inline" onsubmit="return confirm('Delete this announcement?')">
<?php echo csrfField(); ?>
<input type="hidden" name="action" value="delete">
<input type="hidden" name="delete_id" value="<?php echo e((string)$row['id']); ?>">
<button type="submit" class="action-btn delete-btn">Delete</button>
</form>

                                </td>

                            </tr>

                        <?php endforeach; ?>

                    <?php else: ?>

                        <tr>

                            <td colspan="7">

                                No announcements found.

                            </td>

                        </tr>

                    <?php endif; ?>

                    </tbody>

                </table>

            </div>

        </div>

    </div>

</div>

</body>
</html>