<?php
header('Content-Type: application/json');

require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Inventory.php';
require_once __DIR__ . '/../../classes/Logger.php';

$autoloader = __DIR__ . '/../../vendor/autoload.php';
if (file_exists($autoloader)) {
    require_once $autoloader;
}

$tempPath = null;

try {
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    if (empty($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'error' => 'Login required.']);
        exit;
    }

    $database = new Database();
    $conn = $database->getConnection();
    $auth = new Auth($conn);
    if (!$auth->isSuperAdmin($_SESSION['user_id'])) {
        echo json_encode(['success' => false, 'error' => 'Unauthorized.']);
        exit;
    }

    if (!class_exists('\PhpOffice\PhpSpreadsheet\IOFactory')) {
        echo json_encode(['success' => false, 'error' => 'PhpSpreadsheet library is not installed.']);
        exit;
    }

    $stockId = (int)($_POST['stock_id'] ?? 0);
    $branchId = (int)($_POST['branch_id'] ?? 0);
    if ($stockId <= 0 || $branchId <= 0) {
        echo json_encode(['success' => false, 'error' => 'A stock item and destination branch must be selected before uploading.']);
        exit;
    }

    if (empty($_FILES['excel_file']) || $_FILES['excel_file']['error'] !== UPLOAD_ERR_OK) {
        echo json_encode(['success' => false, 'error' => 'No file was uploaded.']);
        exit;
    }

    $extension = strtolower(pathinfo($_FILES['excel_file']['name'], PATHINFO_EXTENSION));
    if (!in_array($extension, ['xlsx', 'xls', 'csv'], true)) {
        echo json_encode(['success' => false, 'error' => 'Invalid file format. Upload .xlsx, .xls, or .csv.']);
        exit;
    }

    $tempDir = __DIR__ . '/../../temp';
    if (!file_exists($tempDir)) {
        mkdir($tempDir, 0777, true);
    }
    $tempPath = $tempDir . '/' . uniqid('unique_code_') . '.' . $extension;
    if (!move_uploaded_file($_FILES['excel_file']['tmp_name'], $tempPath)) {
        echo json_encode(['success' => false, 'error' => 'Failed to store the uploaded file.']);
        exit;
    }

    $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($tempPath);
    $worksheet = $spreadsheet->getActiveSheet();
    $highestRow = $worksheet->getHighestRow();
    $highestColumn = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($worksheet->getHighestColumn());

    $headers = [];
    for ($col = 1; $col <= $highestColumn; $col++) {
        $headers[$col] = strtolower(trim((string)$worksheet->getCellByColumnAndRow($col, 1)->getValue()));
    }
    $itemIdCol = array_search('item_id', $headers, true);
    $codeCol = array_search('unique_code', $headers, true);
    $detailsCol = array_search('item_details', $headers, true);
    if ($itemIdCol === false || $codeCol === false) {
        echo json_encode(['success' => false, 'error' => 'The file must have "item_id" and "unique_code" columns - use the downloaded template.']);
        exit;
    }

    // Scope to items belonging to both this barcode's stock row AND the chosen branch, so a
    // stray/incorrect item_id in the sheet can never touch another branch's copy of this barcode.
    // Items already sold from this branch are excluded - they're no longer editable stock.
    $scopeStmt = $conn->prepare("
        SELECT item_id FROM items i
        WHERE i.source_eis_warehouse_stock_id = :stock_id AND i.current_location_id = :branch_id
          AND NOT EXISTS (
              SELECT 1 FROM sold_items s
              WHERE s.item_id = i.item_id AND s.branch_id = i.current_location_id
          )
    ");
    $scopeStmt->execute([':stock_id' => $stockId, ':branch_id' => $branchId]);
    $allowedItemIds = array_flip($scopeStmt->fetchAll(PDO::FETCH_COLUMN));

    if (empty($allowedItemIds)) {
        echo json_encode(['success' => false, 'error' => 'No linked items were found for that barcode in the selected branch.']);
        exit;
    }

    $logger = new Logger($conn, $_SESSION['user_id'], $_SESSION['username'], $_SESSION['role']);
    $inventory = new Inventory($conn, $logger);

    $updated = 0;
    $skipped = [];
    for ($row = 2; $row <= $highestRow; $row++) {
        $itemIdCell = $worksheet->getCellByColumnAndRow($itemIdCol, $row)->getValue();
        $codeCell = trim((string)$worksheet->getCellByColumnAndRow($codeCol, $row)->getValue());

        if ($itemIdCell === null || trim((string)$itemIdCell) === '') {
            continue;
        }
        $itemId = (int)$itemIdCell;

        if ($codeCell === '') {
            $skipped[] = "Row {$row}: empty unique_code";
            continue;
        }
        if (!isset($allowedItemIds[$itemId])) {
            $skipped[] = "Row {$row}: item #{$itemId} is not a linked item for this barcode/branch";
            continue;
        }
        $updateData = ['unique_code' => $codeCell];
        if ($detailsCol !== false) {
            $updateData['item_details'] = trim((string)$worksheet->getCellByColumnAndRow($detailsCol, $row)->getValue());
        }

        if (!$inventory->updateItem($itemId, $updateData)) {
            $skipped[] = "Row {$row}: item #{$itemId} - " . ($inventory->getLastError() ?: 'update failed');
            continue;
        }
        $updated++;
    }

    echo json_encode(['success' => true, 'updated' => $updated, 'skipped' => $skipped]);
} catch (Throwable $e) {
    error_log('MRA EIS bulk unique code upload failed: ' . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'Server error while processing the file.']);
} finally {
    if ($tempPath && file_exists($tempPath)) {
        unlink($tempPath);
    }
}
