<?php
include '../connection.php';

// Insert Announcement (with duplicate check)
if (isset($_POST['action']) && $_POST['action'] == 'add') {
    $title = $_POST['title'];
    $details = $_POST['details'];
    $related_to = $_POST['related_to'];

    // Check if the title already exists in the database
    $checkQuery = "SELECT * FROM announcement WHERE an_titile = '$title'";
    $checkResult = mysqli_query($conn, $checkQuery);

    if (mysqli_num_rows($checkResult) > 0) {
        // Title exists, return error message
        echo json_encode(['status' => 'error', 'message' => 'Announcement title already exists.']);
        exit;
    }

    // No duplicate, proceed with insert
    $insertQuery = "INSERT INTO announcement (an_titile, details, related_to) 
                    VALUES ('$title', '$details', '$related_to')";
    mysqli_query($conn, $insertQuery);
    echo json_encode(['status' => 'success']);
    exit;
}

// Update Announcement
if (isset($_POST['action']) && $_POST['action'] == 'update') {
    $id = $_POST['id'];
    $title = $_POST['title'];
    $details = $_POST['details'];
    $related_to = $_POST['related_to'];

    $updateQuery = "UPDATE announcement SET an_titile = '$title', details = '$details', related_to = '$related_to' WHERE ID = $id";
    mysqli_query($conn, $updateQuery);
    echo json_encode(['status' => 'success']);
    exit;
}

// Delete Announcement
if (isset($_POST['action']) && $_POST['action'] == 'delete') {
    $id = $_POST['id'];

    $deleteQuery = "DELETE FROM announcement WHERE ID = $id";
    mysqli_query($conn, $deleteQuery);
    echo json_encode(['status' => 'success']);
    exit;
}

// Fetch All Announcements
$query = "SELECT ID, an_titile, details, related_to FROM announcement";
$result = mysqli_query($conn, $query);

$announcements = [];
while ($row = mysqli_fetch_assoc($result)) {
    $announcements[] = $row;
}

echo json_encode(['announcements' => $announcements]);
exit;
?>
