<!DOCTYPE html>
<html>
<head>
    <title>Upload Project Files</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
            background: #f5f7fa;
            color: #333;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 2rem;
        }

        .project-info {
            background: white;
            padding: 2rem;
            border-radius: 12px;
            margin-bottom: 2rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }

        .project-info h2 {
            color: #333;
            margin-bottom: 0.5rem;
        }

        .project-info p {
            color: #666;
            margin-bottom: 0.5rem;
        }

        .upload-container {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            margin-bottom: 2rem;
        }

        .upload-area {
            border: 3px dashed #ddd;
            border-radius: 10px;
            padding: 4rem 2rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
            background: #fafafa;
            margin-bottom: 2rem;
        }

        .upload-area:hover {
            border-color: #007bff;
            background: #f0f7ff;
        }

        .upload-area.dragover {
            border-color: #007bff;
            background: #e6f2ff;
        }

        .upload-icon {
            font-size: 4rem;
            color: #007bff;
            margin-bottom: 1rem;
        }

        .upload-text {
            font-size: 1.2rem;
            color: #555;
            margin-bottom: 0.5rem;
        }

        .upload-subtext {
            color: #888;
            font-size: 0.9rem;
        }

        #fileInput {
            display: none;
        }

        .files-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
        }

        .file-item {
            background: #f8f9fa;
            border-radius: 8px;
            overflow: hidden;
            border: 1px solid #eee;
            transition: all 0.3s;
            position: relative;
        }

        .file-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .file-preview {
            height: 150px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #fff;
            overflow: hidden;
        }

        .file-preview img,
        .file-preview video {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
        }

        .file-preview .doc-icon {
            font-size: 3rem;
            color: #007bff;
        }

        .file-info {
            padding: 0.8rem;
        }

        .file-name {
            font-size: 0.85rem;
            color: #333;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            margin-bottom: 0.3rem;
        }

        .file-type {
            font-size: 0.75rem;
            color: #666;
            text-transform: uppercase;
            background: #e9ecef;
            padding: 0.2rem 0.5rem;
            border-radius: 4px;
            display: inline-block;
        }

        .file-actions {
            position: absolute;
            top: 5px;
            right: 5px;
            opacity: 0;
            transition: opacity 0.3s;
        }

        .file-item:hover .file-actions {
            opacity: 1;
        }

        .btn-delete {
            background: #dc3545;
            color: white;
            border: none;
            border-radius: 4px;
            width: 30px;
            height: 30px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .btn-delete:hover {
            background: #c82333;
        }

        .sortable-placeholder {
            border: 2px dashed #007bff;
            background: #e6f2ff;
            border-radius: 8px;
            min-height: 200px;
        }

        .navigation {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 2rem;
            padding-top: 2rem;
            border-top: 1px solid #eee;
        }

        .btn {
            padding: 0.8rem 2rem;
            border: none;
            border-radius: 8px;
            font-size: 0.95rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }

        .btn-primary {
            background: #007bff;
            color: white;
        }

        .btn-primary:hover {
            background: #0056b3;
            transform: translateY(-1px);
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .btn-secondary:hover {
            background: #545b62;
            transform: translateY(-1px);
        }

        .btn-success {
            background: #28a745;
            color: white;
        }

        .btn-success:hover {
            background: #1e7e34;
            transform: translateY(-1px);
        }

        .progress-bar {
            width: 100%;
            height: 4px;
            background: #eee;
            border-radius: 2px;
            margin-top: 1rem;
            overflow: hidden;
            display: none;
        }

        .progress-fill {
            height: 100%;
            background: #007bff;
            width: 0%;
            transition: width 0.3s;
        }
    </style>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://code.jquery.com/ui/1.13.0/jquery-ui.min.js"></script>
</head>
<body>
    <div class="container">
        <div class="project-info">
            <h2><?php echo $project->title; ?></h2>
            <p><strong>Client:</strong> <?php echo $project->client_name; ?></p>
            <p><strong>Date:</strong> <?php echo date('F d, Y', strtotime($project->shoot_date)); ?></p>
            <p><?php echo nl2br($project->description); ?></p>
        </div>

        <div class="upload-container">
            <h3 style="margin-bottom: 1.5rem; color: #333;">Step 2: Upload Project Files</h3>
            
            <div class="upload-area" id="uploadArea">
                <div class="upload-icon">
                    📁
                </div>
                <div class="upload-text">Drag & Drop files here or click to browse</div>
                <div class="upload-subtext">Supports images (JPG, PNG, GIF, WebP), videos (MP4, MOV, AVI), and documents (PDF, DOC)</div>
                <div class="progress-bar" id="progressBar">
                    <div class="progress-fill" id="progressFill"></div>
                </div>
                <input type="file" id="fileInput" multiple>
            </div>

            <div class="files-grid" id="filesGrid">
                <?php if (!empty($project_files)): ?>
                    <?php foreach ($project_files as $file): ?>
                        <div class="file-item" data-file-id="<?php echo $file->id; ?>">
                            <div class="file-preview">
                                <?php if ($file->file_type == 'image'): ?>
                                    <img src="<?php echo base_url($file->file_path); ?>" alt="Preview">
                                <?php elseif ($file->file_type == 'video'): ?>
                                    <video muted>
                                        <source src="<?php echo base_url($file->file_path); ?>" type="video/mp4">
                                    </video>
                                <?php else: ?>
                                    <div class="doc-icon">📄</div>
                                <?php endif; ?>
                            </div>
                            <div class="file-info">
                                <div class="file-name"><?php echo basename($file->file_path); ?></div>
                                <span class="file-type"><?php echo $file->file_type; ?></span>
                            </div>
                            <div class="file-actions">
                                <button class="btn-delete" onclick="deleteFile(<?php echo $file->id; ?>)">×</button>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div style="grid-column: 1/-1; text-align: center; padding: 3rem; color: #999;">
                        No files uploaded yet. Drag and drop files above to upload.
                    </div>
                <?php endif; ?>
            </div>

            <div class="navigation">
                <a href="<?php echo base_url('admin/projects_enhanced'); ?>" class="btn btn-secondary">
                    ← Back to Projects
                </a>
                
                <div style="display: flex; gap: 1rem;">
                    <a href="<?php echo base_url('admin/project_cover_editor/' . $project->id); ?>" class="btn btn-success">
                        Next: Design Cover →
                    </a>
                </div>
            </div>
        </div>
    </div>

    <script>
        const projectId = <?php echo $project->id; ?>;
        
        // Drag and drop functionality
        const uploadArea = document.getElementById('uploadArea');
        const fileInput = document.getElementById('fileInput');
        const progressBar = document.getElementById('progressBar');
        const progressFill = document.getElementById('progressFill');
        
        uploadArea.addEventListener('click', () => fileInput.click());
        
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('dragover');
        });
        
        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('dragover');
        });
        
        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('dragover');
            handleFiles(e.dataTransfer.files);
        });
        
        fileInput.addEventListener('change', (e) => {
            handleFiles(e.target.files);
            fileInput.value = '';
        });
        
        // Make files sortable
        $(function() {
            $("#filesGrid").sortable({
                placeholder: "sortable-placeholder",
                update: function(event, ui) {
                    saveFileOrder();
                }
            });
            $("#filesGrid").disableSelection();
        });
        
        // Handle file uploads
        function handleFiles(files) {
            if (files.length === 0) return;
            
            progressBar.style.display = 'block';
            progressFill.style.width = '0%';
            
            let uploaded = 0;
            
            Array.from(files).forEach((file, index) => {
                const formData = new FormData();
                formData.append('file', file);
                
                const xhr = new XMLHttpRequest();
                
                xhr.upload.onprogress = (e) => {
                    if (e.lengthComputable) {
                        const percentComplete = ((uploaded + (e.loaded / e.total)) / files.length) * 100;
                        progressFill.style.width = percentComplete + '%';
                    }
                };
                
                xhr.onload = () => {
                    uploaded++;
                    
                    if (xhr.status === 200) {
                        const response = JSON.parse(xhr.responseText);
                        if (response.success) {
                            addFileToGrid(response);
                        } else {
                            alert('Error uploading ' + file.name + ': ' + response.message);
                        }
                    }
                    
                    if (uploaded === files.length) {
                        setTimeout(() => {
                            progressBar.style.display = 'none';
                            progressFill.style.width = '0%';
                        }, 1000);
                        
                        saveFileOrder();
                    }
                };
                
                xhr.open('POST', '<?php echo base_url("admin/upload_project_files/"); ?>' + projectId);
                xhr.send(formData);
            });
        }
        
        // Add file to grid
        function addFileToGrid(fileData) {
            const fileType = fileData.file_type;
            let previewHTML = '';
            
            if (fileType === 'image') {
                previewHTML = `<img src="${fileData.file_path}" alt="Preview">`;
            } else if (fileType === 'video') {
                previewHTML = `<video muted><source src="${fileData.file_path}" type="video/mp4"></video>`;
            } else {
                previewHTML = '<div class="doc-icon">📄</div>';
            }
            
            const fileHTML = `
                <div class="file-item" data-file-id="${fileData.file_id}">
                    <div class="file-preview">
                        ${previewHTML}
                    </div>
                    <div class="file-info">
                        <div class="file-name">${fileData.file_name}</div>
                        <span class="file-type">${fileType}</span>
                    </div>
                    <div class="file-actions">
                        <button class="btn-delete" onclick="deleteFile(${fileData.file_id})">×</button>
                    </div>
                </div>
            `;
            
            document.getElementById('filesGrid').innerHTML = fileHTML + document.getElementById('filesGrid').innerHTML;
        }
        
        // Delete file
        function deleteFile(fileId) {
            if (!confirm('Are you sure you want to delete this file?')) return;
            
            fetch('<?php echo base_url("admin/delete_project_file/"); ?>' + fileId, {
                method: 'POST',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    document.querySelector(`[data-file-id="${fileId}"]`).remove();
                    saveFileOrder();
                }
            });
        }
        
        // Save file order
        function saveFileOrder() {
            const fileOrder = [];
            $('#filesGrid .file-item').each(function(index) {
                fileOrder.push($(this).data('file-id'));
            });
            
            fetch('<?php echo base_url("admin/update_files_order/"); ?>' + projectId, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: JSON.stringify({ files_order: fileOrder })
            });
        }
    </script>
</body>
</html>