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

    $db2 = getDB2Connection();
    
    $stmt = $db2->prepare("
        INSERT INTO notebystaff (user_id, title, content)
        VALUES (?, ?, ?)
    ");
    
    $stmt->execute([
        $_SESSION['user_id'],
        $data['title'],
        $data['content']
    ]);
    
    $noteId = $db2->lastInsertId();
    
    $stmt = $db2->prepare("
        SELECT id, title, content, created_at, updated_at
        FROM notebystaff 
        WHERE id = ?
    ");
    
    $stmt->execute([$noteId]);
    $note = $stmt->fetch(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'message' => 'Note created successfully',
        'note' => [
            'id' => $note['id'],
            'title' => $note['title'],
            'content' => $note['content'],
            'created_at' => $note['created_at'],
            'updated_at' => $note['updated_at']
        ]
    ]);

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