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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'errors' => ['You must be logged in to import data.']]);
    exit();
}

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

// Check if import type is provided
if (!isset($_POST['import_type']) || empty($_POST['import_type'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'errors' => ['Import type is required.']]);
    exit();
}

$importType = $_POST['import_type'];

// Validate import type
if (!in_array($importType, ['transit', 'local'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'errors' => ['Invalid import type.']]);
    exit();
}

// Check if file was uploaded
if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
    $error = $_FILES['file']['error'] ?? UPLOAD_ERR_NO_FILE;
    $errorMessage = getUploadErrorMessage($error);
    
    http_response_code(400);
    echo json_encode(['success' => false, 'errors' => ["File upload failed: $errorMessage"]]);
    exit();
}

// Validate file type
$fileInfo = pathinfo($_FILES['file']['name']);
$fileExtension = strtolower($fileInfo['extension'] ?? '');

if (!in_array($fileExtension, ['xlsx', 'xls', 'csv'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'errors' => ['Invalid file type. Only XLSX, XLS, and CSV files are supported.']]);
    exit();
}

// Move uploaded file to a temporary location
$uploadDir = 'uploads/temp/';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

$tempFilename = md5(time() . rand(1000, 9999)) . '.' . $fileExtension;
$tempFilePath = $uploadDir . $tempFilename;

if (!move_uploaded_file($_FILES['file']['tmp_name'], $tempFilePath)) {
    http_response_code(500);
    echo json_encode(['success' => false, 'errors' => ['Failed to save uploaded file.']]);
    exit();
}

try {
    // Create importer instance
    $importer = new ShipmentImporter($conn, $importType, $user_id);
    
    // Process the file
    $results = $importer->processFile($tempFilePath);
    
    // Delete the temporary file
    @unlink($tempFilePath);
    
    // Return results
    echo json_encode($results);
    
} catch (Exception $e) {
    // Delete the temporary file
    @unlink($tempFilePath);
    
    http_response_code(500);
    echo json_encode([
        'success' => false, 
        'errors' => ['An error occurred while processing the file: ' . $e->getMessage()]
    ]);
}

/**
 * Get error message for upload error code
 * 
 * @param int $errorCode PHP upload error code
 * @return string Human-readable error message
 */
function getUploadErrorMessage($errorCode) {
    switch ($errorCode) {
        case UPLOAD_ERR_INI_SIZE:
            return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
        case UPLOAD_ERR_FORM_SIZE:
            return 'The uploaded file exceeds the MAX_FILE_SIZE directive in the HTML form';
        case UPLOAD_ERR_PARTIAL:
            return 'The uploaded file was only partially uploaded';
        case UPLOAD_ERR_NO_FILE:
            return 'No file was uploaded';
        case UPLOAD_ERR_NO_TMP_DIR:
            return 'Missing a temporary folder';
        case UPLOAD_ERR_CANT_WRITE:
            return 'Failed to write file to disk';
        case UPLOAD_ERR_EXTENSION:
            return 'File upload stopped by extension';
        default:
            return 'Unknown upload error';
    }
}
?>