<?php
require_once '../db.php';
session_start();
header('Content-Type: application/json');

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('Invalid request method');
    }

    $data = json_decode(file_get_contents('php://input'), true);
    
    if (!isset($data['id'])) {
        throw new Exception('Missing note ID');
    }

    $db2 = getDB2Connection();
    
    $stmt = $db2->prepare("
        SELECT user_id 
        FROM notebystaff 
        WHERE id = ?
    ");
    $stmt->execute([$data['id']]);
    $note = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$note) {
        throw new Exception('Note not found');
    }
    
    if ($note['user_id'] !== $_SESSION['user_id']) {
        throw new Exception('Unauthorized access to note');
    }

    $stmt = $db2->prepare("
        DELETE FROM notebystaff 
        WHERE id = ? AND user_id = ?
    ");
    
    $stmt->execute([
        $data['id'],
        $_SESSION['user_id']
    ]);
    
    if ($stmt->rowCount() === 0) {
        throw new Exception('Failed to delete note');
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Note deleted successfully',
        'noteId' => $data['id']
    ]);

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