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

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

    $db2 = getDB2Connection();
    
    if (isset($_GET['id'])) {
        // Récupérer une note spécifique
        $stmt = $db2->prepare("
            SELECT id, title, content, created_at, updated_at
            FROM notebystaff 
            WHERE id = ? AND user_id = ?
        ");
        
        $stmt->execute([
            $_GET['id'],
            $_SESSION['user_id']
        ]);
        
        $note = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$note) {
            throw new Exception('Note not found');
        }
        
        echo json_encode([
            'success' => true,
            'note' => [
                'id' => $note['id'],
                'title' => $note['title'],
                'content' => $note['content'],
                'created_at' => $note['created_at'],
                'updated_at' => $note['updated_at']
            ]
        ]);
        
    } else {
        // Récupérer toutes les notes
        $search = isset($_GET['search']) ? $_GET['search'] : '';
        $orderBy = isset($_GET['order']) ? $_GET['order'] : 'updated_at';
        $direction = isset($_GET['direction']) ? $_GET['direction'] : 'DESC';
        
        $allowedOrders = ['title', 'created_at', 'updated_at'];
        $orderBy = in_array($orderBy, $allowedOrders) ? $orderBy : 'updated_at';
        $direction = strtoupper($direction) === 'ASC' ? 'ASC' : 'DESC';
        
        $query = "
            SELECT id, title, content, created_at, updated_at
            FROM notebystaff 
            WHERE user_id = ?
        ";
        
        $params = [$_SESSION['user_id']];
        
        if ($search) {
            $query .= " AND (title LIKE ? OR content LIKE ?)";
            $params[] = "%$search%";
            $params[] = "%$search%";
        }
        
        $query .= " ORDER BY $orderBy $direction";
        
        $stmt = $db2->prepare($query);
        $stmt->execute($params);
        
        $notes = [];
        while ($note = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $notes[] = [
                'id' => $note['id'],
                'title' => $note['title'],
                'content' => mb_substr(strip_tags($note['content']), 0, 150) . '...',
                'created_at' => $note['created_at'],
                'updated_at' => $note['updated_at']
            ];
        }
        
        echo json_encode([
            'success' => true,
            'notes' => $notes,
            'total' => count($notes),
            'filters' => [
                'search' => $search,
                'orderBy' => $orderBy,
                'direction' => $direction
            ]
        ]);
    }

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