<?php
require_once "config.php";

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

date_default_timezone_set("Asia/Dhaka");

if (!isset($conn) || !($conn instanceof mysqli)) {
    die("Database connection not available.");
}
$conn->set_charset("utf8mb4");

if (empty($_SESSION['auth_logged_in'])) {
    header("Location: admin_login.php");
    exit;
}

$username = (string)($_SESSION['auth_username'] ?? '');
$role = (string)($_SESSION['auth_role'] ?? '');

$can_send_notification = false;

if ($role === 'admin') {
    $can_send_notification = true;
} elseif ($role === 'permission') {
    $sql = "SELECT notification_send FROM `Zabbar_Admin_Permission` WHERE username = ? LIMIT 1";
    $stmt = $conn->prepare($sql);
    if ($stmt) {
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $res = $stmt->get_result();
        if ($row = $res->fetch_assoc()) {
            $can_send_notification = (strtolower(trim((string)($row['notification_send'] ?? ''))) === 'yes');
        }
        $stmt->close();
    }
}

function e($value): string {
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function base64url_encode($data): string {
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

function getAccessToken(string $jsonFilePath) {
    $credentials = json_decode(@file_get_contents($jsonFilePath), true);
    if (!$credentials || empty($credentials['private_key']) || empty($credentials['client_email'])) {
        return false;
    }

    $clientEmail = $credentials['client_email'];
    $privateKey  = $credentials['private_key'];

    $header = json_encode(['alg' => 'RS256', 'typ' => 'JWT'], JSON_UNESCAPED_SLASHES);
    $now = time();
    $payload = json_encode([
        'iss'   => $clientEmail,
        'scope' => 'https://www.googleapis.com/auth/cloud-platform',
        'aud'   => 'https://oauth2.googleapis.com/token',
        'exp'   => $now + 3600,
        'iat'   => $now
    ], JSON_UNESCAPED_SLASHES);

    $unsignedJwt = base64url_encode($header) . "." . base64url_encode($payload);
    $signature = '';
    openssl_sign($unsignedJwt, $signature, $privateKey, OPENSSL_ALGO_SHA256);
    $jwt = $unsignedJwt . "." . base64url_encode($signature);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://oauth2.googleapis.com/token');
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
        'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
        'assertion' => $jwt
    ]));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);
    curl_close($ch);

    $responseData = json_decode((string)$response, true);
    return $responseData['access_token'] ?? false;
}

function sendFCMToToken(string $token, string $title, string $body, string $image = ''): bool {
    $serviceAccountFile = 'noti.json';
    if (empty($token) || !file_exists($serviceAccountFile)) return false;

    $accessToken = getAccessToken($serviceAccountFile);
    if (!$accessToken) return false;

    $credentials = json_decode(file_get_contents($serviceAccountFile), true);
    if (!$credentials || empty($credentials['project_id'])) return false;

    $url = "https://fcm.googleapis.com/v1/projects/" . $credentials['project_id'] . "/messages:send";

    $messagePayload = [
        "message" => [
            "token" => $token,
            "data" => [
                "title" => $title,
                "body"  => $body,
                "image" => $image,
                "extra" => ""
            ]
        ]
    ];

    $postData = json_encode($messagePayload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $accessToken,
        'Content-Type: application/json; charset=UTF-8'
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $result = curl_exec($ch);
    $httpCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return $httpCode === 200;
}

$message = '';

if (isset($_GET['del_id'], $_GET['type']) && $can_send_notification) {
    $d_id = (int)$_GET['del_id'];
    $d_type = (string)$_GET['type'];

    if ($d_id > 0) {
        if ($d_type === 'all') {
            $stmt = $conn->prepare("DELETE FROM announcements WHERE id = ?");
            if ($stmt) {
                $stmt->bind_param("i", $d_id);
                $stmt->execute();
                $stmt->close();
            }
        } elseif ($d_type === 'user') {
            $stmt = $conn->prepare("DELETE FROM user_announcements WHERE id = ?");
            if ($stmt) {
                $stmt->bind_param("i", $d_id);
                $stmt->execute();
                $stmt->close();
            }
        }
    }

    header("Location: " . strtok($_SERVER["REQUEST_URI"], '?'));
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $can_send_notification) {
    $title = trim($_POST['title'] ?? '');
    $body = trim($_POST['body'] ?? '');
    $image_link = trim($_POST['image_link'] ?? '');
    $target_type = ($_POST['target_type'] ?? 'all') === 'user' ? 'user' : 'all';
    $identifier = trim($_POST['identifier'] ?? '');
    $show_image = isset($_POST['show_image']);

    $update_id = (int)($_POST['update_id'] ?? 0);
    $update_type = ($_POST['update_type'] ?? 'all') === 'user' ? 'user' : 'all';

    if ($update_id > 0) {
        if ($title === '' || $body === '') {
            $message = "<div class='alert error'>Announcement title and message are required.</div>";
        } else {
            if ($update_type === 'all') {
                $stmt = $conn->prepare("UPDATE announcements SET title=?, message=?, image_link=? WHERE id=?");
                if ($stmt) {
                    $stmt->bind_param("sssi", $title, $body, $image_link, $update_id);
                    $stmt->execute();
                    $stmt->close();
                    $message = "<div class='alert success'>Announcement updated successfully.</div>";
                } else {
                    $message = "<div class='alert error'>Failed to prepare update query.</div>";
                }
            } else {
                $stmt = $conn->prepare("UPDATE user_announcements SET email=?, title=?, message=?, image_link=? WHERE id=?");
                if ($stmt) {
                    $stmt->bind_param("ssssi", $identifier, $title, $body, $image_link, $update_id);
                    $stmt->execute();
                    $stmt->close();
                    $message = "<div class='alert success'>Announcement updated successfully.</div>";
                } else {
                    $message = "<div class='alert error'>Failed to prepare update query.</div>";
                }
            }
        }
    } else {
        if ($title === '' || $body === '') {
            $message = "<div class='alert error'>Announcement title and message are required.</div>";
        } elseif ($target_type === 'user' && $identifier === '') {
            $message = "<div class='alert error'>Username or email is required.</div>";
        } else {
            $serviceAccountFile = 'noti.json';
            if (!file_exists($serviceAccountFile)) {
                $message = "<div class='alert error'>noti.json file not found.</div>";
            } else {
                $user_email = '';
                $fcm_token = '';
                $user_found = true;

                if ($target_type === 'user') {
                    $u_sql = "SELECT email, fcm_key FROM users WHERE username = ? OR email = ? LIMIT 1";
                    $u_stmt = $conn->prepare($u_sql);
                    if ($u_stmt) {
                        $u_stmt->bind_param("ss", $identifier, $identifier);
                        $u_stmt->execute();
                        $u_res = $u_stmt->get_result();
                        if ($u_row = $u_res->fetch_assoc()) {
                            $user_email = (string)($u_row['email'] ?? '');
                            $fcm_token = (string)($u_row['fcm_key'] ?? '');
                        } else {
                            $user_found = false;
                        }
                        $u_stmt->close();
                    } else {
                        $user_found = false;
                    }
                }

                if (!$user_found) {
                    $message = "<div class='alert error'>User not found with the provided username or email.</div>";
                } else {
                    $accessToken = getAccessToken($serviceAccountFile);
                    if (!$accessToken) {
                        $message = "<div class='alert error'>Failed to generate access token from Google.</div>";
                    } else {
                        $credentials = json_decode(file_get_contents($serviceAccountFile), true);
                        $projectId = $credentials['project_id'] ?? '';
                        if ($projectId === '') {
                            $message = "<div class='alert error'>Invalid service account file.</div>";
                        } else {
                            $url = "https://fcm.googleapis.com/v1/projects/" . $projectId . "/messages:send";
                            $fcm_image = ($show_image && $image_link !== '') ? $image_link : '';

                            $messagePayload = [
                                "message" => [
                                    "data" => [
                                        "title" => $title,
                                        "body" => $body,
                                        "image" => $fcm_image,
                                        "extra" => ""
                                    ]
                                ]
                            ];

                            if ($target_type === 'all') {
                                $messagePayload["message"]["topic"] = "ttt";
                            } else {
                                $messagePayload["message"]["token"] = $fcm_token;
                            }

                            $postData = json_encode($messagePayload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

                            $ch = curl_init();
                            curl_setopt($ch, CURLOPT_URL, $url);
                            curl_setopt($ch, CURLOPT_POST, true);
                            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                                'Authorization: Bearer ' . $accessToken,
                                'Content-Type: application/json; charset=UTF-8'
                            ]);
                            curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
                            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                            $result = curl_exec($ch);
                            $httpCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
                            curl_close($ch);

                            if ($httpCode === 200) {
                                $announce_date = date('Y-m-d');
                                $announce_time = date('H:i:s');

                                if ($target_type === 'all') {
                                    $ins_sql = "INSERT INTO announcements (title, image_link, message, announce_date, announce_time) VALUES (?, ?, ?, ?, ?)";
                                    $ins_stmt = $conn->prepare($ins_sql);
                                    if ($ins_stmt) {
                                        $ins_stmt->bind_param("sssss", $title, $image_link, $body, $announce_date, $announce_time);
                                        $ins_stmt->execute();
                                        $ins_stmt->close();
                                    }
                                } else {
                                    $ins_sql = "INSERT INTO user_announcements (email, title, image_link, message, announce_date, announce_time) VALUES (?, ?, ?, ?, ?, ?)";
                                    $ins_stmt = $conn->prepare($ins_sql);
                                    if ($ins_stmt) {
                                        $ins_stmt->bind_param("ssssss", $user_email, $title, $image_link, $body, $announce_date, $announce_time);
                                        $ins_stmt->execute();
                                        $ins_stmt->close();
                                    }
                                }

                                $message = "<div class='alert success'>Announcement sent and saved successfully.</div>";
                            } else {
                                $err = json_decode((string)$result, true);
                                $errMsg = $err['error']['message'] ?? 'Unknown API error';
                                $message = "<div class='alert error'>Error: " . e($errMsg) . "</div>";
                            }
                        }
                    }
                }
            }
        }
    }
}

$edit_title = '';
$edit_message = '';
$edit_image = '';
$edit_target = 'all';
$edit_identifier = '';
$update_id = 0;
$update_type = 'all';

if (isset($_GET['edit_id'], $_GET['type']) && $can_send_notification) {
    $update_id = (int)$_GET['edit_id'];
    $update_type = ($_GET['type'] === 'user') ? 'user' : 'all';

    if ($update_type === 'all') {
        $stmt = $conn->prepare("SELECT * FROM announcements WHERE id = ? LIMIT 1");
        if ($stmt) {
            $stmt->bind_param("i", $update_id);
            $stmt->execute();
            $q = $stmt->get_result();
            if ($r = $q->fetch_assoc()) {
                $edit_title = (string)($r['title'] ?? '');
                $edit_message = (string)($r['message'] ?? '');
                $edit_image = (string)($r['image_link'] ?? '');
                $edit_target = 'all';
            }
            $stmt->close();
        }
    } else {
        $stmt = $conn->prepare("SELECT * FROM user_announcements WHERE id = ? LIMIT 1");
        if ($stmt) {
            $stmt->bind_param("i", $update_id);
            $stmt->execute();
            $q = $stmt->get_result();
            if ($r = $q->fetch_assoc()) {
                $edit_title = (string)($r['title'] ?? '');
                $edit_message = (string)($r['message'] ?? '');
                $edit_image = (string)($r['image_link'] ?? '');
                $edit_target = 'user';
                $edit_identifier = (string)($r['email'] ?? '');
            }
            $stmt->close();
        }
    }
}

$res_all = $conn->query("SELECT * FROM announcements ORDER BY id DESC");
$res_user = $conn->query("SELECT * FROM user_announcements ORDER BY id DESC");

require_once "header.php";
?>

<style>
    :root{
        --bg:#f4f7fb;
        --card:#ffffff;
        --text:#102033;
        --muted:#5f6f82;
        --line:#dbe5f0;
        --accent:#2563eb;
        --accent2:#7c3aed;
        --shadow:0 20px 60px rgba(16, 32, 51, .08);
        --radius:22px;
    }

    .page-shell{
        padding:18px;
        width:100%;
        max-width:1400px;
        margin:0 auto;
    }

    .container{
        width:100%;
        display:flex;
        flex-direction:column;
        gap:20px;
    }

    .card{
        width:100%;
        background:rgba(255,255,255,.96);
        border:1px solid var(--line);
        border-radius:var(--radius);
        box-shadow:var(--shadow);
        overflow:hidden;
    }

    .card-head{
        padding:22px 22px 16px;
        border-bottom:1px solid var(--line);
        display:flex;
        justify-content:space-between;
        align-items:flex-start;
        gap:12px;
    }

    .card-head h1{
        font-size:22px;
        line-height:1.2;
        margin:0;
        background:linear-gradient(135deg,var(--accent),var(--accent2));
        -webkit-background-clip:text;
        -webkit-text-fill-color:transparent;
    }

    .card-head p{
        margin-top:6px;
        color:var(--muted);
        font-size:14px;
        line-height:1.6;
    }

    .body-content{
        padding:22px;
    }

    .alert{
        padding:14px 16px;
        border-radius:14px;
        margin-bottom:18px;
        font-size:14px;
        line-height:1.6;
        font-weight:600;
    }
    .alert.success{
        background:#f0fdf4;
        border:1px solid #bbf7d0;
        color:#166534;
    }
    .alert.error{
        background:#fef2f2;
        border:1px solid #fecaca;
        color:#991b1b;
    }

    .target-options{
        display:grid;
        grid-template-columns:repeat(2,minmax(0,1fr));
        gap:12px;
        margin-bottom:18px;
    }

    .target-option input{
        display:none;
    }

    .target-option label{
        display:flex;
        align-items:center;
        justify-content:center;
        padding:12px 10px;
        border:1px solid var(--line);
        border-radius:14px;
        cursor:pointer;
        font-size:14px;
        font-weight:700;
        color:var(--muted);
        background:#fff;
        transition:.2s ease;
        user-select:none;
    }

    .target-option input:checked + label{
        background:rgba(37,99,235,.06);
        border-color:var(--accent);
        color:var(--accent);
        box-shadow:0 0 0 4px rgba(37,99,235,.08);
    }

    .field{
        display:flex;
        flex-direction:column;
        gap:8px;
        margin-bottom:16px;
    }

    .field label{
        font-size:13px;
        font-weight:800;
        color:#334155;
    }

    input[type="text"], textarea{
        width:100%;
        border:1px solid var(--line);
        background:#fff;
        color:var(--text);
        border-radius:14px;
        padding:13px 14px;
        font-size:15px;
        outline:none;
        transition:.2s ease;
        font-family:inherit;
    }

    textarea{
        resize:vertical;
        min-height:110px;
    }

    input:focus, textarea:focus{
        border-color:rgba(37,99,235,.7);
        box-shadow:0 0 0 4px rgba(37,99,235,.10);
    }

    .checkbox-wrapper{
        display:flex;
        align-items:center;
        gap:10px;
        margin-top:4px;
    }

    .checkbox-wrapper input[type="checkbox"]{
        width:18px;
        height:18px;
        accent-color:var(--accent);
        cursor:pointer;
    }

    .checkbox-wrapper label{
        font-size:14px;
        color:var(--muted);
        cursor:pointer;
        font-weight:700;
        user-select:none;
    }

    .btn{
        width:100%;
        border:none;
        border-radius:14px;
        padding:15px 16px;
        font-size:15px;
        font-weight:800;
        color:#fff;
        cursor:pointer;
        background:linear-gradient(135deg,var(--accent),var(--accent2));
        box-shadow:0 14px 28px rgba(37,99,235,.16);
        transition:.2s ease;
        text-decoration:none;
        display:inline-block;
        text-align:center;
    }

    .btn:hover{
        transform:translateY(-2px);
        box-shadow:0 16px 32px rgba(37,99,235,.20);
    }

    .cancel-btn{
        display:inline-block;
        margin-top:10px;
        padding:13px 16px;
        width:100%;
        text-align:center;
        border-radius:14px;
        text-decoration:none;
        color:var(--muted);
        font-weight:800;
        background:#f1f5f9;
        transition:.2s;
    }

    .cancel-btn:hover{
        background:#e2e8f0;
    }

    .no-access{
        text-align:center;
        padding:34px 18px;
        background:#fef2f2;
        border:1px dashed #f87171;
        border-radius:18px;
        color:#991b1b;
        font-weight:700;
        font-size:15px;
        line-height:1.6;
    }

    .table-wrap{
        width:100%;
        overflow-x:auto;
        -webkit-overflow-scrolling:touch;
    }

    table{
        width:100%;
        min-width:680px;
        border-collapse:collapse;
    }

    th, td{
        padding:12px 10px;
        border-bottom:1px solid var(--line);
        text-align:left;
        font-size:14px;
        vertical-align:middle;
    }

    th{
        background:#f8fafc;
        font-weight:800;
        color:var(--muted);
        white-space:nowrap;
    }

    td{
        color:#102033;
        line-height:1.5;
    }

    .row-actions{
        display:flex;
        gap:8px;
        justify-content:flex-end;
        flex-wrap:wrap;
    }

    .action-btn{
        padding:8px 12px;
        border-radius:10px;
        text-decoration:none;
        font-size:13px;
        font-weight:800;
        transition:.2s;
        display:inline-flex;
        align-items:center;
        justify-content:center;
        white-space:nowrap;
    }

    .btn-edit{
        background:#eff6ff;
        color:#2563eb;
    }

    .btn-edit:hover{
        background:#dbeafe;
    }

    .btn-del{
        background:#fef2f2;
        color:#dc2626;
    }

    .btn-del:hover{
        background:#fee2e2;
    }

    .badge{
        display:inline-flex;
        align-items:center;
        padding:4px 10px;
        border-radius:999px;
        font-size:12px;
        font-weight:800;
        background:#f1f5f9;
        color:#475569;
        white-space:nowrap;
    }

    .grid-two{
        display:grid;
        grid-template-columns:1fr;
        gap:20px;
    }

    @media (max-width: 768px){
        .page-shell{
            padding:12px;
        }

        .card-head{
            padding:18px 16px 12px;
            flex-direction:column;
            align-items:flex-start;
        }

        .card-head h1{
            font-size:18px;
        }

        .body-content{
            padding:16px;
        }

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

        .row-actions{
            justify-content:flex-start;
        }

        th, td{
            padding:10px 8px;
            font-size:13px;
        }

        table{
            min-width:620px;
        }
    }
</style>

<div class="page-shell">
    <div class="container">
        <div class="card">
            <div class="card-head">
                <div>
                    <h1><?= !empty($update_id) ? 'Edit Announcement' : 'Send Announcement' ?></h1>
                    <p><?= !empty($update_id) ? 'Modify an existing announcement.' : 'Push announcements and updates to users.' ?></p>
                </div>
            </div>

            <div class="body-content">
                <?php if ($message !== '') echo $message; ?>

                <?php if ($can_send_notification): ?>
                    <form method="post" autocomplete="off">
                        <?php if (!empty($update_id)): ?>
                            <input type="hidden" name="update_id" value="<?= e($update_id) ?>">
                            <input type="hidden" name="update_type" value="<?= e($update_type) ?>">
                        <?php endif; ?>

                        <div class="target-options" style="<?= !empty($update_id) ? 'opacity:0.65; pointer-events:none;' : '' ?>">
                            <div class="target-option">
                                <input type="radio" id="tgt_all" name="target_type" value="all" <?= $edit_target === 'all' ? 'checked' : '' ?>>
                                <label for="tgt_all">All User</label>
                            </div>
                            <div class="target-option">
                                <input type="radio" id="tgt_user" name="target_type" value="user" <?= $edit_target === 'user' ? 'checked' : '' ?>>
                                <label for="tgt_user">Specific User</label>
                            </div>
                        </div>

                        <div id="target_value_wrapper" class="field hidden">
                            <label>Email or Username</label>
                            <input type="text" id="identifier" name="identifier" value="<?= e($edit_identifier) ?>" placeholder="Enter target user's email or username...">
                        </div>

                        <div class="field">
                            <label>Announcement Title</label>
                            <input type="text" name="title" value="<?= e($edit_title) ?>" placeholder="Enter announcement title" required>
                        </div>

                        <div class="field">
                            <label>Image Link</label>
                            <input type="text" name="image_link" value="<?= e($edit_image) ?>" placeholder="Enter image URL">
                            <?php if (empty($update_id)): ?>
                                <div class="checkbox-wrapper">
                                    <input type="checkbox" id="show_image" name="show_image" value="1">
                                    <label for="show_image">Show image in notification</label>
                                </div>
                            <?php endif; ?>
                        </div>

                        <div class="field">
                            <label>Announcement Message</label>
                            <textarea name="body" placeholder="Enter announcement details" required><?= e($edit_message) ?></textarea>
                        </div>

                        <button type="submit" class="btn"><?= !empty($update_id) ? 'Update Announcement' : 'Push Announcement' ?></button>

                        <?php if (!empty($update_id)): ?>
                            <a href="?" class="cancel-btn">Cancel Edit</a>
                        <?php endif; ?>
                    </form>
                <?php else: ?>
                    <div class="no-access">
                        Access Denied: You do not have permission to send announcements.
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <?php if ($can_send_notification): ?>
            <div class="card">
                <div class="card-head">
                    <div>
                        <h1>Global History</h1>
                        <p>Announcements sent to all users</p>
                    </div>
                </div>
                <div class="body-content">
                    <div class="table-wrap">
                        <table>
                            <thead>
                                <tr>
                                    <th style="width: 18%;">Date</th>
                                    <th>Title</th>
                                    <th style="width: 26%; text-align:right;">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if ($res_all && $res_all->num_rows > 0): ?>
                                    <?php while ($row = $res_all->fetch_assoc()): ?>
                                        <tr>
                                            <td><span class="badge"><?= e($row['announce_date'] ?? '') ?></span></td>
                                            <td><?= e($row['title'] ?? '') ?></td>
                                            <td>
                                                <div class="row-actions">
                                                    <a href="?edit_id=<?= (int)$row['id'] ?>&type=all" class="action-btn btn-edit">Edit</a>
                                                    <a href="?del_id=<?= (int)$row['id'] ?>&type=all"
                                                       class="action-btn btn-del"
                                                       data-confirm="Are you sure you want to delete this announcement?"
                                                       onclick="return confirmDelete(this);">Delete</a>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr><td colspan="3" style="text-align:center; color:var(--muted); padding:20px;">No global announcements found.</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <div class="card">
                <div class="card-head">
                    <div>
                        <h1>Specific User History</h1>
                        <p>Announcements sent to specific users</p>
                    </div>
                </div>
                <div class="body-content">
                    <div class="table-wrap">
                        <table>
                            <thead>
                                <tr>
                                    <th style="width: 18%;">Date</th>
                                    <th style="width: 28%;">Target</th>
                                    <th>Title</th>
                                    <th style="width: 26%; text-align:right;">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if ($res_user && $res_user->num_rows > 0): ?>
                                    <?php while ($row = $res_user->fetch_assoc()): ?>
                                        <tr>
                                            <td><span class="badge"><?= e($row['announce_date'] ?? '') ?></span></td>
                                            <td><strong><?= e($row['email'] ?? '') ?></strong></td>
                                            <td><?= e($row['title'] ?? '') ?></td>
                                            <td>
                                                <div class="row-actions">
                                                    <a href="?edit_id=<?= (int)$row['id'] ?>&type=user" class="action-btn btn-edit">Edit</a>
                                                    <a href="?del_id=<?= (int)$row['id'] ?>&type=user"
                                                       class="action-btn btn-del"
                                                       data-confirm="Are you sure you want to delete this announcement?"
                                                       onclick="return confirmDelete(this);">Delete</a>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr><td colspan="4" style="text-align:center; color:var(--muted); padding:20px;">No specific user announcements found.</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const radios = document.querySelectorAll('input[name="target_type"]');
    const wrapper = document.getElementById('target_value_wrapper');
    const input = document.getElementById('identifier');

    const toggleWrapper = (val) => {
        if (!wrapper || !input) return;
        if (val === 'all') {
            wrapper.classList.add('hidden');
            input.removeAttribute('required');
        } else {
            wrapper.classList.remove('hidden');
            input.setAttribute('required', 'required');
        }
    };

    radios.forEach(radio => {
        if (radio.checked) toggleWrapper(radio.value);
        radio.addEventListener('change', function() {
            toggleWrapper(this.value);
            if (this.value === 'user' && input) input.focus();
        });
    });
});

function confirmDelete(el) {
    const msg = el.getAttribute('data-confirm') || 'Are you sure you want to delete this item?';
    return confirm(msg);
}
</script>

<?php if (isset($can_send_notification) && $can_send_notification): ?>
    </div>
</body>
</html>
<?php endif; ?>