<?php
ob_start();
include("../../../include/startup.php");

if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'check_group_number') {
    ob_clean();
    header('Content-Type: application/json');

    $group_number = mysqli_real_escape_string($conn, $_REQUEST['group_number']);
    $id = isset($_REQUEST['id']) ? intval($_REQUEST['id']) : 0;

    $sql    = "SELECT id FROM group_mangmnt WHERE group_number = '$group_number' AND id != $id";
    $result = mysqli_query($conn, $sql);

    echo json_encode(['exists' => mysqli_num_rows($result) > 0]);
    exit();
}

else if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'delete_group_mapping') {
    ob_clean();
    header('Content-Type: application/json');

    $na_mapping_id = intval($_REQUEST['na_mapping_id']);

    if($na_mapping_id <= 0) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid mapping ID']);
        exit();
    }

    $sql     = "DELETE FROM group_mangmnt_mapping WHERE id = $na_mapping_id";
    $deleted = mysqli_query($conn, $sql);

    if($deleted && mysqli_affected_rows($conn) > 0) {
        echo json_encode(['status' => 'success', 'message' => 'Mapping deleted successfully']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Delete failed or record not found']);
    }
    exit();
}
?>