<?php
require_once __DIR__ . '/../config.php';
requireRole(['admin']);
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../lib/logic.php';

use PhpOffice\PhpSpreadsheet\IOFactory;

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(['error' => 'Invalid request method'], 405);
}

if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
    jsonResponse(['error' => 'No file uploaded'], 400);
}

$allowedTypes = ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel'];
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mimeType = $finfo->file($_FILES['file']['tmp_name']);

if (!in_array($mimeType, $allowedTypes) && !in_array($_FILES['file']['type'], $allowedTypes)) {
    if (pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION) !== 'xlsx') {
        jsonResponse(['error' => 'Invalid file type. Only XLSX files are allowed'], 400);
    }
}

$dryRun = ($_POST['dry_run'] ?? '1') === '1';

try {
    $spreadsheet = IOFactory::load($_FILES['file']['tmp_name']);
    $sheet = $spreadsheet->getActiveSheet();
    $data = $sheet->toArray();

    if (empty($data)) {
        jsonResponse(['error' => 'Empty file'], 400);
    }

    $result = importInventoryTransactions($data, $dryRun);

    if ($dryRun) {
        jsonResponse([
            'message' => 'Dry run complete. Review the results below.',
            'would_import' => $result['success'],
            'would_skip' => $result['skipped'],
            'errors' => $result['errors']
        ]);
    } else {
        jsonResponse([
            'message' => 'Import complete',
            'imported' => $result['success'],
            'skipped' => $result['skipped'],
            'errors' => $result['errors']
        ]);
    }
} catch (Exception $e) {
    jsonResponse(['error' => 'Failed to process file: ' . $e->getMessage()], 500);
}