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

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

// Get user ID for tracking
$user_id = $_SESSION['user_id'];

// Check for success/error messages
$successMessage = isset($_SESSION['success_message']) ? $_SESSION['success_message'] : null;
$errorMessage = isset($_SESSION['error_message']) ? $_SESSION['error_message'] : null;

// Clear session messages
unset($_SESSION['success_message']);
unset($_SESSION['error_message']);

// Query to fetch user details
$sql_user_details = "SELECT username, user_role, full_name, email, role_id FROM users WHERE user_id = $user_id";
$result_user_details = $conn->query($sql_user_details);

if ($result_user_details && $row_user_details = $result_user_details->fetch_assoc()) {
    $username = $row_user_details['username'];
    $user_role = $row_user_details['user_role'];
    $full_name = $row_user_details['full_name'];
    $email = $row_user_details['email'];
    $role_id = $row_user_details['role_id'];
} else {
    // Handle the case if user details are not found
    $role_id = 0;
}

// Check access permissions - only admin, general manager and ops manager can import
if (!in_array($role_id, [1, 2, 3])) {
    $_SESSION['error_message'] = "You don't have permission to access this page.";
    header('Location: index.php');
    exit();
}

// Create import manager instance
$importManager = new ImportManager($conn, $user_id);

// Handle download template request
if (isset($_GET['action']) && $_GET['action'] == 'download_template') {
    $type = $_GET['type'] ?? 'transit';
    if (!in_array($type, ['transit', 'local'])) {
        $type = 'transit';
    }
    
    try {
        $importManager->generateTemplate($type);
        exit; // Template is sent as download
    } catch (Exception $e) {
        $_SESSION['error_message'] = "Error generating template: " . $e->getMessage();
        header('Location: import_shipment.php');
        exit();
    }
}

// Fetch the system name
$sql = "SELECT setting_value FROM settings WHERE setting_key = 'system_name'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    $system_name = $row['setting_value'];
} else {
    $system_name = "Royal Freight"; // Fallback if not found
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $shipmentType = $_POST['shipment_type'] ?? 'transit';
    
    // Validate shipment type
    if (!in_array($shipmentType, ['transit', 'local'])) {
        $_SESSION['error_message'] = "Invalid shipment type selected.";
        header('Location: import_shipment.php');
        exit();
    }
    
    // Check if file was uploaded
    if (!isset($_FILES['import_file']) || $_FILES['import_file']['error'] !== UPLOAD_ERR_OK) {
        $_SESSION['error_message'] = "Please select a valid file to upload.";
        header('Location: import_shipment.php');
        exit();
    }
    
    try {
        // Process the uploaded file
        $importId = $importManager->processUploadedFile($_FILES['import_file'], $shipmentType);
        
        // Redirect to validation/preview page
        header("Location: preview_import.php?import_id=$importId");
        exit();
    } catch (Exception $e) {
        $_SESSION['error_message'] = "Error processing import: " . $e->getMessage();
        header('Location: import_shipment.php');
        exit();
    }
}
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Import Shipments')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <style>
        .import-card {
            border-left: 3px solid #3498db;
        }
        
        .template-card {
            border-left: 3px solid #2ecc71;
        }
        
        .instructions-card {
            border-left: 3px solid #f39c12;
        }
        
        .file-upload-wrapper {
            padding: 20px;
            border: 2px dashed #ccc;
            border-radius: 5px;
            text-align: center;
            margin-bottom: 20px;
            transition: all 0.3s ease;
        }
        
        .file-upload-wrapper:hover {
            border-color: #3498db;
        }
        
        .file-upload-wrapper label {
            cursor: pointer;
            width: 100%;
            height: 100%;
            display: block;
        }
        
        .file-upload-wrapper input[type="file"] {
            display: none;
        }
        
        .template-btn {
            margin-right: 10px;
        }
        
        .red-text {
            color: red;
        }
    </style>
</head>

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

        <!-- ============================================================== -->
        <!-- Start right Content here -->
        <!-- ============================================================== -->
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Shipment Management', 'title' => 'Import Shipments')); ?>

                    <!-- Alert Messages -->
                    <?php if ($successMessage): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <?php echo $successMessage; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    <?php endif; ?>
                    
                    <?php if ($errorMessage): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <?php echo $errorMessage; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    <?php endif; ?>

                    <div class="row">
                        <div class="col-xxl-8">
                            <div class="card import-card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Import Shipment Data</h4>
                                </div><!-- end card header -->

                                <div class="card-body">
                                    <p class="text-muted">Upload a CSV or Excel file containing shipment data for batch import.</p>
                                    
                                    <form method="POST" action="import_shipment.php" enctype="multipart/form-data">
                                        <div class="mb-3">
                                            <label for="shipment_type" class="form-label">Shipment Type <span class="red-text">*</span></label>
                                            <select class="form-select" id="shipment_type" name="shipment_type" required>
                                                <option value="transit">Transit Shipment</option>
                                                <option value="local">Local Shipment</option>
                                            </select>
                                        </div>
                                        
                                        <div class="file-upload-wrapper">
                                            <label for="import_file">
                                                <div class="mb-2">
                                                    <i class="ri-upload-cloud-2-line" style="font-size: 48px;"></i>
                                                </div>
                                                <h5>Click or drag file to upload</h5>
                                                <p class="text-muted">Supported formats: CSV, XLSX, XLS</p>
                                                <input type="file" id="import_file" name="import_file" accept=".csv, .xlsx, .xls" required>
                                            </label>
                                        </div>
                                        
                                        <p class="mb-3">
                                            <span id="selected-file-name">No file selected</span>
                                        </p>
                                        
                                        <div class="mt-3 d-flex">
                                            <button type="submit" class="btn btn-primary">
                                                <i class="ri-check-line align-bottom me-1"></i> Upload & Validate
                                            </button>
                                            <a href="index.php" class="btn btn-light ms-2">
                                                <i class="ri-close-line align-bottom me-1"></i> Cancel
                                            </a>
                                        </div>
                                    </form>
                                </div>
                            </div>
                            
                            <div class="card instructions-card mt-4">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Import Instructions</h4>
                                </div>
                                <div class="card-body">
                                    <ol>
                                        <li><strong>Download the template</strong> for the type of shipment you want to import.</li>
                                        <li><strong>Fill in the data</strong> according to the template format. Required fields are marked in the template.</li>
                                        <li><strong>Upload the completed file</strong> using the form above.</li>
                                        <li><strong>Validate the data</strong> on the preview screen before final import.</li>
                                        <li><strong>Approve the import</strong> once you've confirmed the data is correct.</li>
                                    </ol>
                                    
                                    <div class="alert alert-warning mt-3 mb-0">
                                        <strong>Important notes:</strong>
                                        <ul class="mb-0 mt-2">
                                            <li>File numbers will be automatically generated based on destination.</li>
                                            <li>Rows with validation errors will be highlighted in the preview and can be skipped during import.</li>
                                            <li>All imports are processed as a transaction. If critical errors occur, the entire import will be rolled back.</li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xxl-4">
                            <div class="card template-card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Download Templates</h4>
                                </div>
                                <div class="card-body">
                                    <p class="text-muted">Download the appropriate template based on the type of shipment you want to import.</p>
                                    
                                    <div class="d-grid gap-2">
                                        <a href="import_shipment.php?action=download_template&type=transit" 
                                           class="btn btn-success btn-label waves-effect waves-light">
                                            <i class="ri-file-download-line label-icon align-middle fs-16 me-2"></i> 
                                            Transit Shipment Template
                                        </a>
                                        
                                        <a href="import_shipment.php?action=download_template&type=local" 
                                           class="btn btn-success btn-label waves-effect waves-light">
                                            <i class="ri-file-download-line label-icon align-middle fs-16 me-2"></i> 
                                            Local Shipment Template
                                        </a>
                                    </div>
                                    
                                    <div class="alert alert-info mt-3 mb-0">
                                        <h5 class="alert-heading"><i class="ri-information-line me-1"></i> Template Information</h5>
                                        <p class="mb-2">The templates include the following sections:</p>
                                        <ul class="mb-0">
                                            <li><strong>Shipment details</strong> - Main information about the shipment</li>
                                            <li><strong>Container details</strong> - Information about containers (optional)</li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="card mt-4">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Required Fields</h4>
                                </div>
                                <div class="card-body">
                                    <h5>Transit Shipments</h5>
                                    <ul>
                                        <li>Destination (e.g., DR-LUB, BU-BU)</li>
                                        <li>Customer ID</li>
                                        <li>Consignee Name</li>
                                        <li>OBL Number</li>
                                    </ul>
                                    
                                    <h5>Local Shipments</h5>
                                    <ul>
                                        <li>Destination</li>
                                        <li>Customer ID</li>
                                        <li>Consignee Name</li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- container-fluid -->
            </div>
            <!-- End Page-content -->
            <?php include 'layouts/footer.php'; ?>
        </div>
        <!-- end main content-->
    </div>
    <!-- END layout-wrapper -->

    <?php include 'layouts/vendor-scripts.php'; ?>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // File upload display
            const fileInput = document.getElementById('import_file');
            const fileNameDisplay = document.getElementById('selected-file-name');
            
            fileInput.addEventListener('change', function() {
                if (this.files && this.files[0]) {
                    fileNameDisplay.textContent = 'Selected file: ' + this.files[0].name;
                } else {
                    fileNameDisplay.textContent = 'No file selected';
                }
            });
        });
    </script>
</body>
</html>