<?php 
$pageTitle = 'Add Note';
$activePage = 'add-note';
include __DIR__ . '/_header.php'; 

$authController = new AuthController();
$currentUser = $authController->getCurrentUser();
$username = $currentUser ? $currentUser->username : 'User';
?>

<header class="pwa-header">
    <div class="container-fluid">
        <div class="d-flex align-items-center justify-content-between">
            <div class="d-flex align-items-center">
                <a href="<?php echo URL_PATH; ?>/home" class="btn-icon me-2">
                    <i class="bi bi-arrow-left"></i>
                </a>
                <div>
                    <small class="text-white-50 d-block" style="font-size: 0.75rem; margin-bottom: -2px;"><?php echo htmlspecialchars($username); ?></small>
                    <h1 class="header-title mb-0" style="font-size: 1.25rem;">Add Note</h1>
                </div>
            </div>
            <a href="<?php echo URL_PATH; ?>/logout" class="btn-icon" title="Logout">
                <i class="bi bi-box-arrow-right"></i>
            </a>
        </div>
    </div>
</header>

<main class="pwa-content">
    <div class="container-fluid">
        <form method="POST" action="<?php echo URL_PATH; ?>/add-note" enctype="multipart/form-data" class="needs-validation" novalidate>
            <div class="card mb-3">
                <div class="card-body">
                    <div class="mb-3">
                        <label for="title" class="form-label">Title *</label>
                        <input type="text" class="form-control" id="title" name="title" required>
                        <div class="invalid-feedback">Please enter a title</div>
                    </div>

                    <div class="mb-3">
                        <label for="note_type" class="form-label">Type *</label>
                        <select class="form-select" id="note_type" name="note_type" required>
                            <option value="single">Single (One-time reminder)</option>
                            <option value="regular">Regular (Annual reminder)</option>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label for="reminder_date" class="form-label">Reminder Date *</label>
                        <input type="date" class="form-control" id="reminder_date" name="reminder_date" required>
                        <div class="invalid-feedback">Please select a reminder date</div>
                    </div>

                    <div class="mb-3">
                        <label for="content" class="form-label">Description</label>
                        <textarea class="form-control" id="content" name="content" rows="3"></textarea>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Images</label>
                        
                        <!-- Hidden file inputs -->
                        <input type="file" id="cameraInput" name="images[]" accept="image/*" capture="environment" multiple style="display: none;">
                        <input type="file" id="galleryInput" name="images[]" accept="image/*" multiple style="display: none;">
                        
                        <!-- Image selection buttons -->
                        <div class="d-grid gap-2">
                            <button type="button" class="btn btn-outline-primary" id="addImageBtn">
                                <i class="bi bi-camera me-2"></i>
                                Add Images
                            </button>
                        </div>
                        
                        <small class="text-muted d-block mt-2">
                            <i class="bi bi-info-circle me-1"></i>
                            Max 5MB per image, will be converted to WebP
                        </small>
                    </div>

                    <!-- Image Preview Grid -->
                    <div id="imagePreviewGrid" class="mb-3" style="display: none;">
                        <div class="row g-2" id="previewContainer"></div>
                    </div>

                    <button type="submit" class="btn btn-primary w-100">
                        <i class="bi bi-plus-circle me-2"></i>
                        Add Note
                    </button>
                </div>
            </div>
        </form>
    </div>
</main>

<!-- Image Source Modal -->
<div class="modal fade" id="imageSourceModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="bi bi-images me-2"></i>
                    Choose Image Source
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="d-grid gap-3">
                    <button type="button" class="btn btn-lg btn-outline-primary" id="cameraBtn">
                        <i class="bi bi-camera fs-3 d-block mb-2"></i>
                        <span>Take Photo</span>
                    </button>
                    <button type="button" class="btn btn-lg btn-outline-success" id="galleryBtn">
                        <i class="bi bi-images fs-3 d-block mb-2"></i>
                        <span>Choose from Gallery</span>
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<?php 
$urlPath = URL_PATH;
?>
<script>
    let selectedFiles = [];
    let imageSourceModal;
    
    // Initialize modal
    document.addEventListener('DOMContentLoaded', function() {
        imageSourceModal = new bootstrap.Modal(document.getElementById('imageSourceModal'));
    });
    
    // Form validation
    (function() {
        'use strict';
        const forms = document.querySelectorAll('.needs-validation');
        Array.from(forms).forEach(form => {
            form.addEventListener('submit', event => {
                if (!form.checkValidity()) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                form.classList.add('was-validated');
            }, false);
        });
    })();

    // Show image source modal
    document.getElementById('addImageBtn').addEventListener('click', function() {
        imageSourceModal.show();
    });
    
    // Camera button
    document.getElementById('cameraBtn').addEventListener('click', function() {
        imageSourceModal.hide();
        document.getElementById('cameraInput').click();
    });
    
    // Gallery button
    document.getElementById('galleryBtn').addEventListener('click', function() {
        imageSourceModal.hide();
        document.getElementById('galleryInput').click();
    });
    
    // Handle camera input
    document.getElementById('cameraInput').addEventListener('change', function(e) {
        handleFileSelection(e.target.files);
    });
    
    // Handle gallery input
    document.getElementById('galleryInput').addEventListener('change', function(e) {
        handleFileSelection(e.target.files);
    });
    
    // Handle file selection
    function handleFileSelection(files) {
        if (!files || files.length === 0) return;
        
        // Add new files to selectedFiles array
        Array.from(files).forEach(file => {
            // Check file size (5MB max)
            if (file.size > 5 * 1024 * 1024) {
                alert('File ' + file.name + ' is too large. Max size is 5MB.');
                return;
            }
            
            // Check if file type is image
            if (!file.type.startsWith('image/')) {
                alert('File ' + file.name + ' is not an image.');
                return;
            }
            
            selectedFiles.push(file);
        });
        
        // Update preview
        updateImagePreview();
        
        // Reset file inputs
        document.getElementById('cameraInput').value = '';
        document.getElementById('galleryInput').value = '';
    }
    
    // Update image preview
    function updateImagePreview() {
        const container = document.getElementById('previewContainer');
        const grid = document.getElementById('imagePreviewGrid');
        
        if (selectedFiles.length === 0) {
            grid.style.display = 'none';
            return;
        }
        
        grid.style.display = 'block';
        container.innerHTML = '';
        
        selectedFiles.forEach((file, index) => {
            const reader = new FileReader();
            reader.onload = function(e) {
                const col = document.createElement('div');
                col.className = 'col-6 col-md-4';
                col.innerHTML = `
                    <div class="position-relative">
                        <img src="${e.target.result}" class="img-fluid rounded" style="width: 100%; height: 150px; object-fit: cover;">
                        <button type="button" class="btn btn-danger btn-sm position-absolute top-0 end-0 m-1" onclick="removeImage(${index})">
                            <i class="bi bi-x-lg"></i>
                        </button>
                    </div>
                `;
                container.appendChild(col);
            };
            reader.readAsDataURL(file);
        });
        
        // Update button text
        document.getElementById('addImageBtn').innerHTML = `
            <i class="bi bi-camera me-2"></i>
            Add More Images (${selectedFiles.length} selected)
        `;
    }
    
    // Remove image
    function removeImage(index) {
        selectedFiles.splice(index, 1);
        updateImagePreview();
    }
    
    // Always submit form via AJAX for consistent JSON response
    document.querySelector('form').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        
        // Remove old file inputs
        formData.delete('images[]');
        
        // Add selected files
        selectedFiles.forEach((file, index) => {
            formData.append('images[]', file);
        });
        
        // Submit form via AJAX
        fetch(this.action, {
            method: 'POST',
            body: formData
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            if (data.success) {
                window.location.href = '<?php echo $urlPath; ?>/notes';
            } else {
                alert('Error: ' + (data.message || 'Failed to add note'));
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('An error occurred. Please try again.');
        });
    });
</script>

<?php 
include __DIR__ . '/_footer.php'; 
?>
