<?php
/**
 * Upload Management
 * Manage uploaded files for cases
 */

require_once '../../config/config.php';
require_once '../../includes/auth.php';
require_once '../../includes/upload-handler.php';

requireLogin();

$pdo = getDB();
$userId = $_SESSION['user_id'];
$caseId = isset($_GET['case_id']) ? (int)$_GET['case_id'] : 0;
$message = '';
$error = '';

// Get case details
$case = null;
if ($caseId) {
    $stmt = $pdo->prepare("SELECT * FROM cases WHERE id = ? AND user_id = ?");
    $stmt->execute([$caseId, $userId]);
    $case = $stmt->fetch();
}

// Get attachments for case
$attachments = [];
if ($caseId) {
    $stmt = $pdo->prepare("SELECT * FROM case_attachments WHERE case_id = ? ORDER BY uploaded_at DESC");
    $stmt->execute([$caseId]);
    $attachments = $stmt->fetchAll();
}

// Handle delete request
if (isset($_GET['delete'])) {
    $attachmentId = (int)$_GET['delete'];
    $stmt = $pdo->prepare("SELECT * FROM case_attachments WHERE id = ? AND case_id IN (SELECT id FROM cases WHERE user_id = ?)");
    $stmt->execute([$attachmentId, $userId]);
    $attachment = $stmt->fetch();
    
    if ($attachment) {
        $uploader = getUploadHandler();
        $uploader->delete('assets/uploads/cases/' . $caseId . '/' . $attachment['filename']);
        
        $stmt = $pdo->prepare("DELETE FROM case_attachments WHERE id = ?");
        $stmt->execute([$attachmentId]);
        $message = "File deleted successfully!";
        header("Location: manage.php?case_id=$caseId&msg=" . urlencode($message));
        exit;
    }
}

if (isset($_GET['msg'])) {
    $message = $_GET['msg'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upload Management - <?php echo APP_NAME; ?></title>
    <link href="../../assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="../../assets/vendor/fontawesome/css/all.min.css" rel="stylesheet">
    <style>
        .upload-area {
            border: 2px dashed #ccc;
            border-radius: 10px;
            padding: 30px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
            background: #f8f9fa;
        }
        .upload-area:hover, .upload-area.dragover {
            border-color: #2ecc71;
            background: #e8f5e9;
        }
        .file-item {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 12px;
            margin-bottom: 10px;
            transition: all 0.2s;
        }
        .file-item:hover {
            background: #e9ecef;
            transform: translateX(5px);
        }
        .file-icon {
            font-size: 24px;
            width: 40px;
            text-align: center;
        }
        .upload-progress {
            display: none;
            margin-top: 15px;
        }
        @media (max-width: 768px) {
            .file-actions {
                margin-top: 10px;
            }
        }
    </style>
</head>
<body>
    <div class="container mt-4">
        <div class="card">
            <div class="card-header">
                <h4><i class="fas fa-upload"></i> File Management</h4>
                <?php if ($case): ?>
                    <p class="mb-0">Case: <?php echo htmlspecialchars($case['patient_name']); ?> (ID: <?php echo $caseId; ?>)</p>
                <?php endif; ?>
            </div>
            <div class="card-body">
                <?php if ($message): ?>
                    <div class="alert alert-success"><?php echo htmlspecialchars($message); ?></div>
                <?php endif; ?>
                
                <?php if ($caseId): ?>
                    <!-- Upload Area -->
                    <div class="upload-area" id="dropZone">
                        <i class="fas fa-cloud-upload-alt fa-3x mb-3 text-muted"></i>
                        <p>Drag & drop files here or click to upload</p>
                        <small class="text-muted">Max file size: 5MB | Allowed: Images, PDF, DOC</small>
                        <input type="file" id="fileInput" style="display: none;" multiple>
                        <button class="btn btn-primary mt-3" onclick="document.getElementById('fileInput').click()">
                            <i class="fas fa-folder-open"></i> Browse Files
                        </button>
                    </div>
                    
                    <!-- Upload Progress -->
                    <div class="upload-progress" id="uploadProgress">
                        <div class="progress">
                            <div class="progress-bar progress-bar-striped progress-bar-animated" style="width: 0%"></div>
                        </div>
                        <p class="mt-2 text-center" id="uploadStatus">Uploading...</p>
                    </div>
                    
                    <!-- Attachments List -->
                    <h5 class="mt-4"><i class="fas fa-paperclip"></i> Attachments (<?php echo count($attachments); ?>)</h5>
                    <div id="attachmentsList">
                        <?php if (empty($attachments)): ?>
                            <p class="text-muted text-center py-3">No attachments yet</p>
                        <?php else: ?>
                            <?php foreach ($attachments as $attachment): ?>
                                <?php
                                $uploader = getUploadHandler();
                                $fileIcon = $uploader->getFileIcon($attachment['mime_type']);
                                $fileSize = $uploader->getFileSize('assets/uploads/cases/' . $caseId . '/' . $attachment['filename']);
                                ?>
                                <div class="file-item" data-id="<?php echo $attachment['id']; ?>">
                                    <div class="row align-items-center">
                                        <div class="col-md-1 file-icon">
                                            <i class="fas <?php echo $fileIcon; ?>"></i>
                                        </div>
                                        <div class="col-md-5">
                                            <strong><?php echo htmlspecialchars($attachment['original_name']); ?></strong><br>
                                            <small class="text-muted"><?php echo $fileSize; ?> | <?php echo date('d-m-Y H:i', strtotime($attachment['uploaded_at'])); ?></small>
                                        </div>
                                        <div class="col-md-3">
                                            <span class="badge bg-secondary"><?php echo strtoupper(pathinfo($attachment['filename'], PATHINFO_EXTENSION)); ?></span>
                                        </div>
                                        <div class="col-md-3 text-end file-actions">
                                            <a href="../../assets/uploads/cases/<?php echo $caseId; ?>/<?php echo $attachment['filename']; ?>" class="btn btn-sm btn-info" target="_blank">
                                                <i class="fas fa-eye"></i> View
                                            </a>
                                            <a href="manage.php?case_id=<?php echo $caseId; ?>&delete=<?php echo $attachment['id']; ?>" 
                                               class="btn btn-sm btn-danger" onclick="return confirm('Delete this file?')">
                                                <i class="fas fa-trash"></i> Delete
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                <?php else: ?>
                    <div class="alert alert-warning">
                        <i class="fas fa-exclamation-triangle"></i> No case selected. Please select a case to manage attachments.
                    </div>
                    <a href="../cases/list.php" class="btn btn-primary">Go to Cases</a>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <script src="../../assets/vendor/jquery/jquery.min.js"></script>
    <script>
        const dropZone = document.getElementById('dropZone');
        const fileInput = document.getElementById('fileInput');
        const uploadProgress = document.getElementById('uploadProgress');
        const progressBar = uploadProgress.querySelector('.progress-bar');
        const uploadStatus = document.getElementById('uploadStatus');
        
        // Click to browse
        dropZone.addEventListener('click', () => fileInput.click());
        
        // Drag and drop
        dropZone.addEventListener('dragover', (e) => {
            e.preventDefault();
            dropZone.classList.add('dragover');
        });
        
        dropZone.addEventListener('dragleave', () => {
            dropZone.classList.remove('dragover');
        });
        
        dropZone.addEventListener('drop', (e) => {
            e.preventDefault();
            dropZone.classList.remove('dragover');
            const files = e.dataTransfer.files;
            handleFiles(files);
        });
        
        // File input change
        fileInput.addEventListener('change', (e) => {
            handleFiles(e.target.files);
        });
        
        function handleFiles(files) {
            if (files.length === 0) return;
            
            uploadProgress.style.display = 'block';
            progressBar.style.width = '0%';
            
            let completed = 0;
            const total = files.length;
            
            Array.from(files).forEach((file, index) => {
                uploadFile(file, index, () => {
                    completed++;
                    progressBar.style.width = (completed / total * 100) + '%';
                    uploadStatus.textContent = `Uploaded ${completed} of ${total} files`;
                    
                    if (completed === total) {
                        setTimeout(() => {
                            uploadProgress.style.display = 'none';
                            location.reload();
                        }, 1000);
                    }
                });
            });
        }
        
        function uploadFile(file, index, callback) {
            const formData = new FormData();
            formData.append('file', file);
            formData.append('type', 'cases');
            formData.append('case_id', '<?php echo $caseId; ?>');
            
            $.ajax({
                url: '../../api/upload.php',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    if (response.success) {
                        callback();
                    } else {
                        console.error('Upload failed:', response.error);
                        uploadStatus.textContent = `Error: ${response.error}`;
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Upload error:', error);
                    uploadStatus.textContent = `Error: ${error}`;
                }
            });
        }
    </script>
</body>
</html>