<?php
/**
 * Public Client File Upload Page
 *
 * @package Freelance_Studio
 */

if (!defined('ABSPATH')) {
    exit;
}
?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
    <meta charset="<?php bloginfo('charset'); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <?php /* translators: 1. files - value */ ?>
    <title><?php echo esc_html(sprintf(__('Upload Files - %s', 'freelance-studio'), $project->name)); ?></title>
    <style>
        :root {
            --brand-color: <?php echo esc_attr($brand_color); ?>;
            --brand-color-dark: <?php echo esc_attr(self::darken_color($brand_color, 15)); ?>;
        }
        
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
            background: #f5f7fa;
            color: #374151;
            line-height: 1.5;
            min-height: 100vh;
        }
        
        .upload-page {
            max-width: 700px;
            margin: 0 auto;
            padding: 40px 20px;
        }
        
        .upload-header {
            text-align: center;
            margin-bottom: 32px;
        }
        
        .business-name {
            font-size: 14px;
            color: #6B7280;
            margin-bottom: 8px;
        }
        
        .project-name {
            font-size: 24px;
            font-weight: 600;
            color: #1F2937;
            margin-bottom: 8px;
        }
        
        .upload-subtitle {
            font-size: 15px;
            color: #6B7280;
        }
        
        .upload-card {
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
            padding: 32px;
            margin-bottom: 24px;
        }
        
        .dropzone {
            border: 2px dashed #D1D5DB;
            border-radius: 12px;
            padding: 48px 24px;
            text-align: center;
            cursor: pointer;
            transition: all 0.2s;
            background: #FAFBFC;
        }
        
        .dropzone:hover,
        .dropzone.active {
            border-color: var(--brand-color);
            background: rgba(31, 187, 166, 0.05);
        }
        
        .dropzone-icon {
            font-size: 48px;
            margin-bottom: 16px;
            color: #9CA3AF;
        }
        
        .dropzone:hover .dropzone-icon,
        .dropzone.active .dropzone-icon {
            color: var(--brand-color);
        }
        
        .dropzone-text {
            font-size: 16px;
            color: #374151;
            margin-bottom: 8px;
        }
        
        .dropzone-hint {
            font-size: 13px;
            color: #9CA3AF;
        }
        
        .upload-queue {
            margin-top: 24px;
        }
        
        .upload-item {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            background: #F9FAFB;
            border-radius: 8px;
            margin-bottom: 8px;
        }
        
        .upload-item-name {
            flex: 1;
            font-size: 14px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        
        .upload-item-size {
            font-size: 13px;
            color: #6B7280;
        }
        
        .upload-item-status {
            width: 24px;
            text-align: center;
        }
        
        .spinner {
            width: 20px;
            height: 20px;
            border: 2px solid #E5E7EB;
            border-top-color: var(--brand-color);
            border-radius: 50%;
            animation: spin 0.8s linear infinite;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        .success-icon {
            color: var(--brand-color);
            font-size: 20px;
        }
        
        .error-icon {
            color: #EF4444;
            font-size: 20px;
        }
        
        .section-title {
            font-size: 16px;
            font-weight: 600;
            color: #1F2937;
            margin-bottom: 16px;
        }
        
        .files-list {
            border: 1px solid #E5E7EB;
            border-radius: 8px;
            overflow: hidden;
        }
        
        .file-row {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            border-bottom: 1px solid #E5E7EB;
        }
        
        .file-row:last-child {
            border-bottom: none;
        }
        
        .file-icon {
            font-size: 24px;
            color: #9CA3AF;
        }
        
        .file-info {
            flex: 1;
        }
        
        .file-name {
            font-size: 14px;
            color: #374151;
            font-weight: 500;
        }
        
        .file-meta {
            font-size: 12px;
            color: #9CA3AF;
            margin-top: 2px;
        }
        
        .empty-state {
            text-align: center;
            padding: 32px;
            color: #9CA3AF;
        }
        
        .empty-state-icon {
            font-size: 32px;
            margin-bottom: 8px;
        }
        
        .footer-note {
            text-align: center;
            font-size: 13px;
            color: #9CA3AF;
            margin-top: 24px;
        }
        
        /* Hide file input */
        #file-input {
            display: none;
        }
        
        /* Upload message */
        .upload-message {
            padding: 16px 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 14px;
            font-weight: 500;
            text-align: center;
        }
        
        .upload-message.success {
            background: #D1FAE5;
            color: #065F46;
            border: 1px solid #6EE7B7;
        }
        
        .upload-message.error {
            background: #FEE2E2;
            color: #991B1B;
            border: 1px solid #FCA5A5;
        }
        
        /* New file highlight animation */
        .file-row-new {
            animation: highlightNew 2s ease-out;
        }
        
        @keyframes highlightNew {
            0% {
                background-color: #D1FAE5;
            }
            100% {
                background-color: transparent;
            }
        }
    </style>
</head>
<body>
    <div class="upload-page">
        <div class="upload-header">
            <div class="business-name"><?php echo esc_html($business_name); ?></div>
            <h1 class="project-name"><?php echo esc_html($project->name); ?></h1>
            <p class="upload-subtitle"><?php esc_html_e('Upload files for this project', 'freelance-studio'); ?></p>
        </div>
        
        <div class="upload-card">
            <div class="dropzone" id="dropzone">
                <div class="dropzone-icon">📁</div>
                <p class="dropzone-text"><?php esc_html_e('Drag & drop files here, or click to select', 'freelance-studio'); ?></p>
                <p class="dropzone-hint"><?php esc_html_e('Maximum file size: 32MB', 'freelance-studio'); ?></p>
            </div>
            <input type="file" id="file-input" multiple>
            
            <div class="upload-queue" id="upload-queue"></div>
        </div>
        
        <?php if (!empty($enriched_files)): ?>
        <div class="upload-card">
            <h3 class="section-title"><?php esc_html_e('Your Uploaded Files', 'freelance-studio'); ?></h3>
            <div class="files-list">
                <?php foreach ($enriched_files as $file): ?>
                <div class="file-row">
                    <span class="file-icon">📄</span>
                    <div class="file-info">
                        <div class="file-name"><?php echo esc_html($file->filename ?? __('Unknown file', 'freelance-studio')); ?></div>
                        <div class="file-meta">
                            <?php echo esc_html($file->filesize_formatted ?? ''); ?> • 
                            <?php echo esc_html(date_i18n(get_option('date_format'), strtotime($file->created_at))); ?>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php else: ?>
        <div class="upload-card">
            <h3 class="section-title"><?php esc_html_e('Your Uploaded Files', 'freelance-studio'); ?></h3>
            <div class="empty-state">
                <div class="empty-state-icon">📭</div>
                <p><?php esc_html_e('No files uploaded yet.', 'freelance-studio'); ?></p>
            </div>
        </div>
        <?php endif; ?>
        
        <p class="footer-note">
            <?php /* translators: 1. recipient name */ ?>
            <?php echo esc_html(sprintf(__('This upload link expires on %s', 'freelance-studio'), date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($token_record->expires_at)))); ?>
        </p>
    </div>
    
    <script>
    (function() {
        const dropzone = document.getElementById('dropzone');
        const fileInput = document.getElementById('file-input');
        const uploadQueue = document.getElementById('upload-queue');
        const token = '<?php echo esc_js($token); ?>';
        const ajaxUrl = '<?php echo esc_url(admin_url('admin-ajax.php')); ?>';
        
        // Click to select files
        dropzone.addEventListener('click', function() {
            fileInput.click();
        });
        
        // Drag and drop handlers
        dropzone.addEventListener('dragover', function(e) {
            e.preventDefault();
            e.stopPropagation();
            this.classList.add('active');
        });
        
        dropzone.addEventListener('dragleave', function(e) {
            e.preventDefault();
            e.stopPropagation();
            this.classList.remove('active');
        });
        
        dropzone.addEventListener('drop', function(e) {
            e.preventDefault();
            e.stopPropagation();
            this.classList.remove('active');
            handleFiles(e.dataTransfer.files);
        });
        
        fileInput.addEventListener('change', function() {
            handleFiles(this.files);
            this.value = '';
        });
        
        function handleFiles(files) {
            Array.from(files).forEach(function(file) {
                uploadFile(file);
            });
        }
        
        function uploadFile(file) {
            // Create upload item
            const item = document.createElement('div');
            item.className = 'upload-item';
            item.innerHTML = `
                <span class="upload-item-name">${escapeHtml(file.name)}</span>
                <span class="upload-item-size">${formatFileSize(file.size)}</span>
                <span class="upload-item-status"><div class="spinner"></div></span>
            `;
            uploadQueue.appendChild(item);
            
            // Create FormData
            const formData = new FormData();
            formData.append('action', 'fs_client_upload_file');
            formData.append('token', token);
            formData.append('file', file);
            
            // Upload
            fetch(ajaxUrl, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                console.log('Upload response:', data);
                if (data.success) {
                    item.querySelector('.upload-item-status').innerHTML = '<span class="success-icon">✓</span>';
                    // Show success message
                    showMessage('<?php esc_html_e('File uploaded successfully!', 'freelance-studio'); ?>', 'success');
                    // Add file to the list dynamically
                    addFileToList(data.data.file);
                } else {
                    item.querySelector('.upload-item-status').innerHTML = '<span class="error-icon">✗</span>';
                    const errorMsg = data.data && data.data.message ? data.data.message : 'Upload failed';
                    showMessage(errorMsg, 'error');
                    console.error('Upload error:', errorMsg);
                }
            })
            .catch(function(error) {
                console.error('Upload fetch error:', error);
                item.querySelector('.upload-item-status').innerHTML = '<span class="error-icon">✗</span>';
                showMessage('<?php esc_html_e('Upload failed. Please try again.', 'freelance-studio'); ?>', 'error');
            });
        }
        
        function addFileToList(file) {
            // Get or create the files list section
            let filesCard = document.querySelector('.files-list');
            const emptyState = document.querySelector('.empty-state');
            
            // If empty state exists, replace with files list
            if (emptyState) {
                const emptyCard = emptyState.closest('.upload-card');
                emptyCard.querySelector('.empty-state').remove();
                
                const filesList = document.createElement('div');
                filesList.className = 'files-list';
                emptyCard.querySelector('.section-title').after(filesList);
                filesCard = filesList;
            }
            
            // Create new file row
            const fileRow = document.createElement('div');
            fileRow.className = 'file-row file-row-new';
            fileRow.innerHTML = `
                <span class="file-icon">📄</span>
                <div class="file-info">
                    <div class="file-name">${escapeHtml(file.filename || 'Uploaded file')}</div>
                    <div class="file-meta">
                        ${escapeHtml(file.filesize_formatted || '')} • <?php echo esc_html(date_i18n(get_option('date_format'))); ?>
                    </div>
                </div>
            `;
            
            // Add to top of list
            if (filesCard.firstChild) {
                filesCard.insertBefore(fileRow, filesCard.firstChild);
            } else {
                filesCard.appendChild(fileRow);
            }
            
            // Highlight animation
            setTimeout(() => fileRow.classList.remove('file-row-new'), 2000);
        }
        
        function showMessage(text, type) {
            // Remove existing message
            const existing = document.querySelector('.upload-message');
            if (existing) existing.remove();
            
            const msg = document.createElement('div');
            msg.className = 'upload-message ' + type;
            msg.textContent = text;
            document.querySelector('.upload-page').insertBefore(msg, document.querySelector('.upload-card'));
            
            // Auto-hide after 8 seconds for success
            if (type === 'success') {
                setTimeout(() => msg.remove(), 8000);
            }
        }
        
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
        
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
    })();
    </script>
</body>
</html>
