<?php

require_once __DIR__ . '/../../core/api_bootstrap.php';
require_once __DIR__ . '/../../core/permissions.php';

/* METHOD */
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_response(false, 'Invalid request method.', [], 405);
}

/* AUTH */
$user = authenticate($pdo);

/* RBAC */
require_permission($user, 'bulk_upload', 'create', $pdo);

/* FILE CHECK */
if (!isset($_FILES['file']) || !isset($_POST['type'])) {
    json_response(false, 'File and type required.', [], 400);
}

$type = $_POST['type'];

if (!in_array($type, ['companies', 'users'], true)) {
    json_response(false, 'Invalid upload type.', [], 400);
}

/* FILE VALIDATION */
$file = $_FILES['file'];

if ($file['error'] !== UPLOAD_ERR_OK) {
    json_response(false, 'File upload failed.', [], 400);
}

/* Size limit: 2MB */
if ($file['size'] > 2 * 1024 * 1024) {
    json_response(false, 'File too large (max 2MB).', [], 400);
}

/* MIME validation */
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $file['tmp_name']);
finfo_close($finfo);

$allowed_mime = [
    'text/plain',
    'text/csv',
    'application/vnd.ms-excel'
];

if (!in_array($mime, $allowed_mime, true)) {
    json_response(false, 'Invalid file type.', [], 400);
}

/* PARSE */
$rows = [];
$errors = [];
$rowLimit = 1000;
$rowCount = 0;

if (($handle = fopen($file['tmp_name'], 'r')) !== false) {

    $headers = fgetcsv($handle);

    if (!$headers) {
        json_response(false, 'Invalid CSV header.', [], 400);
    }

    while (($data = fgetcsv($handle)) !== false) {

        $rowCount++;
        if ($rowCount > $rowLimit) {
            $errors[] = "Row limit exceeded (max {$rowLimit}).";
            break;
        }

        if (count($headers) !== count($data)) {
            $errors[] = "Row {$rowCount} column mismatch.";
            continue;
        }

        $row = array_combine($headers, $data);

        /* CSV Injection Sanitization */
        foreach ($row as &$value) {
            if (preg_match('/^[=\-+@]/', $value)) {
                $value = "'" . $value;
            }
        }

        /* VALIDATION */
        if ($type === 'companies') {

            if (empty($row['company_name']) || empty($row['rsp_id']) || empty($row['type'])) {
                $errors[] = "Row {$rowCount} missing required fields.";
            }

            /* RSP Isolation */
            if (!empty($user['rsp_id']) && (int)$row['rsp_id'] !== (int)$user['rsp_id']) {
                $errors[] = "Row {$rowCount} violates RSP isolation.";
            }
        }

        if ($type === 'users') {

            if (empty($row['email']) || empty($row['role']) || empty($row['company_id'])) {
                $errors[] = "Row {$rowCount} missing required fields.";
            }

            /* Company ownership check */
            if (!empty($user['rsp_id'])) {

                $stmt = $pdo->prepare("SELECT rsp_id FROM companies WHERE id = ?");
                $stmt->execute([(int)$row['company_id']]);
                $companyRsp = $stmt->fetchColumn();

                if (!$companyRsp || (int)$companyRsp !== (int)$user['rsp_id']) {
                    $errors[] = "Row {$rowCount} violates RSP isolation.";
                }
            }
        }

        $rows[] = $row;
    }

    fclose($handle);
}

json_response(true, 'Preview generated.', [
    'rows'   => $rows,
    'errors' => $errors,
    'valid'  => count($errors) === 0
]);