<?php
session_start();
include 'layouts/dbconn.php';

// Set content type to JSON
header('Content-Type: application/json');

// Check if user is logged in and has admin access
if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] !== 1) {
    http_response_code(403);
    echo json_encode(['success' => false, 'error' => 'Insufficient permissions. Not Authorized.']);
    exit;
}

try {
    if (!isset($_POST['setting_id']) || empty($_POST['setting_id'])) {
        throw new Exception('Setting ID is required');
    }

    $setting_id = (int)$_POST['setting_id'];

    // Get recipient details before deletion for logging
    $sql = "SELECT ns.*, nt.template_name 
            FROM notification_settings ns
            JOIN notification_templates nt ON ns.template_id = nt.template_id
            WHERE ns.setting_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $setting_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        throw new Exception('Recipient not found');
    }
    
    $recipient = $result->fetch_assoc();

    // Delete the recipient
    $sql = "DELETE FROM notification_settings WHERE setting_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $setting_id);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to delete recipient: ' . $stmt->error);
    }

    if ($stmt->affected_rows === 0) {
        throw new Exception('Recipient not found or already deleted');
    }

    // Log activity
    $sql = "INSERT INTO activity_log (user_id, action, table_name, record_id, old_values, ip_address, user_agent) 
            VALUES (?, 'DELETE', 'notification_settings', ?, ?, ?, ?)";
    $stmt = $conn->prepare($sql);
    $old_values = json_encode([
        'template_name' => $recipient['template_name'],
        'recipient_type' => $recipient['recipient_type'],
        'recipient_value' => $recipient['recipient_value']
    ]);
    $stmt->bind_param('sssss', 
        $_SESSION['user_id'], 
        $setting_id, 
        $old_values, 
        $_SERVER['REMOTE_ADDR'], 
        $_SERVER['HTTP_USER_AGENT']
    );
    $stmt->execute();

    echo json_encode([
        'success' => true,
        'message' => 'Recipient deleted successfully'
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
} finally {
    if (isset($conn)) {
        $conn->close();
    }
}
?>