<?php

/**
 * Note Controller
 * Handles note CRUD operations with image upload
 */
class NoteController {
    
    private $noteModel;
    private $userModel;
    private $imageService;
    
    public function __construct() {
        $this->noteModel = new Note();
        $this->userModel = new User();
        $this->imageService = new ImageService();
    }
    
    /**
     * Display notes list
     */
    public function index() {
        // Get notes based on user type
        if (isAdmin()) {
            // Admin can see all notes
            $notes = $this->noteModel->getAll();
        } else {
            // Regular user can only see their own notes
            $notes = $this->noteModel->getAll(getCurrentUserId());
        }
        
        require_once APP_PATH . '/views/admin/notes/index.php';
    }
    
    /**
     * Show create note form
     */
    public function create() {
        // No need to get users - notes are always created for current user
        
        require_once APP_PATH . '/views/admin/notes/create.php';
    }
    
    /**
     * Store new note
     */
    public function store() {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            redirect(BASE_URL.'/admin/notes/create');
        }
        
        // Validate required fields
        $errors = [];
        
        // Notes are always created for the current logged-in user
        $userId = getCurrentUserId();
        
        if (empty($userId)) {
            $errors[] = 'User session error. Please login again.';
        }
        
        if (empty($_POST['title'])) {
            $errors[] = 'Title is required';
        }
        
        if (empty($_POST['note_type'])) {
            $errors[] = 'Note type is required';
        }
        
        if (empty($_POST['reminder_date'])) {
            $errors[] = 'Reminder date is required';
        }
        
        // Validate note type
        if (!empty($_POST['note_type']) && !in_array($_POST['note_type'], ['single', 'regular'])) {
            $errors[] = 'Invalid note type';
        }
        
        if (!empty($errors)) {
            $_SESSION['error'] = implode('<br>', $errors);
            redirect(BASE_URL.'/admin/notes/create');
        }
        
        // Handle multiple image uploads
        $imagePaths = [];
        
        if (isset($_FILES['images']) && is_array($_FILES['images']['name'])) {
            $fileCount = count($_FILES['images']['name']);
            
            for ($i = 0; $i < $fileCount; $i++) {
                // Check if file was uploaded
                if ($_FILES['images']['error'][$i] === UPLOAD_ERR_OK) {
                    // Create a temporary file array for ImageService
                    $tempFile = [
                        'name' => $_FILES['images']['name'][$i],
                        'type' => $_FILES['images']['type'][$i],
                        'tmp_name' => $_FILES['images']['tmp_name'][$i],
                        'error' => $_FILES['images']['error'][$i],
                        'size' => $_FILES['images']['size'][$i]
                    ];
                    
                    $imagePath = $this->imageService->processImage($tempFile);
                    
                    if ($imagePath) {
                        $imagePaths[] = $imagePath;
                    }
                }
            }
        }
        
        // Store image paths as JSON array
        $imagePathJson = '';
        if (!empty($imagePaths)) {
            $imagePathJson = json_encode($imagePaths);
        }
        
        // Create note
        $data = [
            'user_id' => $userId,
            'title' => sanitize($_POST['title']),
            'note_type' => $_POST['note_type'],
            'reminder_date' => $_POST['reminder_date'],
            'image_path' => $imagePathJson,
            'content' => sanitize($_POST['content'] ?? '')
        ];
        
        $noteId = $this->noteModel->create($data);
        
        if ($noteId) {
            $_SESSION['success'] = 'Note created successfully';
            redirect(BASE_URL.'/admin/notes');
        } else {
            // Delete uploaded images if note creation failed
            foreach ($imagePaths as $path) {
                $this->imageService->deleteImage($path);
            }
            $_SESSION['error'] = 'Failed to create note';
            redirect(BASE_URL.'/admin/notes/create');
        }
    }
    
    /**
     * Show edit note form
     */
    public function edit($id) {
        $note = $this->noteModel->findById($id);
        
        if (!$note) {
            $_SESSION['error'] = 'Note not found';
            redirect(BASE_URL.'/admin/notes');
        }
        
        // Check if user has permission to edit this note
        if (!isAdmin() && $note->user_id != getCurrentUserId()) {
            $_SESSION['error'] = 'You do not have permission to edit this note';
            redirect(BASE_URL.'/admin/notes');
            return;
        }
        
        require_once APP_PATH . '/views/admin/notes/edit.php';
    }
    
    /**
     * Update note
     */
    public function update($id) {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            redirect(BASE_URL.'/admin/notes/edit/' . $id);
        }
        
        $note = $this->noteModel->findById($id);
        
        if (!$note) {
            $_SESSION['error'] = 'Note not found';
            redirect(BASE_URL.'/admin/notes');
        }
        
        // Check if user has permission to edit this note
        if (!isAdmin() && $note->user_id != getCurrentUserId()) {
            $_SESSION['error'] = 'You do not have permission to edit this note';
            redirect(BASE_URL.'/admin/notes');
            return;
        }
        
        // Validate required fields
        $errors = [];
        
        // Keep the original user_id - notes cannot be reassigned
        $userId = $note->user_id;
        
        if (empty($_POST['title'])) {
            $errors[] = 'Title is required';
        }
        
        if (empty($_POST['note_type'])) {
            $errors[] = 'Note type is required';
        }
        
        if (empty($_POST['reminder_date'])) {
            $errors[] = 'Reminder date is required';
        }
        
        // Validate note type
        if (!empty($_POST['note_type']) && !in_array($_POST['note_type'], ['single', 'regular'])) {
            $errors[] = 'Invalid note type';
        }
        
        if (!empty($errors)) {
            $_SESSION['error'] = implode('<br>', $errors);
            redirect(BASE_URL.'/admin/notes/edit/' . $id);
        }
        
        // Handle multiple image uploads (if new images provided)
        $imagePath = $note->image_path;
        
        if (isset($_FILES['images']) && is_array($_FILES['images']['name']) && !empty($_FILES['images']['name'][0])) {
            $newImagePaths = [];
            $fileCount = count($_FILES['images']['name']);
            
            for ($i = 0; $i < $fileCount; $i++) {
                if ($_FILES['images']['error'][$i] === UPLOAD_ERR_OK) {
                    $tempFile = [
                        'name' => $_FILES['images']['name'][$i],
                        'type' => $_FILES['images']['type'][$i],
                        'tmp_name' => $_FILES['images']['tmp_name'][$i],
                        'error' => $_FILES['images']['error'][$i],
                        'size' => $_FILES['images']['size'][$i]
                    ];
                    
                    $newPath = $this->imageService->processImage($tempFile);
                    if ($newPath) {
                        $newImagePaths[] = $newPath;
                    }
                }
            }
            
            if (!empty($newImagePaths)) {
                // Delete old images
                if ($imagePath) {
                    $oldImages = json_decode($imagePath, true);
                    if (is_array($oldImages)) {
                        foreach ($oldImages as $oldImg) {
                            $this->imageService->deleteImage($oldImg);
                        }
                    } else {
                        $this->imageService->deleteImage($imagePath);
                    }
                }
                $imagePath = json_encode($newImagePaths);
            }
        }
        
        // Update note
        $data = [
            'user_id' => $userId,
            'title' => sanitize($_POST['title']),
            'note_type' => $_POST['note_type'],
            'reminder_date' => $_POST['reminder_date'],
            'image_path' => $imagePath,
            'content' => sanitize($_POST['content'] ?? '')
        ];
        
        if ($this->noteModel->update($id, $data)) {
            $_SESSION['success'] = 'Note updated successfully';
            redirect(BASE_URL.'/admin/notes');
        } else {
            $_SESSION['error'] = 'Failed to update note';
            redirect(BASE_URL.'/admin/notes/edit/' . $id);
        }
    }
    
    /**
     * Delete note
     */
    public function delete($id) {
        $note = $this->noteModel->findById($id);
        
        if (!$note) {
            $_SESSION['error'] = 'Note not found';
            redirect(BASE_URL.'/admin/notes');
        }
        
        // Check if user has permission to delete this note
        if (!isAdmin() && $note->user_id != getCurrentUserId()) {
            $_SESSION['error'] = 'You do not have permission to delete this note';
            redirect(BASE_URL.'/admin/notes');
            return;
        }
        
        // Delete images if exist
        if ($note->image_path) {
            $images = json_decode($note->image_path, true);
            if (is_array($images)) {
                foreach ($images as $img) {
                    $this->imageService->deleteImage($img);
                }
            } else {
                $this->imageService->deleteImage($note->image_path);
            }
        }
        
        if ($this->noteModel->delete($id)) {
            $_SESSION['success'] = 'Note deleted successfully';
        } else {
            $_SESSION['error'] = 'Failed to delete note';
        }
        
        redirect(BASE_URL.'/admin/notes');
    }
    
    /**
     * Bulk delete past single notes
     */
    public function bulkDeletePast() {
        $deletedCount = $this->noteModel->deletePastSingleNotes();
        
        if ($deletedCount > 0) {
            $_SESSION['success'] = "Successfully deleted $deletedCount past single note(s)";
        } else {
            $_SESSION['info'] = 'No past single notes found to delete';
        }
        
        redirect(BASE_URL.'/admin/notes');
    }
}
