<?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);

/* INPUT */
$input = json_decode(file_get_contents('php://input'), true);

if (!$input || empty($input['type']) || empty($input['rows']) || !is_array($input['rows'])) {
    json_response(false, 'Invalid request.', [], 400);
}

$type = $input['type'];
$rows = $input['rows'];

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

/* Row limit */
if (count($rows) > 1000) {
    json_response(false, 'Row limit exceeded (max 1000).', [], 400);
}

$pdo->beginTransaction();

try {

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

        $stmt = $pdo->prepare("
            INSERT INTO companies (company_name, rsp_id, type, status, created_at)
            VALUES (?, ?, ?, ?, NOW())
        ");

        foreach ($rows as $row) {

            if (empty($row['company_name']) || empty($row['rsp_id']) || empty($row['type'])) {
                throw new Exception('Invalid company row.');
            }

            $rsp_id = (int)$row['rsp_id'];

            /* Tenant Isolation */
            if (!empty($user['rsp_id']) && $rsp_id !== (int)$user['rsp_id']) {
                throw new Exception('RSP isolation violation.');
            }

            if (!in_array($row['type'], ['fleet', 'sp'], true)) {
                throw new Exception('Invalid company type.');
            }

            $stmt->execute([
                trim($row['company_name']),
                $rsp_id,
                $row['type'],
                $row['status'] ?? 'active'
            ]);
        }
    }

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

        $stmt = $pdo->prepare("
            INSERT INTO users
            (first_name, last_name, email, password_hash, role, company_id, status, created_at)
            VALUES (?, ?, ?, ?, ?, ?, 'active', NOW())
        ");

        $emailCheck = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email = ?");
        $companyCheck = $pdo->prepare("SELECT rsp_id FROM companies WHERE id = ?");

        $allowed_roles = [
            'rsp_admin',
            'fleet_controller',
            'sp_admin',
            'artisan'
        ];

        foreach ($rows as $row) {

            if (empty($row['email']) || empty($row['role']) || empty($row['company_id'])) {
                throw new Exception('Invalid user row.');
            }

            $email = strtolower(trim($row['email']));

            /* Duplicate email */
            $emailCheck->execute([$email]);
            if ((int)$emailCheck->fetchColumn() > 0) {
                throw new Exception("Duplicate email: {$email}");
            }

            /* Role validation */
            if (!in_array($row['role'], $allowed_roles, true)) {
                throw new Exception('Invalid role assignment.');
            }

            $company_id = (int)$row['company_id'];

            /* Tenant Isolation */
            if (!empty($user['rsp_id'])) {

                $companyCheck->execute([$company_id]);
                $companyRsp = $companyCheck->fetchColumn();

                if (!$companyRsp || (int)$companyRsp !== (int)$user['rsp_id']) {
                    throw new Exception('RSP isolation violation.');
                }
            }

            $temp_password = bin2hex(random_bytes(4));
            $hash = password_hash($temp_password, PASSWORD_DEFAULT);

            $stmt->execute([
                trim($row['first_name'] ?? ''),
                trim($row['last_name'] ?? ''),
                $email,
                $hash,
                $row['role'],
                $company_id
            ]);
        }
    }

    $pdo->commit();

} catch (Throwable $e) {

    $pdo->rollBack();
    json_response(false, $e->getMessage(), [], 400);
}

json_response(true, 'Bulk upload completed securely.');