<?php
session_start();
include 'layouts/session.php';
include 'layouts/main.php';
include 'layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$doctor_id = $_SESSION['user_id'];
$patient_id = $_GET['patient_id'] ?? 0;

// Get patient details
$patient = null;
if ($patient_id > 0) {
    $patient_query = "SELECT p.*, u.full_name FROM patients p
                     INNER JOIN users u ON p.user_id = u.user_id
                     WHERE p.patient_id = ?";
    $patient_stmt = $conn->prepare($patient_query);
    $patient_stmt->bind_param("i", $patient_id);
    $patient_stmt->execute();
    $patient = $patient_stmt->get_result()->fetch_assoc();
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $conn->begin_transaction();
    
    try {
        $patient_id = $_POST['patient_id'];
        $document_type = $_POST['document_type'];
        $document_name = $_POST['document_name'];
        $description = $_POST['description'] ?? null;
        
        // Handle file upload
        if (!isset($_FILES['document_file'])) {
            throw new Exception("No file was uploaded");
        }
        
        $file = $_FILES['document_file'];
        
        // Check for upload errors
        if ($file['error'] !== UPLOAD_ERR_OK) {
            $error_messages = [
                UPLOAD_ERR_INI_SIZE => 'File exceeds upload_max_filesize directive',
                UPLOAD_ERR_FORM_SIZE => 'File exceeds MAX_FILE_SIZE directive',
                UPLOAD_ERR_PARTIAL => 'File was only partially uploaded',
                UPLOAD_ERR_NO_FILE => 'No file was uploaded',
                UPLOAD_ERR_NO_TMP_DIR => 'Missing temporary folder',
                UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk',
                UPLOAD_ERR_EXTENSION => 'File upload stopped by extension'
            ];
            $error_msg = $error_messages[$file['error']] ?? 'Unknown upload error';
            throw new Exception("Upload error: " . $error_msg);
        }
        
        $file_name = $file['name'];
        $file_size = $file['size'];
        $file_tmp = $file['tmp_name'];
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
        
        // Allowed extensions
        $allowed_extensions = ['pdf', 'jpg', 'jpeg', 'png', 'doc', 'docx'];
        
        if (!in_array($file_ext, $allowed_extensions)) {
            throw new Exception("Invalid file type. Allowed: PDF, JPG, PNG, DOC, DOCX");
        }
        
        // Max file size 10MB
        if ($file_size > 10485760) {
            throw new Exception("File size exceeds 10MB limit");
        }
        
        // Validate file actually exists
        if (!is_uploaded_file($file_tmp)) {
            throw new Exception("Invalid file upload");
        }
        
        // Create upload directory if not exists
        $upload_base = 'uploads/medical_documents/';
        $upload_dir = $upload_base . $patient_id . '/';
        
        // Create base directory if it doesn't exist
        if (!file_exists($upload_base)) {
            if (!mkdir($upload_base, 0755, true)) {
                throw new Exception("Failed to create upload directory");
            }
        }
        
        // Create patient-specific directory if it doesn't exist
        if (!file_exists($upload_dir)) {
            if (!mkdir($upload_dir, 0755, true)) {
                throw new Exception("Failed to create patient upload directory");
            }
        }
        
        // Generate unique filename
        $new_filename = uniqid() . '_' . time() . '.' . $file_ext;
        $file_path = $upload_dir . $new_filename;
            
            if (move_uploaded_file($file_tmp, $file_path)) {
                // Insert into database - using correct table and column names
                $sql = "INSERT INTO medical_documents (
                    patient_id, created_by, document_type, document_title, 
                    document_description, file_path, file_name, file_size, file_type
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
                
                $stmt = $conn->prepare($sql);
                if (!$stmt) {
                    throw new Exception("Database error: " . $conn->error);
                }
                
                $stmt->bind_param("iisssssis", 
                    $patient_id, 
                    $_SESSION['user_id'], 
                    $document_type, 
                    $document_name,
                    $description, 
                    $file_path, 
                    $new_filename, 
                    $file_size, 
                    $file_ext
                );
                
                if (!$stmt->execute()) {
                    throw new Exception("Failed to insert document: " . $stmt->error);
                }
                
                $document_id = $conn->insert_id;
                
                // Log activity
                $action = "UPLOAD";
                $module = "MEDICAL_DOCUMENTS";
                $ip_address = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
                
                $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, ip_address, logged_at) 
                            VALUES (?, ?, ?, ?, 'DOCUMENT', ?, NOW())";
                $log_stmt = $conn->prepare($log_sql);
                if ($log_stmt) {
                    $log_stmt->bind_param("issis", $_SESSION['user_id'], $action, $module, $document_id, $ip_address);
                    $log_stmt->execute();
                }
                
                $conn->commit();
                
                $_SESSION['success_message'] = "Document uploaded successfully!";
                header('Location: patient_documents.php?patient_id=' . $patient_id);
                exit();
            } else {
                throw new Exception("Failed to upload file");
            }
        
    } catch (Exception $e) {
        $conn->rollback();
        $_SESSION['error_message'] = "Error uploading document: " . $e->getMessage();
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Upload Document')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/select2/css/select2.min.css" rel="stylesheet" type="text/css" />
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <style>
        .upload-area {
            border: 2px dashed #2d7a2d;
            border-radius: 8px;
            padding: 3rem;
            text-align: center;
            background: #f8fef8;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .upload-area:hover {
            background: #e8f5e9;
            border-color: #26a69a;
        }
        
        .upload-area.drag-over {
            background: #e8f5e9;
            border-color: #26a69a;
            transform: scale(1.02);
        }
        
        .file-preview {
            display: none;
            margin-top: 1rem;
            padding: 1rem;
            background: white;
            border: 1px solid #dee2e6;
            border-radius: 6px;
        }
        
        .file-icon {
            font-size: 3rem;
            color: #2d7a2d;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Upload Document</h4>
                                <div class="page-title-right">
                                    <a href="patient_documents.php?patient_id=<?php echo $patient_id; ?>" class="btn btn-secondary">
                                        <i class="ri-arrow-left-line"></i> Back
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>

                    <?php if ($patient): ?>
                    <!-- Patient Info Bar -->
                    <div class="row mb-3">
                        <div class="col-12">
                            <div class="card" style="background: linear-gradient(135deg, #2d7a2d, #26a69a); color: white;">
                                <div class="card-body">
                                    <h5 class="text-white mb-1"><?php echo htmlspecialchars($patient['full_name']); ?></h5>
                                    <p class="text-white-50 mb-0">
                                        <strong>Patient ID:</strong> <?php echo $patient['patient_number']; ?>
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <form method="POST" enctype="multipart/form-data" id="uploadForm">
                        <div class="row">
                            <div class="col-lg-8">
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="card-title mb-0">Document Information</h5>
                                    </div>
                                    <div class="card-body">
                                        <?php if (!$patient): ?>
                                        <div class="mb-3">
                                            <label class="form-label">Patient <span class="text-danger">*</span></label>
                                            <select class="form-select select2" name="patient_id" id="patientSelect" required>
                                                <option value="">Select Patient</option>
                                            </select>
                                        </div>
                                        <?php else: ?>
                                        <input type="hidden" name="patient_id" value="<?php echo $patient_id; ?>">
                                        <?php endif; ?>

                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Document Type <span class="text-danger">*</span></label>
                                                <select class="form-select" name="document_type" required>
                                                    <option value="">Select Type</option>
                                                    <option value="MEDICAL_REPORT">Medical Report</option>
                                                    <option value="LAB_RESULT">Lab Result</option>
                                                    <option value="IMAGING">Imaging (X-Ray, CT, MRI)</option>
                                                    <option value="PRESCRIPTION">Prescription</option>
                                                    <option value="CONSENT_FORM">Consent Form</option>
                                                    <option value="INSURANCE">Insurance Document</option>
                                                    <option value="REFERRAL">Referral Letter</option>
                                                    <option value="OTHER">Other</option>
                                                </select>
                                            </div>

                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Document Name <span class="text-danger">*</span></label>
                                                <input type="text" class="form-control" name="document_name" 
                                                       placeholder="e.g., Audiometry Test Result" required>
                                            </div>

                                            <div class="col-md-12 mb-3">
                                                <label class="form-label">Description</label>
                                                <textarea class="form-control" name="description" rows="3"
                                                          placeholder="Additional notes about this document..."></textarea>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Upload Area -->
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="card-title mb-0">Upload File</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="upload-area" id="uploadArea">
                                            <div class="file-icon">
                                                <i class="ri-upload-cloud-line"></i>
                                            </div>
                                            <h5 class="mt-3">Drag & Drop file here</h5>
                                            <p class="text-muted">or click to browse</p>
                                            <input type="file" name="document_file" id="fileInput" 
                                                   accept=".pdf,.jpg,.jpeg,.png,.doc,.docx" 
                                                   style="display: none;" required>
                                            <button type="button" class="btn btn-primary mt-2" id="browseBtn">
                                                <i class="ri-folder-line me-1"></i> Browse Files
                                            </button>
                                        </div>

                                        <div class="file-preview" id="filePreview">
                                            <div class="d-flex align-items-center">
                                                <i class="ri-file-line fs-2 me-3 text-primary"></i>
                                                <div class="flex-grow-1">
                                                    <h6 class="mb-1" id="fileName"></h6>
                                                    <p class="text-muted mb-0" id="fileSize"></p>
                                                </div>
                                                <button type="button" class="btn btn-sm btn-danger" id="removeFile">
                                                    <i class="ri-close-line"></i>
                                                </button>
                                            </div>
                                        </div>

                                        <div class="alert alert-info mt-3">
                                            <strong>Accepted formats:</strong> PDF, JPG, PNG, DOC, DOCX<br>
                                            <strong>Maximum size:</strong> 10MB
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-lg-4">
                                <!-- Guidelines -->
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="card-title mb-0">Upload Guidelines</h5>
                                    </div>
                                    <div class="card-body">
                                        <ul class="list-unstyled mb-0">
                                            <li class="mb-2">
                                                <i class="ri-checkbox-circle-line text-success me-2"></i>
                                                Ensure document is clear and readable
                                            </li>
                                            <li class="mb-2">
                                                <i class="ri-checkbox-circle-line text-success me-2"></i>
                                                Remove any personal information if not needed
                                            </li>
                                            <li class="mb-2">
                                                <i class="ri-checkbox-circle-line text-success me-2"></i>
                                                Use descriptive names for easy identification
                                            </li>
                                            <li class="mb-2">
                                                <i class="ri-checkbox-circle-line text-success me-2"></i>
                                                Verify document belongs to correct patient
                                            </li>
                                            <li class="mb-2">
                                                <i class="ri-checkbox-circle-line text-success me-2"></i>
                                                PDF format is recommended for reports
                                            </li>
                                        </ul>
                                    </div>
                                </div>

                                <!-- Submit Button -->
                                <div class="card">
                                    <div class="card-body">
                                        <div class="d-grid gap-2">
                                            <button type="submit" class="btn btn-success btn-lg" id="submitBtn" disabled>
                                                <i class="ri-upload-line me-1"></i> Upload Document
                                            </button>
                                            <a href="patient_documents.php?patient_id=<?php echo $patient_id; ?>" class="btn btn-secondary btn-lg">
                                                <i class="ri-close-line me-1"></i> Cancel
                                            </a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/select2/js/select2.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="assets/js/app.js"></script>
    
    <script>
        $(document).ready(function() {
            $('.select2').select2({
                width: '100%'
            });

            <?php if (!$patient): ?>
            $.ajax({
                url: 'ajax/get_doctor_patients.php',
                type: 'POST',
                success: function(response) {
                    var patients = JSON.parse(response);
                    patients.forEach(function(patient) {
                        $('#patientSelect').append(
                            '<option value="' + patient.patient_id + '">' + 
                            patient.patient_name + ' (' + patient.patient_number + ')' +
                            '</option>'
                        );
                    });
                }
            });
            <?php endif; ?>

            var uploadArea = $('#uploadArea');
            var fileInput = $('#fileInput');
            var filePreview = $('#filePreview');
            var submitBtn = $('#submitBtn');

            // Debug: Check if elements exist
            if (fileInput.length === 0) {
                console.error('File input not found!');
            }
            if ($('#browseBtn').length === 0) {
                console.error('Browse button not found!');
            }

            // Browse button click handler
            $('#browseBtn').on('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                console.log('Browse button clicked');
                if (fileInput.length > 0) {
                    fileInput[0].click(); // Use native click instead of jQuery trigger
                } else {
                    console.error('File input element not found');
                    alert('File input not found. Please refresh the page.');
                }
            });
            
            // Native JavaScript fallback for browse button
            var browseBtnNative = document.getElementById('browseBtn');
            var fileInputNative = document.getElementById('fileInput');
            if (browseBtnNative && fileInputNative) {
                browseBtnNative.addEventListener('click', function(e) {
                    e.preventDefault();
                    e.stopPropagation();
                    console.log('Native browse button clicked');
                    fileInputNative.click();
                });
            }

            // Upload area click handler (but not when clicking the button)
            uploadArea.on('click', function(e) {
                // Don't trigger if clicking the button or its children
                if ($(e.target).is('#browseBtn') || $(e.target).closest('#browseBtn').length > 0) {
                    return;
                }
                e.preventDefault();
                e.stopPropagation();
                console.log('Upload area clicked');
                if (fileInput.length > 0) {
                    fileInput[0].click();
                }
            });

            fileInput.on('change', function(e) {
                console.log('File input changed');
                if (this.files && this.files.length > 0) {
                    console.log('File selected:', this.files[0].name);
                    handleFile(this.files[0]);
                } else {
                    console.log('No file selected');
                }
            });
            
            // Also add native event listener as fallback
            if (fileInput.length > 0) {
                fileInput[0].addEventListener('change', function(e) {
                    console.log('Native change event fired');
                    if (this.files && this.files.length > 0) {
                        handleFile(this.files[0]);
                    }
                });
            }

            uploadArea.on('dragover', function(e) {
                e.preventDefault();
                $(this).addClass('drag-over');
            });

            uploadArea.on('dragleave', function() {
                $(this).removeClass('drag-over');
            });

            uploadArea.on('drop', function(e) {
                e.preventDefault();
                $(this).removeClass('drag-over');
                var files = e.originalEvent.dataTransfer.files;
                if (files.length > 0) {
                    fileInput[0].files = files;
                    handleFile(files[0]);
                }
            });

            function handleFile(file) {
                if (!file) return;

                var fileName = file.name;
                var fileSize = formatFileSize(file.size);
                var fileExt = fileName.split('.').pop().toLowerCase();
                var allowedExt = ['pdf', 'jpg', 'jpeg', 'png', 'doc', 'docx'];

                if (!allowedExt.includes(fileExt)) {
                    Swal.fire('Invalid File', 'Please upload PDF, JPG, PNG, DOC, or DOCX files only', 'error');
                    fileInput.val('');
                    return;
                }

                if (file.size > 10485760) {
                    Swal.fire('File Too Large', 'File size must not exceed 10MB', 'error');
                    fileInput.val('');
                    return;
                }

                $('#fileName').text(fileName);
                $('#fileSize').text(fileSize);
                uploadArea.hide();
                filePreview.show();
                submitBtn.prop('disabled', false);
            }

            $('#removeFile').on('click', function() {
                fileInput.val('');
                uploadArea.show();
                filePreview.hide();
                submitBtn.prop('disabled', true);
            });

            function formatFileSize(bytes) {
                if (bytes === 0) return '0 Bytes';
                var k = 1024;
                var sizes = ['Bytes', 'KB', 'MB', 'GB'];
                var i = Math.floor(Math.log(bytes) / Math.log(k));
                return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
            }

            $('#uploadForm').on('submit', function() {
                submitBtn.prop('disabled', true).html('<i class="ri-loader-4-line spinner-border spinner-border-sm me-1"></i> Uploading...');
            });

            <?php if(isset($_SESSION['error_message'])): ?>
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: '<?php echo addslashes($_SESSION['error_message']); ?>'
                });
                <?php unset($_SESSION['error_message']); ?>
            <?php endif; ?>
            
            <?php if(isset($_SESSION['success_message'])): ?>
                Swal.fire({
                    icon: 'success',
                    title: 'Success',
                    text: '<?php echo addslashes($_SESSION['success_message']); ?>'
                });
                <?php unset($_SESSION['success_message']); ?>
            <?php endif; ?>
        });
    </script>
</body>
</html>