<?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 status to check if it's valid for processing
    $importStatus = $importManager->getImportStatus($importId);
    
    // Make sure there's at least one valid row
    if ($importStatus['validRows'] === 0) {
        $_SESSION['error_message'] = "No valid data to import.";
        header('Location: preview_import.php?import_id=' . $importId);
        exit();
    }
    
    // Process the 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 file list page
    header('Location: file_list.php');
    exit();
    
} catch (Exception $e) {
    $_SESSION['error_message'] = "Error processing import: " . $e->getMessage();
    header('Location: preview_import.php?import_id=' . $importId);
    exit();
}
?>