<?php

/**
 * PWA Note Controller
 * Handles note management for PWA
 */
class PwaNoteController {
    
    private $noteModel;
    
    public function __construct() {
        $this->noteModel = new Note();
        $this->requireAuth();
    }
    
    /**
     * Display all notes
     */
    public function index() {
        $userId = getCurrentUserId();
        
        // Get notes based on user type
        if (isAdmin()) {
            $notes = $this->noteModel->getAll();
        } else {
            $notes = $this->noteModel->getByUser($userId);
        }
        
        require_once APP_PATH . '/views/pwa/notes.php';
    }
    
    /**
     * Show create note form
     */
    public function create() {
        // Handle POST request
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $this->store();
            return;
        }
        
        require_once APP_PATH . '/views/pwa/add-note.php';
    }
    
    /**
     * Store new note
     */
    private function store() {
        $userId = getCurrentUserId();
        
        $data = [
            'user_id' => $userId,
            'title' => sanitize($_POST['title'] ?? ''),
            'note_type' => sanitize($_POST['note_type'] ?? 'single'),
            'reminder_date' => sanitize($_POST['reminder_date'] ?? ''),
            'content' => sanitize($_POST['content'] ?? ''),
            'image_path' => ''
        ];
        
        // Handle multiple image uploads
        $imagePaths = [];
        
        if (isset($_FILES['images']) && is_array($_FILES['images']['name'])) {
            $imageService = new ImageService();
            
            $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 = $imageService->processImage($tempFile);
                    
                    if ($imagePath) {
                        $imagePaths[] = $imagePath;
                    }
                }
            }
        }
        
        // Store image paths as JSON array
        if (!empty($imagePaths)) {
            $data['image_path'] = json_encode($imagePaths);
        }
        
        $noteId = $this->noteModel->create($data);
        
        // Always return JSON response (form is submitted via AJAX)
        header('Content-Type: application/json');
        if ($noteId) {
            echo json_encode(['success' => true, 'message' => 'Note created successfully!']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Failed to create note']);
        }
        exit;
    }
    
    /**
     * Require authentication
     */
    private function requireAuth() {
        if (!isAuthenticated()) {
            redirect('/login');
            exit;
        }
    }
}
