<?php
/**
 * API: Delete notification
 * 
 * This endpoint deletes a notification and its recipients
 */

require_once '../../config/database.php';
requireAdmin();

// Default response structure
$response = [
    'success' => false,
    'data' => null,
    'message' => 'Error deleting notification'
];

// Only allow POST or DELETE requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST' && $_SERVER['REQUEST_METHOD'] !== 'DELETE') {
    $response['message'] = 'Method not allowed';
    header('Content-Type: application/json');
    echo json_encode($response);
    exit;
}

try {
    // Get data
    if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
        parse_str(file_get_contents('php://input'), $data);
    } else {
        $postData = json_decode(file_get_contents('php://input'), true);
        if (!$postData) {
            $postData = $_POST;
        }
        $data = $postData;
    }
    
    // Validate required fields
    if (!isset($data['notification_id']) || empty($data['notification_id'])) {
        throw new Exception("Field 'notification_id' is required");
    }
    
    $db = new Database();
    $conn = $db->getConnection();
    
    $notificationId = $data['notification_id'];
    
    // Start transaction
    $conn->beginTransaction();
    
    // First delete recipients (due to foreign key constraint)
    $deleteRecipientsQuery = "DELETE FROM notification_recipients WHERE notification_id = :notification_id";
    $deleteRecipientsStmt = $conn->prepare($deleteRecipientsQuery);
    $deleteRecipientsStmt->bindValue(':notification_id', $notificationId);
    $deleteRecipientsStmt->execute();
    
    // Then delete the notification
    $deleteNotificationQuery = "DELETE FROM notifications WHERE id = :notification_id";
    $deleteNotificationStmt = $conn->prepare($deleteNotificationQuery);
    $deleteNotificationStmt->bindValue(':notification_id', $notificationId);
    $deleteNotificationStmt->execute();
    
    // Commit transaction
    $conn->commit();
    
    // Format the response
    $response = [
        'success' => true,
        'data' => [
            'notification_id' => $notificationId,
            'deleted' => true
        ],
        'message' => 'Notification deleted successfully'
    ];
    
} catch (PDOException $e) {
    // Rollback transaction on error
    if (isset($conn)) {
        $conn->rollBack();
    }
    $response['message'] = 'Database error: ' . $e->getMessage();
} catch (Exception $e) {
    if (isset($conn)) {
        $conn->rollBack();
    }
    $response['message'] = 'Error: ' . $e->getMessage();
}

// Send JSON response
header('Content-Type: application/json');
echo json_encode($response);
exit;
