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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Get user details and check permissions
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT username, user_role, role_id FROM users WHERE user_id = $user_id";
$result_user_details = $conn->query($sql_user_details);
$row_user_details = $result_user_details->fetch_assoc();

// Only allow admin, general manager, operations roles
$allowed_roles = [1, 2, 3];
if (!in_array($row_user_details['role_id'], $allowed_roles)) {
    $_SESSION['error_message'] = "You don't have permission to access this page.";
    header('Location: index.php');
    exit();
}

// Get system name from settings
$sql = "SELECT setting_value FROM settings WHERE setting_key = 'system_name'";
$result = $conn->query($sql);
$system_name = ($result->num_rows > 0) ? $result->fetch_assoc()['setting_value'] : "Royal Freight";

// Get recent imports
$imports_query = "SELECT i.*, u.username as created_by_name
                 FROM import_batches i 
                 JOIN users u ON i.created_by = u.user_id
                 ORDER BY i.created_at DESC LIMIT 10";
$imports_result = $conn->query($imports_query);
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Import Data')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- Dropzone CSS -->
    <link href="https://unpkg.com/dropzone@5/dist/min/dropzone.min.css" rel="stylesheet" type="text/css" />
    
    <style>
        .import-type-card {
            cursor: pointer;
            border: 2px solid transparent;
            transition: all 0.3s ease;
        }
        
        .import-type-card.selected {
            border-color: #3498db;
            background-color: #f8f9fa;
        }
        
        .step-indicator {
            display: flex;
            justify-content: space-between;
            margin-bottom: 2rem;
        }
        
        .step {
            flex: 1;
            text-align: center;
            padding: 1rem;
            position: relative;
        }
        
        .step:not(:last-child):after {
            content: '';
            position: absolute;
            top: 50%;
            right: 0;
            width: 100%;
            height: 2px;
            background: #e9ecef;
            transform: translateY(-50%);
            z-index: -1;
        }
        
        .step.active .step-number {
            background: #3498db;
            color: white;
        }
        
        .step-number {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background: #e9ecef;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 0.5rem;
        }
        
        .dropzone {
            border: 2px dashed #3498db;
            border-radius: 5px;
            padding: 20px;
            text-align: center;
            min-height: 200px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Data Management', 'title' => 'Import Data')); ?>
                    
                    <!-- Display messages -->
                    <?php if (isset($_SESSION['success_message'])): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    <?php endif; ?>
                    
                    <?php if (isset($_SESSION['error_message'])): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    <?php endif; ?>
                    
                    <!-- Import wizard -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Import Shipment Data</h4>
                                </div>
                                <div class="card-body">
                                    <!-- Step indicators -->
                                    <div class="step-indicator mb-4">
                                        <div class="step active" id="step1-indicator">
                                            <div class="step-number">1</div>
                                            <div>Select Type</div>
                                        </div>
                                        <div class="step" id="step2-indicator">
                                            <div class="step-number">2</div>
                                            <div>Upload Data</div>
                                        </div>
                                        <div class="step" id="step3-indicator">
                                            <div class="step-number">3</div>
                                            <div>Review & Import</div>
                                        </div>
                                    </div>
                                    
                                    <!-- Step 1: Select Import Type -->
                                    <div id="step1" class="step-content">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="card import-type-card" data-type="transit">
                                                    <div class="card-body">
                                                        <h5>Transit Shipment</h5>
                                                        <p class="mb-0">Import transit shipment data including container tracking details</p>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="card import-type-card" data-type="local">
                                                    <div class="card-body">
                                                        <h5>Local Shipment</h5>
                                                        <p class="mb-0">Import local shipment data with simplified tracking</p>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="text-end mt-3">
                                            <button class="btn btn-primary" id="nextToStep2" disabled>Next</button>
                                        </div>
                                    </div>
                                    
                                    <!-- Step 2: Upload File -->
                                    <div id="step2" class="step-content" style="display: none;">
                                        <div class="row">
                                            <div class="col-12 mb-3">
                                                <div class="alert alert-info">
                                                    <div class="d-flex">
                                                        <i class="ri-information-line me-2 fs-16"></i>
                                                        <div>
                                                            <h5 class="alert-heading">Import Guidelines</h5>
                                                            <p class="mb-0">Download the template file and ensure your data matches the required format.</p>
                                                            <a href="#" id="downloadTemplate" class="alert-link">Download Template</a>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="col-12">
                                                <form action="process_import.php" class="dropzone" id="importDropzone">
                                                    <div class="dz-message">
                                                        <h4>Drop files here or click to upload</h4>
                                                        <p class="text-muted">Accepted formats: .xlsx, .xls, .csv</p>
                                                    </div>
                                                </form>
                                            </div>
                                        </div>
                                        
                                        <div class="d-flex justify-content-between mt-3">
                                            <button class="btn btn-secondary" id="backToStep1">Back</button>
                                            <button class="btn btn-primary" id="nextToStep3" disabled>Next</button>
                                        </div>
                                    </div>
                                    
                                    <!-- Step 3: Review & Import -->
                                    <div id="step3" class="step-content" style="display: none;">
                                        <div id="previewContent">
                                            <div class="text-center py-5">
                                                <div class="spinner-border text-primary"></div>
                                                <p class="mt-2">Loading preview...</p>
                                            </div>
                                        </div>
                                        
                                        <div class="d-flex justify-content-between mt-3">
                                            <button class="btn btn-secondary" id="backToStep2">Back</button>
                                            <button class="btn btn-success" id="submitImport" disabled>Import Data</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Recent Imports -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Recent Imports</h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-bordered">
                                            <thead>
                                                <tr>
                                                    <th>Date</th>
                                                    <th>Type</th>
                                                    <th>File</th>
                                                    <th>Status</th>
                                                    <th>Records</th>
                                                    <th>Created By</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while($row = $imports_result->fetch_assoc()): ?>
                                                <tr>
                                                    <td><?php echo date('Y-m-d H:i', strtotime($row['created_at'])); ?></td>
                                                    <td><?php echo ucfirst(str_replace('_', ' ', $row['import_type'])); ?></td>
                                                    <td><?php echo htmlspecialchars($row['filename']); ?></td>
                                                    <td>
                                                        <span class="badge bg-<?php 
                                                            echo $row['status'] == 'success' ? 'success' : 
                                                                ($row['status'] == 'pending' ? 'warning' : 'danger'); 
                                                        ?>">
                                                            <?php echo ucfirst($row['status']); ?>
                                                        </span>
                                                    </td>
                                                    <td><?php echo $row['processed_records'] . '/' . $row['total_records']; ?></td>
                                                    <td><?php echo htmlspecialchars($row['created_by_name']); ?></td>
                                                    <td>
                                                        <a href="view_import.php?id=<?php echo $row['id']; ?>" 
                                                           class="btn btn-sm btn-info">
                                                            <i class="ri-eye-line"></i>
                                                        </a>
                                                        <?php if($row['status'] == 'pending'): ?>
                                                        <a href="delete_import.php?id=<?php echo $row['id']; ?>" 
                                                           class="btn btn-sm btn-danger">
                                                            <i class="ri-delete-bin-line"></i>
                                                        </a>
                                                        <?php endif; ?>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                                
                                                <?php if($imports_result->num_rows == 0): ?>
                                                <tr>
                                                    <td colspan="7" class="text-center">No recent imports found</td>
                                                </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    
    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
    <!-- Dropzone JS -->
    <script src="https://unpkg.com/dropzone@5/dist/min/dropzone.min.js"></script>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            let selectedType = null;
            let myDropzone = null;
            
            // Import type selection
            document.querySelectorAll('.import-type-card').forEach(card => {
                card.addEventListener('click', function() {
                    document.querySelectorAll('.import-type-card').forEach(c => 
                        c.classList.remove('selected'));
                    this.classList.add('selected');
                    selectedType = this.dataset.type;
                    document.getElementById('nextToStep2').disabled = false;
                });
            });
            
            // Initialize Dropzone
            Dropzone.autoDiscover = false;
            
            function initDropzone() {
                if (myDropzone) {
                    myDropzone.destroy();
                }
                
                myDropzone = new Dropzone("#importDropzone", {
                    url: "process_import.php",
                    paramName: "file",
                    maxFilesize: 10,
                    acceptedFiles: ".xlsx,.xls,.csv",
                    addRemoveLinks: true,
                    maxFiles: 1,
                    init: function() {
                        this.on("success", function(file, response) {
                            document.getElementById('nextToStep3').disabled = false;
                        });
                        this.on("error", function(file, message) {
                            alert(message);
                            this.removeFile(file);
                        });
                    }
                });
            }
            
            // Navigation handlers
            document.getElementById('nextToStep2').addEventListener('click', function() {
                showStep(2);
                initDropzone();
            });
            
            document.getElementById('backToStep1').addEventListener('click', function() {
                showStep(1);
            });
            
            document.getElementById('nextToStep3').addEventListener('click', function() {
                showStep(3);
                loadPreview();
            });
            
            document.getElementById('backToStep2').addEventListener('click', function() {
                showStep(2);
            });
            
            document.getElementById('submitImport').addEventListener('click', function() {
                if (confirm('Are you sure you want to import this data?')) {
                    submitImport();
                }
            });
            
            // Download template handler
            document.getElementById('downloadTemplate').addEventListener('click', function(e) {
                e.preventDefault();
                if (!selectedType) {
                    alert('Please select an import type first');
                    return;
                }
                window.location.href = `download_template.php?type=${selectedType}`;
            });
            
            function showStep(stepNumber) {
                // Hide all steps
                document.querySelectorAll('.step-content').forEach(step => {
                    step.style.display = 'none';
                });
                
                // Show selected step
                document.getElementById(`step${stepNumber}`).style.display = 'block';
                
                // Update step indicators
                document.querySelectorAll('.step').forEach((step, index) => {
                    if (index + 1 < stepNumber) {
                        step.classList.add('completed');
                        step.classList.remove('active');
                    } else if (index + 1 === stepNumber) {
                        step.classList.add('active');
                        step.classList.remove('completed');
                    } else {
                        step.classList.remove('active', 'completed');
                    }
                });
            }
            
            function loadPreview() {
                const previewContent = document.getElementById('previewContent');
                previewContent.innerHTML = `
                    <div class="text-center py-5">
                        <div class="spinner-border text-primary"></div>
                        <p class="mt-2">Processing data...</p>
                    </div>
                `;
                
                fetch('preview_import.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ type: selectedType })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        previewContent.innerHTML = data.html;
                        document.getElementById('submitImport').disabled = false;
                    } else {
                        previewContent.innerHTML = `
                            <div class="alert alert-danger">
                                ${data.message}
                            </div>
                        `;
                    }
                })
                .catch(error => {
                    previewContent.innerHTML = `
                        <div class="alert alert-danger">
                            Failed to load preview: ${error.message}
                        </div>
                    `;
                });
            }
            
            function submitImport() {
                const submitButton = document.getElementById('submitImport');
                submitButton.disabled = true;
                submitButton.innerHTML = `
                    <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                    Importing...
                `;
                
                fetch('process_import.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ type: selectedType })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('Import completed successfully!');
                        window.location.reload();
                    } else {
                        alert('Import failed: ' + data.message);
                        submitButton.disabled = false;
                        submitButton.innerHTML = 'Import Data';
                    }
                })
                .catch(error => {
                    alert('Import failed: ' + error.message);
                    submitButton.disabled = false;
                    submitButton.innerHTML = 'Import Data';
                });
            }
        });
    </script>
</body>
</html>