<?php
/**
 * Kontroler Notatek per encja (AJAX API)
 */

require_once __DIR__ . '/BaseController.php';

class EntityNotesController extends BaseController
{
    private EntityNotes $notesModel;
    private AuditLog $auditLog;
    
    public function __construct()
    {
        parent::__construct();
        $this->notesModel = new EntityNotes();
        $this->auditLog = new AuditLog();
    }
    
    /**
     * Lista notatek dla encji
     */
    public function list(): void
    {
        $entityType = get('entity_type');
        $entityId = (int)get('entity_id');
        
        if (!$this->validateEntityAccess($entityType, $entityId)) {
            $this->json(['success' => false, 'error' => 'Brak dostępu']);
            return;
        }
        
        $notes = $this->notesModel->getByEntity($entityType, $entityId);
        
        $this->json([
            'success' => true,
            'notes' => $notes,
            'count' => count($notes)
        ]);
    }
    
    /**
     * Dodaj notatkę
     */
    public function add(): void
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $this->json(['success' => false, 'error' => 'Nieprawidłowa metoda']);
            return;
        }
        
        $entityType = post('entity_type');
        $entityId = (int)post('entity_id');
        
        if (!$this->validateEntityAccess($entityType, $entityId)) {
            $this->json(['success' => false, 'error' => 'Brak dostępu']);
            return;
        }
        
        $data = [
            'title' => post('title', ''),
            'content' => post('content', ''),
            'color' => post('color', 'default'),
            'is_pinned' => post('is_pinned') ? 1 : 0
        ];
        
        $result = $this->notesModel->add($entityType, $entityId, $this->currentUser['id'], $data);
        
        if ($result['success']) {
            $this->logger->log('note_added', "Dodano notatkę do {$entityType} #{$entityId}", $this->currentUser['id']);
            
            // Audit log ze szczegółami
            $this->auditLog->log(
                'note',
                $result['id'] ?? 0,
                'create',
                null,
                [
                    'entity_type' => $entityType,
                    'entity_id' => $entityId,
                    'title' => $data['title'],
                    'content' => $data['content'],
                    'color' => $data['color'],
                    'is_pinned' => $data['is_pinned']
                ]
            );
        }
        
        $this->json($result);
    }
    
    /**
     * Aktualizuj notatkę
     */
    public function update(): void
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $this->json(['success' => false, 'error' => 'Nieprawidłowa metoda']);
            return;
        }
        
        $noteId = (int)post('id');
        
        // Pobierz starą notatkę do audit logu
        $oldNote = $this->notesModel->getById($noteId);
        
        $data = [
            'title' => post('title'),
            'content' => post('content'),
            'color' => post('color'),
            'is_pinned' => post('is_pinned') !== null ? (post('is_pinned') ? 1 : 0) : null
        ];
        
        // Usuń null wartości
        $data = array_filter($data, fn($v) => $v !== null);
        
        $result = $this->notesModel->update($noteId, $this->currentUser['id'], $data);
        
        if ($result['success'] && $oldNote) {
            $this->logger->log('note_updated', "Zaktualizowano notatkę #{$noteId}", $this->currentUser['id']);
            
            // Audit log z before/after
            $this->auditLog->log(
                'note',
                $noteId,
                'update',
                [
                    'entity_type' => $oldNote['entity_type'],
                    'entity_id' => $oldNote['entity_id'],
                    'title' => $oldNote['title'] ?? null,
                    'content' => $oldNote['content'] ?? $oldNote['note'] ?? '',
                    'color' => $oldNote['color'] ?? 'default',
                    'is_pinned' => $oldNote['is_pinned'] ?? 0
                ],
                [
                    'entity_type' => $oldNote['entity_type'],
                    'entity_id' => $oldNote['entity_id'],
                    'title' => $data['title'] ?? $oldNote['title'] ?? null,
                    'content' => $data['content'] ?? $oldNote['content'] ?? $oldNote['note'] ?? '',
                    'color' => $data['color'] ?? $oldNote['color'] ?? 'default',
                    'is_pinned' => $data['is_pinned'] ?? $oldNote['is_pinned'] ?? 0
                ]
            );
        }
        
        $this->json($result);
    }
    
    /**
     * Usuń notatkę
     */
    public function delete(): void
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $this->json(['success' => false, 'error' => 'Nieprawidłowa metoda']);
            return;
        }
        
        $noteId = (int)post('id');
        
        // Pobierz notatkę przed usunięciem do audit logu
        $oldNote = $this->notesModel->getById($noteId);
        
        $result = $this->notesModel->delete($noteId, $this->currentUser['id']);
        
        if ($result['success']) {
            $this->logger->log('note_deleted', "Usunięto notatkę #{$noteId}", $this->currentUser['id']);
            
            // Audit log ze szczegółami usuniętej notatki
            if ($oldNote) {
                $this->auditLog->log(
                    'note',
                    $noteId,
                    'delete',
                    [
                        'entity_type' => $oldNote['entity_type'],
                        'entity_id' => $oldNote['entity_id'],
                        'title' => $oldNote['title'] ?? null,
                        'content' => $oldNote['content'] ?? $oldNote['note'] ?? '',
                        'color' => $oldNote['color'] ?? 'default',
                        'is_pinned' => $oldNote['is_pinned'] ?? 0,
                        'created_by_user_id' => $oldNote['user_id']
                    ],
                    null
                );
            }
        }
        
        $this->json($result);
    }
    
    /**
     * Przełącz przypięcie
     */
    public function togglePin(): void
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $this->json(['success' => false, 'error' => 'Nieprawidłowa metoda']);
            return;
        }
        
        $noteId = (int)post('id');
        
        // Pobierz stan przed zmianą
        $oldNote = $this->notesModel->getById($noteId);
        
        $result = $this->notesModel->togglePin($noteId, $this->currentUser['id']);
        
        if ($result['success'] && $oldNote) {
            $newPinned = !($oldNote['is_pinned'] ?? 0);
            $action = $newPinned ? 'pin' : 'unpin';
            
            $this->logger->log('note_' . $action, ($newPinned ? 'Przypięto' : 'Odpięto') . " notatkę #{$noteId}", $this->currentUser['id']);
            
            $this->auditLog->log(
                'note',
                $noteId,
                $action,
                ['is_pinned' => $oldNote['is_pinned'] ?? 0],
                ['is_pinned' => $newPinned ? 1 : 0]
            );
        }
        
        $this->json($result);
    }
    
    /**
     * Sprawdź dostęp do encji
     */
    private function validateEntityAccess(string $entityType, int $entityId): bool
    {
        if (!in_array($entityType, ['device', 'playlist', 'user'])) {
            return false;
        }
        
        // Admin ma dostęp do wszystkiego
        if ($this->auth->isAdmin()) {
            return true;
        }
        
        $db = Database::getInstance();
        
        switch ($entityType) {
            case 'device':
                $device = $db->fetchOne(
                    "SELECT user_id FROM devices WHERE id = :id",
                    ['id' => $entityId]
                );
                if (!$device) return false;
                
                // Właściciel urządzenia
                if ($device['user_id'] == $this->currentUser['id']) return true;
                
                // Reseller - urządzenie jego usera
                if ($this->auth->isReseller()) {
                    $user = $db->fetchOne(
                        "SELECT parent_id FROM users WHERE id = :id",
                        ['id' => $device['user_id']]
                    );
                    return $user && $user['parent_id'] == $this->currentUser['id'];
                }
                break;
                
            case 'playlist':
                $playlist = $db->fetchOne(
                    "SELECT d.user_id FROM playlists p 
                     JOIN devices d ON p.device_id = d.id 
                     WHERE p.id = :id",
                    ['id' => $entityId]
                );
                if (!$playlist) return false;
                
                if ($playlist['user_id'] == $this->currentUser['id']) return true;
                
                if ($this->auth->isReseller()) {
                    $user = $db->fetchOne(
                        "SELECT parent_id FROM users WHERE id = :id",
                        ['id' => $playlist['user_id']]
                    );
                    return $user && $user['parent_id'] == $this->currentUser['id'];
                }
                break;
                
            case 'user':
                // Użytkownik może dodać notatkę do siebie
                if ($entityId == $this->currentUser['id']) return true;
                
                // Reseller do swoich userów
                if ($this->auth->isReseller()) {
                    $user = $db->fetchOne(
                        "SELECT parent_id FROM users WHERE id = :id",
                        ['id' => $entityId]
                    );
                    return $user && $user['parent_id'] == $this->currentUser['id'];
                }
                break;
        }
        
        return false;
    }
}
