<?php
session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Inventory.php';
require_once __DIR__ . '/../../classes/Shipment.php';
require_once __DIR__ . '/../../classes/ExcelImport.php';
require_once __DIR__ . '/../../classes/Suppliers.php';
require_once __DIR__ . '/../../classes/MraEisCompliance.php';
require_once __DIR__ . '/../../classes/SystemSettings.php';


$phpspreadsheet_installed = false;

$autoloader = __DIR__ . '/../../vendor/autoload.php';
if (file_exists($autoloader)) {
    require_once $autoloader;
    $phpspreadsheet_installed = class_exists('\PhpOffice\PhpSpreadsheet\IOFactory');
}


$database = new Database();
$conn = $database->getConnection();
$systemSettings = new SystemSettings($conn);
$imsOnly = $systemSettings->imsOnly();


$auth = new Auth($conn);
if (!isset($_SESSION['user_id'])) {
    header('Location: ../../login.php');
    exit();
}


$userRole = $auth->getUserRole($_SESSION['user_id']);
if (!in_array($userRole, ['warehouse', 'admin'])) {
    die("Access denied. You must have warehouse or admin privileges.");
}


$branch_id = 7;


$stmt = $conn->prepare("SELECT branch_name FROM branches WHERE branch_id = ?");
$stmt->execute([$branch_id]);
$branch_name = $stmt->fetchColumn();
if (!$branch_name) {
    die("Invalid branch.");
}


$inventory = new Inventory($conn);
$suppliers = new Suppliers($conn);
$supplierList = $suppliers->getSuppliers('active');


$message = '';
$preview_data = [];
$import_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (isset($_FILES['excel_file']) && $_FILES['excel_file']['error'] === UPLOAD_ERR_OK) {
        $import_type = $_POST['import_type'] ?? '';

        if (!in_array($import_type, ['simple', 'detailed'])) {
            $message = "<div class='alert alert-danger'>Please select a valid import type (Simple or Detailed).</div>";
        } else {

            $tmp_file = $_FILES['excel_file']['tmp_name'];


            $file_extension = strtolower(pathinfo($_FILES['excel_file']['name'], PATHINFO_EXTENSION));

            if (!in_array($file_extension, ['xlsx', 'xls', 'csv'])) {
                $message = "<div class='alert alert-danger'>Invalid file format. Please upload an Excel file (.xlsx, .xls) or CSV file.</div>";
            } else {

                if (!$phpspreadsheet_installed) {
                    $message = "<div class='alert alert-danger'>PhpSpreadsheet library is not installed. Please ensure PhpSpreadsheet is correctly placed in the vendor directory.</div>";
                } else {

                    $temp_dir = __DIR__ . '/../../temp';
                    if (!file_exists($temp_dir)) {
                        mkdir($temp_dir, 0777, true);
                    }


                    $temp_file_path = $temp_dir . '/' . uniqid('import_') . '.' . $file_extension;


                    if (move_uploaded_file($tmp_file, $temp_file_path)) {

                        $excelImport = new ExcelImport($conn, $temp_file_path, $import_type);


                        if ($excelImport->processFile()) {

                            if ($excelImport->validateUniqueCodes()) {

                                $preview_data = $excelImport->getData();


                                $_SESSION['temp_excel_file'] = $temp_file_path;
                                $_SESSION['excel_import_type'] = $import_type;
                                $_SESSION['excel_receiving_meta'] = [
                                    'supplier_id' => (int)($_POST['supplier_id'] ?? 0),
                                    'delivery_note_number' => trim((string)($_POST['delivery_note_number'] ?? '')),
                                    'purchase_order_number' => trim((string)($_POST['purchase_order_number'] ?? '')),
                                    'received_by' => trim((string)($_POST['received_by'] ?? ($_SESSION['username'] ?? ''))),
                                    'unit_of_measure' => trim((string)($_POST['unit_of_measure'] ?? 'EACH')),
                                    'notes' => trim((string)($_POST['notes'] ?? '')),
                                    'is_finished_product' => !empty($_POST['is_finished_product']),
                                ];

                                $message = "<div class='alert alert-success'>File processed successfully. Please review the data before importing.</div>";
                            } else {

                                $errors = $excelImport->getErrors();
                                $message = "<div class='alert alert-danger'>Validation failed: " . implode('<br>', $errors) . "</div>";
                                $preview_data = [];
                            }
                        } else {

                            $errors = $excelImport->getErrors();
                            $message = "<div class='alert alert-danger'>Processing failed: " . implode('<br>', $errors) . "</div>";
                            $preview_data = [];
                        }
                    } else {
                        $message = "<div class='alert alert-danger'>Failed to move uploaded file.</div>";
                    }
                }
            }
        }
    } else if (isset($_FILES['excel_file']) && $_FILES['excel_file']['error'] !== UPLOAD_ERR_OK) {

        $upload_errors = [
            UPLOAD_ERR_INI_SIZE => "The uploaded file exceeds the upload_max_filesize directive in php.ini",
            UPLOAD_ERR_FORM_SIZE => "The uploaded file exceeds the MAX_FILE_SIZE directive in the HTML form",
            UPLOAD_ERR_PARTIAL => "The uploaded file was only partially uploaded",
            UPLOAD_ERR_NO_FILE => "No file was uploaded",
            UPLOAD_ERR_NO_TMP_DIR => "Missing a temporary folder",
            UPLOAD_ERR_CANT_WRITE => "Failed to write file to disk",
            UPLOAD_ERR_EXTENSION => "A PHP extension stopped the file upload"
        ];

        $error_message = isset($upload_errors[$_FILES['excel_file']['error']])
            ? $upload_errors[$_FILES['excel_file']['error']]
            : "Unknown upload error";

        $message = "<div class='alert alert-danger'>Upload failed: {$error_message}</div>";
    }


    if (isset($_POST['confirm_import'], $_SESSION['temp_excel_file'], $_SESSION['excel_import_type']) && $_POST['confirm_import'] === '1') {

        $temp_file_path = $_SESSION['temp_excel_file'];
        $import_type = $_SESSION['excel_import_type'];


        if (file_exists($temp_file_path)) {

            $excelImport = new ExcelImport($conn, $temp_file_path, $import_type);


            if ($excelImport->processFile() && $excelImport->validateUniqueCodes()) {

                $formattedData = $excelImport->formatDataForImport();


                error_log("Formatted data for warehouse import: " . json_encode($formattedData));


                try {

                    if ($inventory->addItemsToWarehouse($formattedData, $_SESSION['user_id'])) {
                        $message = "<div class='alert alert-success'>Import successful! " . count($formattedData) . " items have been added directly to the warehouse and are now available.</div>";

                        if ($imsOnly) {
                            $message .= "<div class='alert alert-info mt-2'>IMS Only: items were imported locally and no MRA EIS transaction was created.</div>";
                        } else {
                            // Auto-queue this stock receipt as an MRA EIS informal purchase (goods receiving).
                            // Never lets an EIS problem turn the already-successful import into an error -
                            // a bad/incomplete receiving batch just lands in the outbox as 'blocked' for review.
                            try {
                            $receivingMeta = $_SESSION['excel_receiving_meta'] ?? [];
                            $receivingMeta['receiving_date'] = date('Y-m-d H:i:s');

                            $grouped = [];
                            foreach ($formattedData as $row) {
                                $groupKey = trim((string)($row['item_name'] ?? '')) . '|' . (string)($row['unit_price'] ?? 0);
                                if (!isset($grouped[$groupKey])) {
                                    $grouped[$groupKey] = [
                                        'item_code' => trim((string)($row['product_code'] ?? '')),
                                        'description' => trim((string)($row['item_details'] ?? '')) ?: trim((string)($row['item_name'] ?? '')),
                                        'quantity' => 0,
                                        'unit_price' => (float)($row['unit_price'] ?? 0),
                                    ];
                                }
                                $grouped[$groupKey]['quantity']++;
                            }

                            $compliance = new MraEisCompliance($conn);
                            $eisWarehouseBranchId = $systemSettings->eisWarehouseBranchId();
                            $eisResult = $compliance->prepareInformalPurchaseBatch($eisWarehouseBranchId, array_values($grouped), $receivingMeta, (int)$_SESSION['user_id']);
                            $message .= "<div class='alert alert-info mt-2'>MRA EIS: " . htmlspecialchars($eisResult['status']) . ($eisResult['last_error'] ? ' - ' . htmlspecialchars($eisResult['last_error']) : '.') . "</div>";
                            } catch (Throwable $e) {
                                error_log('MRA EIS informal purchase queueing failed: ' . $e->getMessage());
                                $message .= "<div class='alert alert-warning mt-2'>MRA EIS queueing failed - see logs.</div>";
                            }
                        }

                        if (file_exists($temp_file_path)) {
                            unlink($temp_file_path);
                        }


                        unset($_SESSION['temp_excel_file']);
                        unset($_SESSION['excel_import_type']);
                        unset($_SESSION['excel_receiving_meta']);


                        $preview_data = [];

                    } else {

                        $errorMessage = $inventory->getLastError();
                        $message = "<div class='alert alert-danger'>Failed to add items to warehouse: " . htmlspecialchars($errorMessage) . "</div>";
                        error_log("Warehouse import failed: " . $errorMessage);
                    }
                } catch (Exception $e) {
                    $message = "<div class='alert alert-danger'>Error during warehouse import: " . htmlspecialchars($e->getMessage()) . "</div>";
                    error_log("Exception during warehouse import: " . $e->getMessage());
                }
            } else {

                $errors = $excelImport->getErrors();
                $message = "<div class='alert alert-danger'>File processing failed: " . implode('<br>', $errors) . "</div>";
            }
        } else {
            $message = "<div class='alert alert-danger'>Temporary file not found. Please upload the file again.</div>";
        }


        $preview_data = [];
    }
}
?>

<?php include __DIR__ . '/../../includes/header.php'; ?>
<link rel="stylesheet" href="../../assets/css/choose_form.css">
    <style>
        .preview-table {
            margin-top: 20px;
        }
        .preview-table th, .preview-table td {
            padding: 8px;
            text-align: left;
        }
        .file-upload-container {
            margin-bottom: 20px;
        }
        .import-options {
            margin-bottom: 20px;
        }
    </style>

    <a href="choose_warehouse_form.php?branch_id=7" class="back-link">← Back to Form Selection</a>

    <div class="container mt-5">
        <h1>Import Inventory from Excel for <?php echo htmlspecialchars($branch_name); ?></h1>

        <?php echo $message; ?>

        <?php if (empty($preview_data)): ?>

        <form action="" method="post" enctype="multipart/form-data">
            <input type="hidden" name="branch_id" value="7">

            <?php if ($imsOnly): ?>
                <div class="alert alert-info">IMS Only is enabled. Imported items will be saved locally without creating or submitting any MRA EIS transaction.</div>
            <?php else: ?>
            <div class="mb-4">
                <h4>Receiving Details (MRA EIS)</h4>
                <p class="text-muted">Queued to MRA EIS as an informal purchase (goods receiving) once the import is confirmed.</p>
                <div class="row g-3">
                    <div class="col-md-4">
                        <label class="form-label" for="supplier_id">Supplier</label>
                        <select class="form-control" name="supplier_id" id="supplier_id">
                            <option value="">Select supplier...</option>
                            <?php foreach ($supplierList as $supplierOption): ?>
                                <option value="<?php echo (int)$supplierOption['supplier_id']; ?>">
                                    <?php echo htmlspecialchars($supplierOption['supplier_name']); ?><?php echo empty($supplierOption['eis_supplier_id']) ? ' (no EIS ID set)' : ''; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label" for="delivery_note_number">Delivery Note Number</label>
                        <input type="text" class="form-control" name="delivery_note_number" id="delivery_note_number">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label" for="purchase_order_number">Purchase Order Number</label>
                        <input type="text" class="form-control" name="purchase_order_number" id="purchase_order_number">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label" for="received_by">Received By</label>
                        <input type="text" class="form-control" name="received_by" id="received_by" value="<?php echo htmlspecialchars($_SESSION['username'] ?? ''); ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label" for="unit_of_measure">Unit of Measure</label>
                        <input type="text" class="form-control" name="unit_of_measure" id="unit_of_measure" value="EACH">
                    </div>
                    <div class="col-md-3 d-flex align-items-end">
                        <div class="form-check">
                            <input type="checkbox" class="form-check-input" name="is_finished_product" id="is_finished_product" value="1" checked>
                            <label class="form-check-label" for="is_finished_product">Finished product</label>
                        </div>
                    </div>
                    <div class="col-md-5">
                        <label class="form-label" for="notes">Notes</label>
                        <input type="text" class="form-control" name="notes" id="notes">
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <div class="import-options">
                <h4>Select Import Type:</h4>
                <div class="form-check">
                    <input class="form-check-input" type="radio" name="import_type" id="simple" value="simple" checked>
                    <label class="form-check-label" for="simple">
                        Simple Import (Basic item details only)
                    </label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="radio" name="import_type" id="detailed" value="detailed">
                    <label class="form-check-label" for="detailed">
                        Detailed Import (Including technical specifications)
                    </label>
                </div>
            </div>

            <div class="file-upload-container">
                <h4>Upload Excel File:</h4>
                <div class="mb-3">
                    <input type="file" class="form-control" name="excel_file" accept=".xlsx,.xls,.csv" required>
                    <div class="form-text">Supported formats: .xlsx, .xls, .csv</div>
                </div>

                <div class="mb-3">
                    <button type="submit" class="btn btn-primary">Upload and Preview</button>
                </div>
            </div>

            <div class="mb-3">
                <h4>Template Instructions:</h4>
                <p>Your Excel file should have the following columns:</p>

                <div id="simple-instructions">
                    <h5>For Simple Import:</h5>
                    <ul>
                        <li><strong>item_name</strong> (required): Name of the item</li>
                        <li><strong>unique_code</strong> (optional): Unique identifier for the item. If not provided, will be auto-generated.</li>
                        <li><strong>item_details</strong> (optional): Additional details for the item</li>
                        <li><strong>condition_status</strong> (required): Condition of the item (New, Used, Refurbished, etc.)</li>
                        <li><strong>category</strong> (required): item category</li>                        
                        <li><strong>unit_price</strong> (required): Price per unit</li>
                        <li><strong>quantity</strong> (required): Number of items</li>
                        <li><strong>warranty_months</strong> (optional): Warranty period in months</li>
                    </ul>
                </div>

                <div id="detailed-instructions" style="display: none;">
                    <h5>For Detailed Import:</h5>
                    <ul>
                        <li><strong>item_name</strong> (required): Name of the item</li>
                        <li><strong>unique_code</strong> (optional): Unique identifier for the item. If not provided, will be auto-generated.</li>
                        <li><strong>item_details</strong> (optional): Additional details for the item</li>
                        <li><strong>condition_status</strong> (required): Condition of the item (New, Used, Refurbished, etc.)</li>
                        <li><strong>category</strong> (required): item category</li>
                        <li><strong>unit_price</strong> (required): Price per unit</li>
                        <li><strong>quantity</strong> (required): Number of items</li>
                        <li><strong>warranty_months</strong> (optional): Warranty period in months</li>
                        <li><strong>serial_number</strong> (optional): Serial number</li>
                        <li><strong>technical_specs</strong> (optional): Technical specifications</li>
                    </ul>
                </div>
            </div>
        </form>
        <?php else: ?>

        <div class="preview-container">
            <h3>Data Preview</h3>
            <p>Please review the data before importing:</p>

            <table class="table table-striped preview-table">
                <thead>
                    <tr>
                        <th>Unique Code</th>
                        <th>Item Name</th>
                        <th>Item Details</th>
                        <th>Condition</th>
                        <th>Category</th>
                        <th>Unit Price</th>
                        <?php if ($import_type === 'detailed'): ?>
                        <th>Serial Number</th>
                        <?php endif; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($preview_data as $item): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($item['unique_code']); ?></td>
                        <td><?php echo htmlspecialchars($item['item_name']); ?></td>
                        <td><?php echo htmlspecialchars($item['item_details'] ?? ''); ?></td>
                        <td><?php echo htmlspecialchars($item['condition_status']); ?></td>
                        <td><?php echo htmlspecialchars($item['category']); ?></td>
                        <td><?php echo htmlspecialchars($item['unit_price']); ?></td>
                        <?php if ($import_type === 'detailed'): ?>
                        <td><?php echo htmlspecialchars($item['serial_number'] ?? ''); ?></td>
                        <?php endif; ?>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <form action="" method="post">
                <input type="hidden" name="confirm_import" value="1">
                <input type="hidden" name="import_type" value="<?php echo htmlspecialchars($import_type); ?>">
                <button type="submit" class="btn btn-success">Confirm Import</button>
                <a href="import_excel.php" class="btn btn-secondary">Cancel</a>
            </form>
        </div>
        <?php endif; ?>
    </div>

    <script>
        $(document).ready(function() {

            $('input[name="import_type"]').change(function() {
                if ($(this).val() === 'simple') {
                    $('#simple-instructions').show();
                    $('#detailed-instructions').hide();
                } else {
                    $('#simple-instructions').hide();
                    $('#detailed-instructions').show();
                }
            });
        });
    </script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
