<?php
/**
 * API: Delete Survey
 * Research Survey Management System
 */

require_once __DIR__ . '/../includes/functions.php';
requireRole(['admin', 'researcher']);

$surveyId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($surveyId) {
    $pdo = getDBConnection();
    
    // Check ownership
    $stmt = $pdo->prepare("SELECT created_by FROM surveys WHERE survey_id = :id");
    $stmt->execute(['id' => $surveyId]);
    $survey = $stmt->fetch();
    
    if ($survey && ($survey['created_by'] == $_SESSION['user_id'] || $_SESSION['user_role'] === 'admin')) {
        $stmt = $pdo->prepare("DELETE FROM surveys WHERE survey_id = :id");
        $stmt->execute(['id' => $surveyId]);
        
        logAudit('delete', 'survey', $surveyId);
        
        $_SESSION['flash_message'] = 'Survey deleted successfully.';
        $_SESSION['flash_type'] = 'success';
    } else {
        $_SESSION['flash_message'] = 'You do not have permission to delete this survey.';
        $_SESSION['flash_type'] = 'danger';
    }
}

header('Location: ' . BASE_URL . '/pages/surveys.php');
exit;