<?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']) || !isset($data['title']) || !isset($data['content'])) {
        throw new Exception('Missing required fields');
    }

    $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("
        UPDATE notebystaff 
        SET title = ?, 
            content = ?,
            updated_at = CURRENT_TIMESTAMP
        WHERE id = ? AND user_id = ?
    ");
    
    $stmt->execute([
        $data['title'],
        $data['content'],
        $data['id'],
        $_SESSION['user_id']
    ]);
    
    $stmt = $db2->prepare("
        SELECT id, title, content, created_at, updated_at
        FROM notebystaff 
        WHERE id = ?
    ");
    
    $stmt->execute([$data['id']]);
    $updatedNote = $stmt->fetch(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'message' => 'Note updated successfully',
        'note' => [
            'id' => $updatedNote['id'],
            'title' => $updatedNote['title'],
            'content' => $updatedNote['content'],
            'created_at' => $updatedNote['created_at'],
            'updated_at' => $updatedNote['updated_at']
        ]
    ]);

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