<?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'];

// 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();
}

// Check if import_id parameter exists
if (!isset($_GET['import_id']) || empty($_GET['import_id'])) {
    $_SESSION['error_message'] = "No import data specified.";
    header('Location: import_shipment.php');
    exit();
}

$importId = $_GET['import_id'];

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

try {
    // Get import data
    $importData = $importManager->getImportData($importId);
    
    // Get import status summary
    $importStatus = $importManager->getImportStatus($importId);
    
    // Get shipment type (transit or local)
    $shipmentType = $importData['type'];
    
    // Prepare data arrays for display
    $data = $importData['data'];
    $errors = $importData['errors'];
    
} catch (Exception $e) {
    $_SESSION['error_message'] = "Error loading import data: " . $e->getMessage();
    header('Location: import_shipment.php');
    exit();
}

// Handle form submission for final import
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action']) && $_POST['action'] === 'process_import') {
        try {
            // Process the approved import
            $results = $importManager->processApprovedImport($importId);
            
            // Prepare success message
            $successMessage = "Import completed: {$results['success']} shipments successfully imported";
            
            if ($results['skipped'] > 0) {
                $successMessage .= ", {$results['skipped']} shipments skipped";
            }
            
            if ($results['error'] > 0) {
                $successMessage .= ", {$results['error']} errors encountered";
            }
            
            $_SESSION['success_message'] = $successMessage;
            
            if (!empty($results['errors'])) {
                // Store detailed errors in session for display
                $_SESSION['import_errors'] = $results['errors'];
            }
            
            // Redirect to appropriate list page based on shipment type
            $redirectPage = ($shipmentType === 'transit') ? 'file_list.php' : 'file_list.php';
            header("Location: $redirectPage");
            exit();
        } catch (Exception $e) {
            $_SESSION['error_message'] = "Error processing import: " . $e->getMessage();
            header("Location: preview_import.php?import_id=$importId");
            exit();
        }
    } elseif (isset($_POST['action']) && $_POST['action'] === 'cancel_import') {
        // Cancel import and redirect
        $_SESSION['info_message'] = "Import cancelled.";
        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
}

// Get customers for lookup
$customerMap = [];
$sql_customers = "SELECT customer_id, first_name FROM customers";
$result_customers = $conn->query($sql_customers);
if ($result_customers) {
    while ($row = $result_customers->fetch_assoc()) {
        $customerMap[$row['customer_id']] = $row['first_name'];
    }
}
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Preview Import')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <style>
        .error-row {
            background-color: #ffe6e6 !important;
        }
        
        .validation-errors {
            margin-top: 5px;
            color: #dc3545;
        }
        
        .action-buttons {
            margin-top: 20px;
            margin-bottom: 20px;
        }
        
        .summary-card {
            border-left: 3px solid #3498db;
        }
        
        .error-summary-card {
            border-left: 3px solid #e74c3c;
        }
        
        .import-table td, .import-table th {
            white-space: nowrap;
        }
        
        .table-responsive {
            min-height: 300px;
        }
        
        .truncate {
            max-width: 150px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .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' => 'Preview Import')); ?>

                    <div class="row">
                        <div class="col-xxl-3">
                            <div class="card summary-card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Import Summary</h4>
                                </div>
                                <div class="card-body">
                                    <div class="mb-4">
                                        <h5>Shipment Type</h5>
                                        <p class="text-muted mb-0">
                                            <?php echo ucfirst($shipmentType); ?> Shipment
                                        </p>
                                    </div>
                                    
                                    <div class="mb-4">
                                        <h5>Statistics</h5>
                                        <ul class="list-group">
                                            <li class="list-group-item d-flex justify-content-between align-items-center">
                                                Total Rows
                                                <span class="badge bg-primary rounded-pill"><?php echo $importStatus['totalRows']; ?></span>
                                            </li>
                                            <li class="list-group-item d-flex justify-content-between align-items-center">
                                                Valid Rows
                                                <span class="badge bg-success rounded-pill"><?php echo $importStatus['validRows']; ?></span>
                                            </li>
                                            <li class="list-group-item d-flex justify-content-between align-items-center">
                                                Rows With Errors
                                                <span class="badge bg-danger rounded-pill"><?php echo $importStatus['rowsWithErrors']; ?></span>
                                            </li>
                                        </ul>
                                    </div>
                                    
                                    <?php if ($importStatus['isValid'] && $importStatus['validRows'] > 0): ?>
                                        <div class="alert alert-success mb-0" role="alert">
                                            <div class="d-flex">
                                                <i class="ri-check-line me-2 fs-20 align-middle"></i>
                                                <div>
                                                    <strong>Ready for import!</strong>
                                                    <p class="mb-0">All data is valid and ready to be imported.</p>
                                                </div>
                                            </div>
                                        </div>
                                    <?php elseif ($importStatus['validRows'] > 0): ?>
                                        <div class="alert alert-warning mb-0" role="alert">
                                            <div class="d-flex">
                                                <i class="ri-alert-line me-2 fs-20 align-middle"></i>
                                                <div>
                                                    <strong>Partial import available</strong>
                                                    <p class="mb-0">Some rows have errors but valid rows can be imported.</p>
                                                </div>
                                            </div>
                                        </div>
                                    <?php else: ?>
                                        <div class="alert alert-danger mb-0" role="alert">
                                            <div class="d-flex">
                                                <i class="ri-error-warning-line me-2 fs-20 align-middle"></i>
                                                <div>
                                                    <strong>Import not available</strong>
                                                    <p class="mb-0">All rows have errors. Please correct your data and try again.</p>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                    
                                    <div class="action-buttons">
                                        <form method="POST">
                                            <?php if ($importStatus['validRows'] > 0): ?>
                                                <input type="hidden" name="action" value="process_import">
                                                <button type="submit" class="btn btn-success w-100 mb-2">
                                                    <i class="ri-check-double-line me-1"></i> Process Import
                                                </button>
                                            <?php endif; ?>
                                            
                                            <button type="submit" name="action" value="cancel_import" class="btn btn-light w-100">
                                                <i class="ri-close-line me-1"></i> Cancel Import
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                            
                            <?php if ($importStatus['rowsWithErrors'] > 0): ?>
                            <div class="card error-summary-card mt-4">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Error Summary</h4>
                                </div>
                                <div class="card-body">
                                    <p class="text-muted">Rows with the following issues will be skipped during import.</p>
                                    <div class="alert alert-danger">
                                        <h5><i class="ri-error-warning-line me-1"></i> Common Issues</h5>
                                        <ul class="mb-0">
                                            <?php 
                                            $commonErrors = [];
                                            foreach ($errors as $rowIndex => $rowErrors) {
                                                foreach ($rowErrors as $error) {
                                                    if (!in_array($error, $commonErrors)) {
                                                        $commonErrors[] = $error;
                                                        if (count($commonErrors) <= 5) { // Limit to showing only 5 common errors
                                                            echo "<li>$error</li>";
                                                        }
                                                    }
                                                }
                                            }
                                            
                                            if (count($commonErrors) > 5) {
                                                echo "<li>... and " . (count($commonErrors) - 5) . " more error types</li>";
                                            }
                                            ?>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="col-xxl-9">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Data Preview</h4>
                                    <div class="flex-shrink-0">
                                        <span class="text-muted small">
                                            <span class="red-text">*</span> Rows in red have validation errors and will be skipped
                                        </span>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-striped table-bordered import-table">
                                            <thead>
                                                <tr>
                                                    <th>#</th>
                                                    <th>File Number</th>
                                                    <th>Customer</th>
                                                    <th>Consignee</th>
                                                    <th>Destination</th>
                                                    <?php if ($shipmentType === 'transit'): ?>
                                                    <th>OBL Number</th>
                                                    <th>ETA</th>
                                                    <?php else: ?>
                                                    <th>Transporter</th>
                                                    <th>ETA</th>
                                                    <?php endif; ?>
                                                    <th>Container</th>
                                                    <th>Container Size</th>
                                                    <th>Status</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (empty($data)): ?>
                                                <tr>
                                                    <td colspan="10" class="text-center">No data found</td>
                                                </tr>
                                                <?php else: ?>
                                                    <?php foreach ($data as $index => $row): 
                                                        $hasError = isset($errors[$index]);
                                                    ?>
                                                    <tr class="<?php echo $hasError ? 'error-row' : ''; ?>">
                                                        <td><?php echo $index + 1; ?></td>
                                                        <td><?php echo $row['file_number'] ?? 'N/A'; ?></td>
                                                        <td>
                                                            <?php 
                                                                if (!empty($row['customer'])) {
                                                                    echo $row['customer'] . ' - ' . ($customerMap[$row['customer']] ?? $row['customer_name'] ?? 'Unknown');
                                                                } else {
                                                                    echo 'N/A';
                                                                }
                                                            ?>
                                                        </td>
                                                        <td class="truncate"><?php echo $row['consignee_name'] ?? 'N/A'; ?></td>
                                                        <td><?php echo $row['destination'] ?? 'N/A'; ?></td>
                                                        <?php if ($shipmentType === 'transit'): ?>
                                                        <td class="truncate"><?php echo $row['obl_no'] ?? 'N/A'; ?></td>
                                                        <td><?php echo $row['eta'] ?? 'N/A'; ?></td>
                                                        <?php else: ?>
                                                        <td><?php echo $row['transporter'] ?? 'N/A'; ?></td>
                                                        <td><?php echo $row['eta'] ?? 'N/A'; ?></td>
                                                        <?php endif; ?>
                                                        <td><?php echo $row['container_code'] ?? 'N/A'; ?></td>
                                                        <td><?php echo $row['container_size'] ?? 'N/A'; ?></td>
                                                        <td>
                                                            <?php if ($hasError): ?>
                                                                <span class="badge bg-danger">Error</span>
                                                                <div class="validation-errors">
                                                                    <?php foreach ($errors[$index] as $error): ?>
                                                                        <small><?php echo $error; ?></small><br>
                                                                    <?php endforeach; ?>
                                                                </div>
                                                            <?php else: ?>
                                                                <span class="badge bg-success">Valid</span>
                                                            <?php endif; ?>
                                                        </td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </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>
</body>
</html>